Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs(repair): fence repair during a sync, owner_unavailable reasons, CHANGELOG and behavior-change rows (#6278 PR 2)
garrytan25e034891ed1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d37ffc8bbf..2ec7bbfa0c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,49 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.110.0] - 2026-10-08++**Fence repair and chronicle now run while a sync is in progress, and a refused owner check says exactly which host or state is in the way.**++On a managed brain, `gbrain repair fences` used to skip a whole source as soon as one managed sync of it was unfinished, and a long catch-up is unfinished for most of an hour. The held fences it should have cleared stayed held until the sync ended. Now the repair looks at each file on its own: only a file that a write in flight or the running sync's frozen list still names waits, and every other candidate, held files included, is repaired and committed during the catch-up. A file the sync held earlier is never considered busy, because the sync retries a held file only once its bytes change, and the repair is what changes them.++The other refusal from the same report, `fence_repair` and chronicle saying `owner_unavailable` with no further word, now names the condition. The common one on a single machine is `host_mismatch`: a maintenance worker started with a different `GBRAIN_HOME` or user than the shell that ran the sync reads a different identity file and is, to the brain, another host. The message prints both host ids and, for a local caller, the identity file this process read, and tells the agent not to retry. A worktree draining for a transfer or recovering from a clone is a short wait and says so.++### How to use it++```bash+gbrain repair fences --source <id> # preview: files a running sync still names are listed as sync_in_progress, the rest are planned+gbrain repair fences --source <id> --apply --expect <hash> # applies the previewed set while the sync runs; a file the sync froze since the preview is skipped, not written+gbrain errors owner_unavailable # the reasons and what each one asks of you+gbrain sources writer status --source <id> --json # read-only: the owner host id, the worktree state and this host's registration+```++### What you see++| Where | What changed |+|---|---|+| `gbrain repair fences` during a sync | Per-file `sync_in_progress` instead of a source-wide skip. Busy: a file a queued, running or recovering write names (both ends of a rename, and a finished write whose recovery is still open), and a file still ahead in the running sync's frozen manifest. Not busy: a held file. When the busy set cannot be read at all, every candidate waits and the hold's text says why. |+| The busy check | Runs when the plan is made, again when each item is applied, and once more when the file write is admitted, because a sync can start while the repair waits on its model call. A write caught there is skipped, nothing is written, and the model attempt is not counted against the file. |+| `owner_unavailable` | Carries `reason`: `host_mismatch` (both ids' first 8 characters; local callers also see the `host.json` path; `retryable: false`), `transfer_in_progress` and `clone_in_progress` (`fix.next: wait`, 30 s), `binding_missing`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`. The fix is always the read-only writer status; nothing claims or transfers ownership to run maintenance. Remote callers get the ids, never a local path. |+| Fence holds | A hold the owner check refused records the reason (`host_mismatch`, `transfer_in_progress`, ...) instead of a bare `owner_unavailable`; `gbrain sources status` and doctor route all of them as owner-host holds with the exact command. |+| The maintenance `fence_repair` phase, chronicle, fact-fence adoption | The phase repairs under the same per-file rule while a sync runs; every maintenance writer's owner check refuses with the same reasons when this is not the owner host. |++### Things to watch++- **A file still ahead in the sync waits on purpose.** Repairing it would change the bytes the sync is about to admit, and the sync would then refuse that entry. The next repair run, or the maintenance phase, picks it up once the sync has passed it.+- **`host_mismatch` is not a retry.** If the sync shell and the maintenance worker report different host ids, point both at one `GBRAIN_HOME`. Do not copy or regenerate `host.json`; a new identity orphans the ownership recorded for the old one.+- **A doctor check for a split host identity is not in this release.** It waits on evidence from the field; the refusal text already carries both ids.++### Itemized changes++- `src/core/persistence/owner-refusal.ts`: the `owner_unavailable` reasons matrix. `checkOwner` names the first failing condition in a fixed order or returns the usable binding; `ownerRefusal` / `ownerUnavailableError` give each reason its message, `why`, actor (`provider` for the two in-progress reasons, so `fix.next` renders `wait`; `host_admin` otherwise), the read-only `gbrain sources writer status --source <id> --json` as fix and verify, and `retryable` (`host_mismatch` false). `maintenancePreflight` (`prepared-maintenance.ts`), `loadFenceSource` (`fence-repair/repair-io.ts`) and `managedRepairRoot` (`file-repair.ts`) refuse through it. `OperationError` and `opError` gain a site-level `retryable` the envelope carries.+- `src/core/persistence/repair-busy.ts`: `loadRepairBusySet` (in-flight requests with rename endpoints and open recoveries, plus the not-yet-admitted entries of every unfinished `managed-sync` cursor of the incarnation from its frozen manifest, held paths excluded; fails closed), `repairBusy`, `repairBusyMessage`, `repairBusyError` (`sync_in_progress`, reasons `candidate_in_flight` / `busy_set_unreadable`). `repair/fences.ts` drops the source-wide `syncUnfinished` skip and checks the set at plan and apply; `submitManagedFileRepair` checks it again at admission and `writeFenceRepair` reports that refusal as `sync_in_progress` (the Tier 3 attempt memo records it as transient).+- Registry: `owner_unavailable` gains `reasons`, `why`, a docs anchor (`troubleshooting.md#owner-unavailable`) and a suggestion; `sync_in_progress` gains `reasons` and `why`. `FENCE_REASONS` and the hold-fix OWNER list gain `host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing` (`owner_unavailable` stays the fallback for a source with no binding).+- Docs: `docs/guides/repair.md` (fence repair during a sync, owner reasons), `docs/guides/troubleshooting.md` (the `owner_unavailable` table and symptom rows), `docs/guides/write-refusals.md` rows, regenerated `docs/guides/error-codes.md`, KEY_FILES entries, two behavior-change rows.+- Tests: `test/owner-refusal.test.ts` (the matrix, every preflight condition on a claimed worktree, the HTTP envelope without a local path), `test/repair-busy.test.ts`, `test/repair-fences.test.ts` (far-ahead manifest, held path not busy, admission race during the model wait, host mismatch and worktree states), `test/repair-fences-during-catchup.test.ts` with its Postgres arm `test/e2e/repair-fences-during-catchup-postgres.test.ts` (a real catch-up paused at a sync member's preparation and between two entries).++Fixes the third problem of #6278 (`fence_repair` and chronicle refusing with `owner_unavailable` while a sync runs); the first two, the stalled preparation and the fact-fence adoption failures, shipped in the previous release.+## [0.60.109.0] - 2026-10-08**A managed catch-up no longer stalls on one stuck write: the write is cut off, its file is held, and the rest of the source keeps syncing.**diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex fd78e33818..b6a0a21feb 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -50,6 +50,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 does not own (`owner_unavailable`) or that are mid-sync (`sync_in_progress`), 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/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/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 3354c88f8b..ffd5299446 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -12,12 +12,12 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an- `src/core/fence-repair/{normalize,structure,content,rules}.ts` — #6188 Tier 1. `normalizeFences(page, ctx)` returns a page that compiles plus location-only fixes and residual issues; a page whose fences compile comes back as the same object, and only edited cells, markers and headers change (no table is re-rendered). `structure.ts` closes a fence only when nothing but blank lines follows its last row and fixes two-dash takes markers; `content.ts` rewrites headers into canonical order with header-level defaults and renumbers prior-aware across both sections (`nextFreeRowNum`: above every fence and stored number; hidden rows never move); `rules.ts` holds the cell rules (kind map with the original word kept in `context`, enum and holder synonyms, percent confidence). `safeNormalizeFences` turns a throw into residual `normalizer_failed`. Tests: `test/fence-repair-normalize.test.ts`, `test/fence-repair-fixtures.test.ts`.- `src/core/fence-repair/{validate,validate-cells,page-checks}.ts` — #6188 the one gate every tier's output passes before a write: (a) compiles, (e) row count and containment, (b) claims, (c) existing row numbers, (d) visibility only tightens, (f) per-row cell preservation with rule-produced changes only, (g) nothing the privacy boundary hid is shown; gates (b), (c), (e) and (f) read the raw-row view. `isFenceFixedPoint` is E14. `page-checks.ts` holds `strictFailures` (gate a, the projection's three checks) and `exposedLines` (gate g). Tests: `test/fence-repair-validate.test.ts`.- `src/core/fence-repair/{tier1,import-step,config,report}.ts` — #6188 Tier 1 on every write path. `fenceStep(page, ctx, { normalize })` is the step the coordinated screen, `importFromContent` and the append verbs share: no work beyond a marker substring check for a page with no fence, one shared scan when the fences compile, and `normalized` only when the validator passes and the output is a fixed point; otherwise `residual` with issues and the refusal location (`fenceIssuesWire` is the D18 `fence_issues` shape). `import-step.ts`: `applyImportFences` runs inside `importFromContent` before the remote hidden-row merge and withdrawal preservation (E7), reusing the screen's verdict unless hidden rows or a planned `renumber` need the database (stored rows load only then); `normalizeTargetFences` normalizes an append verb's target page or throws `target_fence_malformed` for a residual in its own fence kind; `normalizePageFences` serves synthesize verify. `config.ts`: `fences.normalize` (default on, read only when there is something to fix) and the model-repair caps `fences.repair.max_usd_per_page` (0.05) and `fences.repair.max_usd_per_day` (1.00), validated at `config set` as non-negative USD (0 = no model spend) and read by `readFenceRepairCaps` (stored value = a user cap). `report.ts`: the one `fences_normalized` shape (count, by_class, writers, sample paths for local callers, coaching fix), the `fence_normalized` coaching notice and the per-file import tally (`fence_issues` for lenient imports). Tests: `test/fence-write-verbs.test.ts`, `test/persistence-sync-fence-holds.test.ts`, `test/fence-normalize-overhead.slow.test.ts`.-- `src/core/fence-repair/hold-fix.ts` — #6188 (D16, D17, E35, Codex CEO #7) what an `invalid_fence` sync hold tells an agent. `readFenceAutoRepair` (two reads: `fences.repair.enabled`, `fences.repair.llm` and `autopilot.last_global_at` from `config`, plus the last completed `autopilot-global-maintenance` job) says whether the maintenance run repairs fences by itself (active within `FENCE_MAINTENANCE_ACTIVE_MS`, 24 h). `fenceHoldStatus` derives the state from the reason table and `meta.fence_repair`: `auto` (no action needed, the read-only preview), `apply` (preview, then apply), `manual` (manual-only reason, gate rejection or a model failure the run does not retry: the preview names the edit, then the sync), `paid` (`budget_exhausted`, `llm_disabled`, `no_pricing`: the exact config or `pricing set` command with consent `paid`), `owner` (the owner-host command, actor `host_admin`). `fenceHoldFix` is the local fix (`gbrain repair fences --source <id> --only <path>`), `fenceHoldRelay` the remote one (`tell_user_to_run`, no path), `fenceHoldLocation` the D16 object, `fenceFileLine` the file line of a section line. Location only. Tests: `test/fence-hold-surfaces.test.ts`, `test/sync-hold-surfaces.test.ts`.+- `src/core/fence-repair/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/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`: managed owner root (or `ownerElsewhere`), legacy checkout, mirror flag, unfinished managed sync cursor and the paths/slugs pending writes name. `readFenceTarget`: a held or walked file from the checkout (UTF-8 only, confined, slug from the page by origin, hold or path) or the stored page; `spliceFileSections` puts the repaired sections back into the file by locating each changed line range with the fewest unique context lines and refuses unless the result parses back to exactly those sections. `writeFenceRepair`: managed → `submitManagedFileRepair` (bytes bound to the before-hash, page revision and publication digest; refused imports and canonical overlays are not written); legacy → confined path re-hashed (`changed_since_read`), backed up under `~/.gbrain/backups/fences/<run>/`, written, `importFromFile` (restored from the backup if it refuses), hold cleared, and an "uncommitted fence repair" notice (`uncommitted.ts`, op `fence-repair-uncommitted`, purge-exempt) with the exact `git add`/`git commit` step, dropped on read once the path is committed; db and mirror → a revision-bound `put_page` (mirror: database-only, hold cleared). Every write carries a `FenceRepairReceipt` (`receipt.ts`: actor `fence-repair`, tier, classes, rows, columns, model, before/after sha256, cost; `parseFenceRepairReceipt` rejects anything malformed) and clears the census parts of the key. Tests: `test/repair-fences.test.ts`.+- `src/core/fence-repair/{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`.- `src/core/fence-repair/attempts.ts` — #6188 attempt claims and the attempt memo for paid (Tier 3) fence repairs, one `op_checkpoints` row per candidate (op `fence-repair-attempt`) changed only by compare-and-swap on a record version: `claimed` → `dispatched` → `settled` → `published` | `rejected` | `transient`, at most one paid call plus one corrective re-ask per claim. A rejected or published memo (content sha256, model, fence rules version, prompt version) is not claimed again until one changes; transient failures do not consume it; an expired lease is taken over (a stale dispatch counts a crash, two reject the memo). Records carry location and reason codes and their source incarnation, so the purge keeps them while it lives. Tests: `test/fence-repair-attempts.test.ts` (+ Postgres e2e).- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 4aa0c86e9d..c22033daca 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -16,7 +16,7 @@ Connector ingestion, item holds, checkpoint validation and the single-write fast- `src/core/persistence/onboarding.ts` + `legacy-locks.ts` + `physical-root-recovery.ts` — read-only source onboarding states; exact same-host dead-lock cleanup under explicit activation opt-in; and state-bound same-owner root repair using a durable manifest and token-verified temporary stamp. `physical-root.ts` `restampPhysicalRoot` handles a filesystem device id that changed while the owner token, brain, worktree, root, inode and a non-zero birth time still match (macOS can renumber `st_dev` across reboots): under the caller's outside-root native lock, one transaction verifies owner host, brain and host binding and rewrites the recorded self-transfer copies and retained topology staging identities (each only while it still names the old device); after commit the stamp and the reservation's initial device are rewritten and the event is logged, so an interruption between the two leaves a device-only change the next locked acquisition finishes. Ownership markers inside a retained topology clone stage are not re-stamped; an interrupted clone recovery that spans a device renumbering still needs source recovery. `assertPhysicalRoot` stays read-only; zero birth time or any other difference keeps the refusal. `--self-transfer` prepare/accept requires separate fresh reviewed state, preserves original reservation owner evidence and refuses uncertain records. Tests: `test/persistence-onboarding.test.ts`, `test/persistence-admin-recovery.test.ts`, `test/persistence-container-preflight.test.ts`.-- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests. A failed atom batch's resume refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify.+- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. A failed atom batch's resume refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify.- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.Atom completion admits replacement and revision-pinned stale-atom deletion children together.Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 554660ceea..f991ca5132 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/repair/ontology-facts.ts` — `gbrain repair ontology-facts` (#6264), explicit-only and preview-bound (`--apply --expect <hash>`). `classifyOntologyFacts` (read-only; also doctor `ontology_facts_fenced`) takes ontology rows (`dimension IS NOT NULL`) carrying the pre-fix fence step's signature, a `row_num` or a `source_markdown_slug` that differs from `source` (`mergeOntologyFact` writes them equal and never sets `row_num`), and classes each `fenced` or `retired`, or excluded as `withdrawn` (`fact_withdrawals`), `consolidated` or `duplicate` (restoring would collide with the ontology dedup key). The apply sets `row_num` NULL, `source_markdown_slug = source` and `expired_at` NULL in one statement that rechecks row number, page, expiry and the dedup key (`changed_since_preview` otherwise), through `coordinatedDatabaseWrite('ontology_propose')` on the entity and page keys on a managed brain or one maintenance transaction otherwise; the withdrawal trigger re-expires a claim forgotten after the preview (`withdrawn`). Page text is never rewritten. Tests: `test/ontology-fence-sweep.test.ts`.- `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 non-owner host is `owner_unavailable`, an unfinished managed sync cursor or a pending write naming it is `sync_in_progress` (E9); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, no measured model with a key and `models.fence_repair` unset → `no_measured_model`, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `resolveFenceRepairModel` (`fence-repair/model.ts`: `models.fence_repair`, else the first measured model with a key, else none). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, a corrective re-ask only after gate (a) or (e)); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.+- `src/core/repair/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/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 5d456e96dc..19e04ccd3e 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -20,7 +20,7 @@- **`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.- **`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`. `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). 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/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`. #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`.- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex 87b14a3672..76284b7747 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -13,6 +13,8 @@ sync-holds, sync-drain, deactivation, source lifecycle) are in- `src/core/persistence/claim-phase.ts` — #6176 / #6278: the phase and step a running write request's claim is in. `startClaimPhase`/`enterClaimPhase` keep a per-claim `ClaimPhaseClock` in the consumer (single and group routes); `claimPhaseStamp` is the jsonb every claim, renewal and group dispatch mark stores in `persistence_requests.claim_phase` (v217): phase `preparing` or `publishing`, claim start, phase start, the execution token (so a later claim never reads an earlier claim's ages), the `step` in flight and when it began, `waiting_on` and the owning process (`owner`: command kind, pid, gbrain build). Preparers (`sync-prepare.ts`, `page-prepare.ts`, `prepared-maintenance.ts`, link resolution) call `enterClaimStep(clock, step, signal, waitingOn)` at each await boundary: it names the step, records what the await waits on (`git`, `fs`, `db`, `pool`, else `unknown`: set only where observed, never inferred) and throws the preparation's abort reason, so cancellation reaches a preparer between its queries even though the queries take no signal. `claimStateOf` reads a row back from the current claim's stamp only: `preparing`/`publishing` (live renewal), `publication_transaction` (claim lapsed while running, read on the database clock: a transaction holds the row or the owner is gone; requeued once it ends), `file_publication` (`publication_started`; recovery finishes it) or `unrecorded`, with claim and phase ages, `step`, `step_age_ms`, `waiting_on`, `owner`, `resumes_on_its_own` and a `why`. `claimStall` is the `preparation_overdue` verdict (`claim.stall`) for a preparing claim past its budget. `EXPIRED_PREPARING_CHARGE_SQL` is the one rule an expired-claim reclaim charges a preparation attempt by: only a claim stamped `preparing` under the token being reclaimed. `persistence.max_claim_ms` (default 600000, 60000 to 86400000; `validateMaxClaimConfigValue` is `config set`'s `invalid_params` refusal) is doctor `persistence_write_stall`'s threshold. Consumer and group-publish store the stamp on every renewal, so writer status (`diagnostics.ts`, `claim` on each running blocker, never the token) and doctor name a stuck phase and step without an extra statement per write. Tests: `test/persistence-write-stall.test.ts`, `test/persistence-claim-step.test.ts`.- `src/core/persistence/preparation-budget.ts` + `src/commands/config/preparation-keys.ts` — #6278: how long a claimed write may prepare and how many cut-offs it survives. `preparationKind` sorts a request into `foreground` (`remember`, and `put_page`/`edit_page` with no internal intent: the consumer's 30 s `preparationMs`), `sync` (`managed_sync_*` kinds: `persistence.sync_preparation_ms`, default 120000) or `maintenance` (every other kind: `persistence.maintenance_preparation_ms`, default 120000). `persistence.preparation_ceiling_ms` (default 600000, 60000 to 3600000, floored at the larger budget plus 30 s) is the hard ceiling for a preparation that ignores cancellation and `persistence.max_preparation_attempts` (default 2, 1 to 10) the cut-offs before a request finishes `preparation_stalled`; a missing or out-of-range value keeps its default (`resolvePreparationPolicy`). The four keys ride the write-switch snapshot (`switches.ts`, one statement, 5 s TTL) together with the `preparation_deadlines` kill switch, so a claim never reads config on its own. `startPreparation` runs a preparer under its budget and the budget wins the race even when the preparer ignores its signal (the signal aborts with `{ code: 'preparation_deadline' }`; a result that lands after the budget on the clock still reads as a deadline; the late result is the caller's to drop); `racePreparation` is its outcome-only form for the sync's out-of-consumer preparations (`sync-waivers.ts`). `validatePreparationConfigValue` is `config set`'s structured refusal (each key's range, and the ceiling rule across the sibling keys; usage error exit 2, nothing written), wired in by `refuseInvalidPreparationValue`. `persistence.max_claim_ms` keeps its doctor meaning. Tests: `test/persistence-preparation-budget.test.ts`.+- `src/core/persistence/owner-refusal.ts` — #6278: the `owner_unavailable` reasons matrix. `checkOwner(binding, incarnation, hostId)` names the first failing condition in a fixed order (`binding_missing`, `incarnation_changed`, `host_mismatch`, `transfer_in_progress` for a `draining` worktree, `clone_in_progress` for `recovering`, `local_path_missing`, `coordination_path_missing`) or returns the usable `ActiveOwnerBinding`; `ownerRefusal` gives each reason its message, `why`, actor, fix (always the read-only `gbrain sources writer status --source <id> --json`, with the same verify; `actor: provider` so the two in-progress reasons render `next: wait` with a 30 s delay, `host_admin` for the rest) and `retryable` (`host_mismatch` false at the site, carried by `OperationError.retryable`); `ownerUnavailableError` is the thrown form. `host_mismatch` prints both host ids' first 8 characters and, when `remote` is false, the `host.json` path this process read; nothing here claims or transfers ownership. Used by `maintenancePreflight`, `loadFenceSource` and `managedRepairRoot`; the registry's `owner_unavailable.reasons` and the `FENCE_REASONS` owner entries carry the same vocabulary. Tests: `test/owner-refusal.test.ts` (matrix, every preflight condition on a claimed worktree, the HTTP envelope without a local path), `test/fence-repair-reasons.test.ts`.+- `src/core/persistence/repair-busy.ts` — #6278: the busy set a repair must not write while a managed sync runs. `loadRepairBusySet(engine, sourceId, incarnation)` returns the paths and slugs named by queued, running and recovering requests and terminal rows with an open recovery (both rename endpoints included) plus, for every unfinished `managed-sync` cursor of the incarnation, the entries of its frozen `managed-sync-manifest` from the cursor's index on (a path with a `sync-hold` record is left out: the sync retries a held file only when its bytes change); it never throws and fails closed (`unknown` set, so `repairBusy` answers true for everything) when a query fails or a cursor's manifest is missing. `repairBusyMessage` is the hold text, `repairBusyError` the `sync_in_progress` refusal (`reason` `candidate_in_flight` or `busy_set_unreadable`) `submitManagedFileRepair` raises at admission. Tests: `test/repair-busy.test.ts`, `test/repair-fences.test.ts`, `test/repair-fences-during-catchup.test.ts` (Postgres: `test/e2e/repair-fences-during-catchup-postgres.test.ts`).- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Every claimed write has a preparation budget (`preparation-budget.ts`): `execute` races the preparation against it (`startPreparation`), so the claim is released with `blocked_reason` `preparation_deadline` and one counted attempt at the budget even when the preparer ignores its signal, and a late result never publishes (the execution-token fence). A request already at `persistence.max_preparation_attempts` is finished `failed` with `preparation_stalled` at claim without preparing again, and the release that reaches the limit finishes it there (`coordinator.ts` `finishPreparationStalled`; a waiting `awaitWrite` caller gets the terminal receipt, foreground writes included); a preparer's rejection on the consumer's own abort (its reason, an `AbortError` or a cancelled statement, `preparationAbortReason`) is a release, never a receipt. The expired-claim sweep (Postgres, and PGLite's `releaseAbandonedClaims`) charges one attempt for a claim stamped `preparing` (a process killed mid-preparation); `claim_lost`, `consumer_stopping` and `group_member_waiting` never charge, and a commit resets the counter. The #5373 root barrier for an abandoned preparation ends at `persistence.preparation_ceiling_ms` measured from the claim: the root is freed, the counter is pinned at the limit (an overrun proves cancellation is ignored, so the next claim fails the request `preparation_stalled`) and the zombie stays in `status().outlived_ceiling`; at the per-process cap (`zombieCap`, default 1) the consumer claims nothing more and `status().restart_required` is true. `stop()` gives abandoned preparations `ABANDONED_STOP_GRACE_MS` (5 s) after aborting them instead of waiting forever. The fault point `consumer:preparing` sits inside the budget, `status()` reports `preparation_policy` and `abandoned_preparations`, and the stderr line carries `phase=preparation reason=deadline_exceeded | preparation_stalled | ceiling_exceeded`. With the `preparation_deadlines` switch off only `remember` and intent-less `put_page`/`edit_page` keep the 30 s budget, the old unbounded wait applies and no attempt is counted. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `claimableWriteSql` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles or the ceiling passes, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains in-flight renewals and gives abandoned preparations their grace before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`, `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-deadline.e2e.test.ts`.- **`src/core/persistence/sync-group.ts`** + **`group-publish.ts`** — #5984 bulk publication for draining managed Postgres syncs. `sync-group.ts` resolves bulk settings (`--no-bulk` > `GBRAIN_SYNC_BULK` > `sync.bulk` > on; `sync.bulk_size` 16, `sync.bulk_max_txn_ms` 15 s; PGLite off), sizes the next group from the last group's admission-to-commit time per member, freezes followers (four at a time, stopping at a rename, company plan, overtaken entry or one the waiver would take) and admits a group in one transaction (`admitWriteGroupInTransaction`, which keeps one request row, ID and digest per page and replays priors). `sync-run.ts` keeps the head in `pending` and all members in the cursor's `group` (members carry `intent.group` = the head's request ID), waits for the last member and advances over the committed prefix; a terminal failure becomes the single pending entry, a still-pending member returns `writer_pending`. Any caller finishes an existing group; only a drain forms one. #6075: when another owner loop already admitted the group's head on the single path with the head's pre-group intent (the intent minus the `group`/`lane` keys `formGroup` adds, `groupedIntent`/`ungroupedIntent`), `groupStep` drops the group and the single path takes that request, and the never-admitted followers are frozen again; a different intent under the head's request ID still refuses `idempotency_conflict`. The single path's ENG-A7 admission guard compares the stored pending intent as well as its request ID, so a pass that read the head before a drain grouped it re-reads the cursor instead of admitting the stale intent, and an `idempotency_conflict` against a head the group admitted first re-reads the cursor too (`test/managed-sync-stale-group-head.test.ts`). The consumer claims a head's directly following queued members (`claimGroupFollowers`, never past an unfinished non-member) and `executeClaimedGroup` prepares four at a time, then `publishGroup` publishes them in one transaction: one worktree lock, ownership guard and coordinated write (each member set as the attributed actor with `setMemberAttribution`), per-member authorization, preimage read, sync validation (its source-wide part shared per transaction), apply (which reads the postimage the receipt and effects use), effects and receipt; `completeGroup` then reads every member's effect bytes, and pipelines the counter lock with one `UPDATE ... FROM unnest(...) RETURNING` that checks each member's claim and terminal reservation and releases the counters (a short `RETURNING` throws, so the single path reports each member's own code). Any failure rolls the group back; members then publish singly, later members are cancelled after a terminal failure or released after a requeue. Sync validation accepts a group member through the cursor's `group`. #6007: the pages of one `put_pages` batch (`intent.page_batch.id`; the group key is `journal.ts` `publicationGroupKey`) also publish as groups of at most `PAGE_BATCH_GROUP_MAX` (8) pages, prepared all at once, files included: one transaction records every member's recovery record (`prepareRecoveries`) before any file is touched, the publication transaction marks the members `publication_started`, publishes each member's file before its apply and re-arms the batch's mention links once after every member completes (`reconcileFinishedBatch`), and one transaction clears the records after commit (`clearResolvedRecoveries`). A single foreground page write publishes here too, as a group of one (core-persistence-continued.md, `switches.ts` entry). Within that transaction the source's local path, the owner's host binding and config values are read once per group (source membership and the writer registration are already memoized per transaction by `transactionMemo`). On failure every file the group published is restored by `recoverPublication`, which requeues those claims; the fallback claims them back in order (`reclaimReleasedWrite`) and publishes the members singly, and a batch member's failure never cancels its siblings. Each member has its own preparation budget (#6278): `executeClaimedGroup` marks a wave durably (`markDispatched`) and starts each member's clock when the wave dispatches it, so a follower waiting behind four others is never charged; the lease renews the mutable set of members still held (`renewGroupClaims` stamps each member's own phase), so releasing one member never reads as a lost group lease. When member k's budget passes, nothing later is dispatched, the in-flight suffix is aborted, k is released `preparation_deadline` (charged; finished `preparation_stalled` when that reaches the limit) and the later members `group_member_waiting` (not charged), and the contiguous prepared prefix 0..k-1 publishes (singly when shorter than two; under lanes in the original group's key order). An independent `put_pages` batch group releases only k, `laneFallback` keeps the expired member's reason, and an abandoned member's preparation goes to the consumer with its clock, so the root waits for it until it settles or the ceiling. A member's signal reaches its preparer through its clock (`enterClaimStep`), never as a blanket statement signal: `preparationReads` and `groupReads` answer one read for every member and skip their memo for a signalled statement, so a member that must give up on a shared read races its own signal against the shared promise (pinned by `test/persistence-preparation-memo-rule.test.ts`). A commit resets `preparation_attempts` (`completeGroup`). Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`, `test/e2e/persistence-group-deadline-postgres.test.ts`.- `src/core/persistence/journal.ts` — the request journal SQL: admission, claims, renewals, releases and completion. #6278: the claim statements stamp a `preparing` phase of their own token at claim time and return the previous claim's stamp with the row (`previous_claim_phase`), so a stalled receipt names the last recorded step; a group follower carries no stamp until its wave dispatches it (`markDispatched`), so a kill charges exactly the members that were preparing; `renewGroupClaims` stamps each member's own phase; `releaseUnpublishedClaim` charges one `preparation_attempts` only for `preparation_deadline` (`claim_lost`, `consumer_stopping` and `group_member_waiting` never do); `chargePreparationAttempt` charges a claim this owner still holds before it is finished `preparation_stalled`; `floorPreparationAttempts` pins the counter at the limit after a ceiling overrun; completing a request as committed resets the counter (`completeWrite`, `completeGroup`). An older owner ignores the counter and its renewals overwrite the stamp with the old shape (writer status shows each owner's version); every statement keeps `PERSISTENCE_PROTOCOL_PREDICATE`. Tests: `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex b1a368dfa5..096a52d0c7 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1376,7 +1376,7 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| A facts or takes fence in the page cannot be imported without dropping or guessing rows, so the page (or the file) was not written. | Facts and takes fences are the page's structured rows. Importing a fence that does not parse, repeats a marker or reuses a row number would silently drop or renumber rows, so coordinated writers refuse it and managed sync holds the one file while the rest of the source syncs. | A refused write: fix the fence the message names (fence, section and rows; the reason says what is wrong) and send the page again with a new request_id, or write rows with remember / takes_add. A held file or stored page: the maintenance run repairs it; preview it now with gbrain repair fences --source <id> on the brain host. | agent | `repeat the read that failed` | 1 | no |-Reasons: `header_unmapped`, `no_header`, `row_before_header`, `short_row`, `extra_cells`, `claim_split`, `holder_unresolved`, `missing_begin`, `split_rows`, `unclosed_trailing_content`, `marker_near_miss`, `repeated_marker`, `takes_in_facts`, `superseded_ambiguous`, `enum_unmapped`, `weight_missing`, `holder_missing`, `confidence_out_of_range`, `claim_value_invalid`, `takes_kind_unsupported`, `unparseable`, `row_collision`, `quoted_fence_rows`, `stored_row_collision`, `withdrawn_claim_in_malformed_fence`, `target_fence_malformed`, `prepare_time`, `normalizer_failed`, `llm_unavailable`, `llm_empty`, `llm_refused`, `llm_malformed`, `llm_truncated`, `llm_declined`, `llm_disabled`, `no_measured_model`, `budget_exhausted`, `no_pricing`, `ledger_unavailable`, `owner_unavailable`, `owner_cli_required`, `sync_in_progress`, `time_budget`, `changed_since_read`, `changed_since_preview`, `still_invalid`, `claim_changed`, `row_number_changed`, `visibility_loosened`, `row_count_changed`, `cell_changed`, `protection_loosened`.+Reasons: `header_unmapped`, `no_header`, `row_before_header`, `short_row`, `extra_cells`, `claim_split`, `holder_unresolved`, `missing_begin`, `split_rows`, `unclosed_trailing_content`, `marker_near_miss`, `repeated_marker`, `takes_in_facts`, `superseded_ambiguous`, `enum_unmapped`, `weight_missing`, `holder_missing`, `confidence_out_of_range`, `claim_value_invalid`, `takes_kind_unsupported`, `unparseable`, `row_collision`, `quoted_fence_rows`, `stored_row_collision`, `withdrawn_claim_in_malformed_fence`, `target_fence_malformed`, `prepare_time`, `normalizer_failed`, `llm_unavailable`, `llm_empty`, `llm_refused`, `llm_malformed`, `llm_truncated`, `llm_declined`, `llm_disabled`, `no_measured_model`, `budget_exhausted`, `no_pricing`, `ledger_unavailable`, `owner_unavailable`, `owner_cli_required`, `host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`, `sync_in_progress`, `time_budget`, `changed_since_read`, `changed_since_preview`, `still_invalid`, `claim_changed`, `row_number_changed`, `visibility_loosened`, `row_count_changed`, `cell_changed`, `protection_loosened`.More: [docs/guides/write-refusals.md#invalid_fence](../../docs/guides/write-refusals.md#invalid_fence)@@ -1778,7 +1778,11 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| The brain's persistence owner is not reachable right now. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |+| The source's canonical owner cannot run this write or maintenance step right now; `reason` says which condition. | A managed source publishes only through the host that owns its checkout. `host_mismatch`: another host id owns it (two GBRAIN_HOME identity files on one machine look the same; both ids are printed, and a retry on this host cannot help). `transfer_in_progress`: the worktree is draining for a writer transfer; `clone_in_progress`: a topology clone is recovering it; both clear by themselves. `binding_missing`, `incarnation_changed`, `local_path_missing` and `coordination_path_missing` name an incomplete or outdated registration. `not_sent` / `outcome_unknown`: the local owner's IPC lane did not take the write, or lost its acknowledgment. | Read gbrain sources writer status --source <id> --json on the brain host. A transfer or clone in progress: wait and retry. host_mismatch: run the step on the owner host, or give the worker and the shell one GBRAIN_HOME; never copy or regenerate host.json. Nothing claims or transfers ownership to run maintenance. | agent | `repeat the read that failed` | 1 | yes |++Reasons: `host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `binding_missing`, `incarnation_changed`, `coordination_path_missing`, `local_path_missing`, `not_sent`, `outcome_unknown`.++More: [docs/guides/troubleshooting.md#owner-unavailable](../../docs/guides/troubleshooting.md#owner-unavailable)### page_identity_changed@@ -2454,7 +2458,9 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A sync is running on this source. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |+| A sync is running on this source, or a write in flight or the sync's frozen manifest still names the file a repair would write. | A repair that changed a file the running sync admits later would make that entry refuse on its raw hash, and a file a write in flight names would be written twice; so the one candidate waits while the rest of the source is repaired. `candidate_in_flight`: the file is named; `busy_set_unreadable`: the busy set could not be read, so every candidate waited. | Nothing to do for the repair: the next run reads the file again. To finish the sync now: gbrain sync --source <id> --no-pull. | agent | `repeat the read that failed` | 1 | yes |++Reasons: `candidate_in_flight`, `busy_set_unreadable`.More: [docs/guides/write-refusals.md#sync_in_progress](../../docs/guides/write-refusals.md#sync_in_progress)diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex e037c94ea0..f6a346a1cb 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -969,8 +969,10 @@ hash binds the selected files, their exact before and after bytes, and thepage each import would store (bound to the page revision). The apply deriveseach change again from the file as it is: a file, proposal or page thatchanged since the preview reports `changed_since_preview` and is not written.-The apply refuses while an unfinished managed sync still names a selected file-(`sync_in_progress`; finish it with `gbrain sync --source <id> --no-pull`).+The apply refuses a selected file a write in flight or an unfinished managed+sync's frozen manifest still names (`sync_in_progress`, checked again when the+write is admitted; finish the sync with `gbrain sync --source <id> --no-pull`+or let the next run pick the file up).On a managed brain each file is one coordinated write (`managed_file_repair`):the exact approved bytes, the import, and the hold clear commit together, and@@ -1162,12 +1164,55 @@ with the exact `git add`/`git commit` step until the path is committed; astored page with no file by a revision-bound page write; a read-only mirror inthe database only (the file is never written). Every write's receipt carriesthe actor `fence-repair`, the tier, the classes, rows and columns, the model,-the before and after sha256 and the cost, never a cell value. A source this-host does not own is skipped (`owner_unavailable`), and so is one whose sync is-still running (`sync_in_progress`); the next run picks them up. MCP and+the before and after sha256 and the cost, never a cell value. MCP andthin-client callers cannot run a repair or reach the model; a hold's fix handsthem the owner-host command to give the user.+<a id="fence-repair-during-a-sync"></a>+#### Fence repair during a sync++A running `gbrain sync` of the source no longer stops the repair. Each+candidate is checked on its own against the sync's busy set, and only the+ones below wait as `sync_in_progress`; every other candidate is repaired while+the catch-up runs, including a file the sync held earlier (a held path is not+busy, because the sync retries a held file only once its bytes change, and+the repair is what changes them).++| Busy (waits as `sync_in_progress`) | Why |+| --- | --- |+| A file or page a queued, running or recovering write names, or a finished write whose recovery is still open; both endpoints of a rename | The write is still publishing it. |+| A file still ahead in the running sync's frozen manifest (from the cursor's index on) | The sync admits it later with the raw hash it reads then; a repair that changed the bytes first would make that entry refuse (`source_changed`). |+| Every candidate, when the busy set cannot be read (a failed query, a cursor whose manifest is missing) | The check fails closed; the hold's text says so. |++The busy set is read when the plan is made, again when each item is applied+(a sync may have started since the preview), and once more when the managed+file write is admitted, because a sync can freeze the candidate while the+repair waits on its model call. An item caught at that last check is skipped+`sync_in_progress`, nothing is written, and its model attempt is recorded as+transient, so the next run sends the same bytes again.++<a id="owner-reasons"></a>+#### Owner reasons++Fence repairs write only on the host that owns the source's checkout. When+this host may not, the candidate is skipped with the condition as its reason+(the same reasons `gbrain errors owner_unavailable` lists and chronicle and+the other maintenance writers refuse with), and the hold records it:++| Reason | What it means | Who acts | Next |+| --- | --- | --- | --- |+| `host_mismatch` | Another host id owns the checkout; the text prints both ids' first 8 characters and, for a local caller, the `host.json` path this process read. Two environments on one machine with different `GBRAIN_HOME` values (a launchd or cron worker and a shell) look exactly like this. Not retryable. | host administrator | Run the repair on the owner host (`gbrain sources writer status --source <id> --json` names it), or give the worker and the shell one `GBRAIN_HOME`. Never copy or regenerate `host.json`. |+| `transfer_in_progress` | The worktree is draining for a prepared writer transfer. | nobody | Wait 30 s and retry; the next maintenance run repairs it once the transfer is accepted or cancelled. |+| `clone_in_progress` | A topology clone or reclone is recovering the worktree. | nobody | Wait 30 s and retry; the next run repairs it once the clone finishes. |+| `incarnation_changed` | The checkout binding is from an earlier incarnation of the source (removed and re-added, or restored). | host administrator | Review writer status and re-bind the checkout. |+| `local_path_missing` | This host owns the worktree but has no checkout path registered. | host administrator | Review writer status and register the checkout again. |+| `coordination_path_missing` | This host's registration has no coordination directory. | host administrator | Review writer status and repair the registration. |+| `owner_unavailable` | The generic fallback: a source with no owner at all, or an older hold. | host administrator | Review writer status. |++Nothing in this path claims or transfers ownership to get a repair through;+the fix is always the read-only writer status. Remote callers get the host ids+but never a local path.+Inspect or undo a repair:- Managed sources: `git log --grep 'repair fence in'` lists the repair commits,diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex d31ab6deb3..edcb621c5b 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -26,6 +26,10 @@| [Sync held a file (`Held <path>: invalid_frontmatter …`, `git_held_files`)](#held-files) | `gbrain sources status <id>`, then preview `gbrain repair frontmatter --source <id>` and apply the printed `--apply --expect <hash> --yes` | agent; the apply after the user agrees | `destructive` (rewrites the previewed lines of the files) | `gbrain doctor --only git_held_files --json` || [Sync held a file for its facts or takes fence (`Held <path>: invalid_fence …`)](#held-fence-files) | nothing for most holds: the next maintenance run repairs and commits the fence. To see or do it now, preview `gbrain repair fences --source <id>` and run its printed `--apply --expect <hash>`; to pause automatic repair, `gbrain config set fences.repair.enabled false` (ask the user first). A `manual` reason needs the edit the hold names | agent; the apply needs no extra consent | none (model repair spends within the `fences.repair.*` caps; raising them is `paid`, the user's call) | `gbrain doctor --only fence_integrity --json` || [Managed catch-up stuck, or `Held <path>: preparation_stalled`, or the drain stopped `preparation_abandoned` / `preparation_systemic`](#catch-up-stuck) | `gbrain sources writer status --source <id> --json` (what the stuck write was doing: step, `waiting_on`, owner, version), fix what it names or upgrade the owner, then `gbrain sources retry-held <id>` and the same sync with its options | agent; a restart or upgrade of the owner after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources status <id> --json`, then `gbrain doctor --only git_held_files,persistence_write_stall --json` |+| [`fence_repair` or chronicle refused `owner_unavailable`, reason `host_mismatch`](#owner-unavailable) | `gbrain sources writer status --source <id> --json` on the brain host (the owner host id); run the step there, or give the worker and the shell one `GBRAIN_HOME`. Never copy or regenerate `host.json`. Do not retry from the same host | brain host | none | `gbrain sources writer status --source <id> --json` shows this host's id as the owner |+| [`owner_unavailable`, reason `transfer_in_progress` or `clone_in_progress`](#owner-unavailable) | wait 30 s and retry the same step; the worktree is draining for a writer transfer or recovering from a topology clone | agent | none | `gbrain sources writer status --source <id> --json` shows state `active` |+| [`owner_unavailable`, reason `binding_missing`, `incarnation_changed`, `local_path_missing` or `coordination_path_missing`](#owner-unavailable) | `gbrain sources writer status --source <id> --json`; the registration is missing or outdated and re-binding or re-registering the checkout is the host administrator's decision | brain host | none | the same status read shows an active binding for this host |+| [`gbrain repair fences` skipped a file `sync_in_progress` while a sync runs](repair.md#fence-repair-during-a-sync) | nothing: a write in flight or the running sync's frozen manifest still names that file; every other candidate repairs now and the next run picks this one up (`gbrain sync --source <id> --no-pull` finishes the sync) | agent | none | `gbrain doctor --only fence_integrity --json` || [A Google or GitHub item is held (`connector_held_items`)](#held-connector-items) | `gbrain sources status <id>`, fix the cause, then `gbrain sources retry-held <id>` and `gbrain sync --source <id>` | agent, after the user agrees | `egress` (fetches from the provider again) | `gbrain doctor --only connector_held_items --json` || [`gbrain migrate --to` refused with `writer_coordinator_required`](../ENGINES.md#engine-migration-refused) | follow the refusal's `fix`: relay its `user_message` (stay on PGLite and share with `gbrain mcp expose`, or leave the brain as it is) | agent, after the user agrees | `persistent_install`, `egress` (for `gbrain mcp expose`) | `gbrain doctor --no-migrate --json` || [A write was refused with a named reason](#write-refused) | the reason's recovery in [write refusal reasons](write-refusals.md) | as the refusal's `fix` | as the refusal's `fix` | the refusal's `verify` |@@ -95,6 +99,21 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p<a id="persistence-write-stall"></a>**A managed write stays `running` and later writes queue behind it, or doctor warns `persistence_write_stall`?** The owner keeps renewing a hung claim; doctor warns past `persistence.max_claim_ms` (default 600000) and names the request, root, age, phase and, for a preparation, its step and what it waited on. A write stuck *preparing* is released at its deadline and finally held or failed `preparation_stalled` on its own: see [catch-up stuck](#catch-up-stuck). A write stuck *publishing*, or one whose owner predates the deadlines, still needs the owner restarted: run `gbrain sources writer status --source <id> --json` (read-only), then restart the `gbrain serve` that owns the root and attach that output when reporting it.+<a id="owner-unavailable"></a>**`fence_repair`, chronicle, fact-fence adoption or another maintenance step refused `owner_unavailable`?** A managed source publishes only through the host that owns its checkout, and the refusal's `reason` says which condition this is; the fix is always the read-only `gbrain sources writer status --source <id> --json`, and nothing claims or transfers ownership to get a step through.++| `reason` | What it means | Next |+|---|---|---|+| `host_mismatch` | Another host id owns the checkout. The message prints both ids' first 8 characters and, to a local caller, the `host.json` this process read (`<GBRAIN_HOME>/.gbrain/persistence/host.json`). A maintenance worker (launchd, cron, autopilot) started with a different `GBRAIN_HOME` or user than the shell that ran the sync reads a different identity file and is, to the brain, a different host. `retryable: false`: a retry from the same environment cannot change the answer. | Run the step on the owner host writer status names, or make both environments use one `GBRAIN_HOME`. Never copy or regenerate `host.json`: a new identity orphans the ownership and pending writes recorded for the old one. |+| `transfer_in_progress` | The worktree is `draining`: a writer transfer was prepared and not yet accepted or cancelled. | `fix.next` is `wait`: retry after 30 s; the status read shows the state. |+| `clone_in_progress` | The worktree is `recovering`: a topology clone or reclone is in progress. | `wait`: retry after 30 s; it is `active` when the clone finishes. |+| `binding_missing` | The source has no canonical worktree binding at all. | Claiming a checkout is the host administrator's decision. |+| `incarnation_changed` | The binding belongs to an earlier incarnation of the source (removed and re-added, or restored). | Re-bind the checkout on the brain host. |+| `local_path_missing` | This host owns the worktree but has no checkout path registered. | Register the checkout again on the brain host. |+| `coordination_path_missing` | This host's registration has no coordination directory. | Repair the registration on the brain host. |+| `not_sent`, `outcome_unknown` | The local owner's IPC lane did not take the write, or lost its acknowledgment. | `gbrain sources writer status --probe --json`; for `outcome_unknown` read the receipt (`gbrain write-request -- <id>`) before resubmitting. |++A running sync is not one of these: `gbrain repair fences` now runs during a catch-up for every candidate the sync does not still name ([fence repair during a sync](repair.md#fence-repair-during-a-sync)), and a candidate it does name is `sync_in_progress`, not `owner_unavailable`.+<a id="write-capacity"></a>**Managed writes refused with `queue_capacity`, or doctor warns `persistence_capacity`?** A per-principal or per-brain write-journal limit (`persistence.limits.*`) is full (`queue_capacity`), or doctor sees lifetime request IDs or receipt bytes at 80% or more (`persistence_capacity`). For the cumulative limits (lifetime request IDs and receipt bytes), the warning and the refusal print a `gbrain config set persistence.limits.<limit> <value>` sized for about one more year; run it on the brain host, then retry with the same request ID. For outstanding-request or queued-byte limits, let outstanding writes finish and check `gbrain sources writer status`. Receipt compaction age is `persistence.receipt_retention_days` (default 30). Limits and defaults: [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention).<a id="dream-paid-loop"></a>**Dream keeps skipping one transcript, or doctor warns `dream_paid_loop`?** A dream key died `dream.breaker.max_dead_submissions` times (default 3) in 24 hours and is refused so it stops billing you. Fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'`. See [the paid-loop breaker](../operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax_dead_submissions).diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex e24ec5e438..727d4095af 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -348,7 +348,13 @@ clears or retries it with no one acting.| <a id="fence-ledger_unavailable"></a>`ledger_unavailable` | The spend ledger could not be read or written, so no model call was made. | `llm` | yes | Nothing to do: the next run retries. If it keeps happening, check the database with `gbrain doctor --json`. Format: [tiers](fence-format.md#never-guessed). || <a id="fence-owner_unavailable"></a>`owner_unavailable` | This host is not the brain's owner host, and fence repairs run only there. | `-` | yes | Run `gbrain repair fences` on the owner host (`gbrain sources writer status <source>` names it). A remote caller hands that command to the user. Format: [tiers](fence-format.md#never-guessed). || <a id="fence-owner_cli_required"></a>`owner_cli_required` | The maintenance worker may not apply this managed-file repair; it must be applied from the owner host's CLI. | `-` | no | On the owner host: `gbrain repair fences --source <source>`, then the printed apply command. Format: [tiers](fence-format.md#never-guessed). |-| <a id="fence-sync_in_progress"></a>`sync_in_progress` | A managed sync of the source has an unfinished cursor, or a queued sync request names the file, so the repair skipped it. | `-` | yes | Nothing to do: the next run retries. To finish the sync now: `gbrain sync --source <source> --no-pull`. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-host_mismatch"></a>`host_mismatch` | Another host id owns this source's checkout; the hold names both ids (first 8 characters). Two environments on one machine with different `GBRAIN_HOME` identity files (a launchd or cron worker and a shell) look exactly like this. Retrying from this host cannot change the answer. | `-` | no | Run `gbrain repair fences --source <source>` on the owner host (`gbrain sources writer status --source <source> --json` names it), or give the worker and the shell one `GBRAIN_HOME`. Never copy or regenerate `host.json`: a new identity orphans the ownership recorded for the old one. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-transfer_in_progress"></a>`transfer_in_progress` | A writer transfer of the source is prepared and its worktree is draining, so no host may write it yet. | `-` | yes | Nothing to do: the next run repairs it once the transfer is accepted or cancelled; `gbrain sources writer status --source <source> --json` shows the state. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-clone_in_progress"></a>`clone_in_progress` | A topology clone or reclone of the source's checkout is in progress and its worktree is recovering. | `-` | yes | Nothing to do: the next run repairs it once the clone finishes; `gbrain sources writer status --source <source> --json` shows the state. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-incarnation_changed"></a>`incarnation_changed` | The source's checkout binding belongs to an earlier incarnation of the source (it was removed and re-added, or restored), so the checkout it names is not this source's. | `-` | no | On the brain host, review `gbrain sources writer status --source <source> --json` and re-bind the checkout; the next run after that repairs the file. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-local_path_missing"></a>`local_path_missing` | This host owns the source's worktree but has no checkout path registered for it. | `-` | no | On the brain host, review `gbrain sources writer status --source <source> --json` and register the checkout again; the next run after that repairs the file. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-coordination_path_missing"></a>`coordination_path_missing` | This host's registration for the source has a checkout path but no coordination directory (where the physical-root stamp and locks live). | `-` | no | On the brain host, review `gbrain sources writer status --source <source> --json` and repair the registration; the next run after that repairs the file. Format: [tiers](fence-format.md#never-guessed). |+| <a id="fence-sync_in_progress"></a>`sync_in_progress` | A write in flight names the file, or the file is still ahead in a running sync's frozen manifest (the sync would refuse it on its raw hash if a repair changed it first), so this one candidate waits; the rest of the source is repaired while the sync runs. A held file is not busy. When the busy set itself cannot be read, every candidate waits. | `-` | yes | Nothing to do: the next run retries. To finish the sync now: `gbrain sync --source <source> --no-pull`. Format: [tiers](fence-format.md#never-guessed). || <a id="fence-time_budget"></a>`time_budget` | The repair run reached its time budget (the maintenance phase stops at the smaller of 300 s and a third of the job's remaining deadline). | `-` | yes | Nothing to do: the next run resumes where it stopped. Format: [tiers](fence-format.md#never-guessed). || <a id="fence-changed_since_read"></a>`changed_since_read` | The file changed after the repair read it, so nothing was written. | `-` | yes | Nothing to do: the next run reads it again. Format: [tiers](fence-format.md#never-guessed). || <a id="fence-changed_since_preview"></a>`changed_since_preview` | `gbrain repair fences --apply --expect <hash>` found the file's bytes or the page's revision changed since the preview, so that item was not applied. | `-` | no | Preview again with the same selection and apply the new `--expect` hash. Format: [tiers](fence-format.md#never-guessed). |diff --git a/llms-full.txt b/llms-full.txtindex e95fd3e0cb..5323b84786 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -9370,6 +9370,10 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| [Sync held a file (`Held <path>: invalid_frontmatter …`, `git_held_files`)](#held-files) | `gbrain sources status <id>`, then preview `gbrain repair frontmatter --source <id>` and apply the printed `--apply --expect <hash> --yes` | agent; the apply after the user agrees | `destructive` (rewrites the previewed lines of the files) | `gbrain doctor --only git_held_files --json` || [Sync held a file for its facts or takes fence (`Held <path>: invalid_fence …`)](#held-fence-files) | nothing for most holds: the next maintenance run repairs and commits the fence. To see or do it now, preview `gbrain repair fences --source <id>` and run its printed `--apply --expect <hash>`; to pause automatic repair, `gbrain config set fences.repair.enabled false` (ask the user first). A `manual` reason needs the edit the hold names | agent; the apply needs no extra consent | none (model repair spends within the `fences.repair.*` caps; raising them is `paid`, the user's call) | `gbrain doctor --only fence_integrity --json` || [Managed catch-up stuck, or `Held <path>: preparation_stalled`, or the drain stopped `preparation_abandoned` / `preparation_systemic`](#catch-up-stuck) | `gbrain sources writer status --source <id> --json` (what the stuck write was doing: step, `waiting_on`, owner, version), fix what it names or upgrade the owner, then `gbrain sources retry-held <id>` and the same sync with its options | agent; a restart or upgrade of the owner after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources status <id> --json`, then `gbrain doctor --only git_held_files,persistence_write_stall --json` |+| [`fence_repair` or chronicle refused `owner_unavailable`, reason `host_mismatch`](#owner-unavailable) | `gbrain sources writer status --source <id> --json` on the brain host (the owner host id); run the step there, or give the worker and the shell one `GBRAIN_HOME`. Never copy or regenerate `host.json`. Do not retry from the same host | brain host | none | `gbrain sources writer status --source <id> --json` shows this host's id as the owner |+| [`owner_unavailable`, reason `transfer_in_progress` or `clone_in_progress`](#owner-unavailable) | wait 30 s and retry the same step; the worktree is draining for a writer transfer or recovering from a topology clone | agent | none | `gbrain sources writer status --source <id> --json` shows state `active` |+| [`owner_unavailable`, reason `binding_missing`, `incarnation_changed`, `local_path_missing` or `coordination_path_missing`](#owner-unavailable) | `gbrain sources writer status --source <id> --json`; the registration is missing or outdated and re-binding or re-registering the checkout is the host administrator's decision | brain host | none | the same status read shows an active binding for this host |+| [`gbrain repair fences` skipped a file `sync_in_progress` while a sync runs](repair.md#fence-repair-during-a-sync) | nothing: a write in flight or the running sync's frozen manifest still names that file; every other candidate repairs now and the next run picks this one up (`gbrain sync --source <id> --no-pull` finishes the sync) | agent | none | `gbrain doctor --only fence_integrity --json` || [A Google or GitHub item is held (`connector_held_items`)](#held-connector-items) | `gbrain sources status <id>`, fix the cause, then `gbrain sources retry-held <id>` and `gbrain sync --source <id>` | agent, after the user agrees | `egress` (fetches from the provider again) | `gbrain doctor --only connector_held_items --json` || [`gbrain migrate --to` refused with `writer_coordinator_required`](../ENGINES.md#engine-migration-refused) | follow the refusal's `fix`: relay its `user_message` (stay on PGLite and share with `gbrain mcp expose`, or leave the brain as it is) | agent, after the user agrees | `persistent_install`, `egress` (for `gbrain mcp expose`) | `gbrain doctor --no-migrate --json` || [A write was refused with a named reason](#write-refused) | the reason's recovery in [write refusal reasons](write-refusals.md) | as the refusal's `fix` | as the refusal's `fix` | the refusal's `verify` |@@ -9439,6 +9443,21 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p<a id="persistence-write-stall"></a>**A managed write stays `running` and later writes queue behind it, or doctor warns `persistence_write_stall`?** The owner keeps renewing a hung claim; doctor warns past `persistence.max_claim_ms` (default 600000) and names the request, root, age, phase and, for a preparation, its step and what it waited on. A write stuck *preparing* is released at its deadline and finally held or failed `preparation_stalled` on its own: see [catch-up stuck](#catch-up-stuck). A write stuck *publishing*, or one whose owner predates the deadlines, still needs the owner restarted: run `gbrain sources writer status --source <id> --json` (read-only), then restart the `gbrain serve` that owns the root and attach that output when reporting it.+<a id="owner-unavailable"></a>**`fence_repair`, chronicle, fact-fence adoption or another maintenance step refused `owner_unavailable`?** A managed source publishes only through the host that owns its checkout, and the refusal's `reason` says which condition this is; the fix is always the read-only `gbrain sources writer status --source <id> --json`, and nothing claims or transfers ownership to get a step through.++| `reason` | What it means | Next |+|---|---|---|+| `host_mismatch` | Another host id owns the checkout. The message prints both ids' first 8 characters and, to a local caller, the `host.json` this process read (`<GBRAIN_HOME>/.gbrain/persistence/host.json`). A maintenance worker (launchd, cron, autopilot) started with a different `GBRAIN_HOME` or user than the shell that ran the sync reads a different identity file and is, to the brain, a different host. `retryable: false`: a retry from the same environment cannot change the answer. | Run the step on the owner host writer status names, or make both environments use one `GBRAIN_HOME`. Never copy or regenerate `host.json`: a new identity orphans the ownership and pending writes recorded for the old one. |+| `transfer_in_progress` | The worktree is `draining`: a writer transfer was prepared and not yet accepted or cancelled. | `fix.next` is `wait`: retry after 30 s; the status read shows the state. |+| `clone_in_progress` | The worktree is `recovering`: a topology clone or reclone is in progress. | `wait`: retry after 30 s; it is `active` when the clone finishes. |+| `binding_missing` | The source has no canonical worktree binding at all. | Claiming a checkout is the host administrator's decision. |+| `incarnation_changed` | The binding belongs to an earlier incarnation of the source (removed and re-added, or restored). | Re-bind the checkout on the brain host. |+| `local_path_missing` | This host owns the worktree but has no checkout path registered. | Register the checkout again on the brain host. |+| `coordination_path_missing` | This host's registration has no coordination directory. | Repair the registration on the brain host. |+| `not_sent`, `outcome_unknown` | The local owner's IPC lane did not take the write, or lost its acknowledgment. | `gbrain sources writer status --probe --json`; for `outcome_unknown` read the receipt (`gbrain write-request -- <id>`) before resubmitting. |++A running sync is not one of these: `gbrain repair fences` now runs during a catch-up for every candidate the sync does not still name ([fence repair during a sync](repair.md#fence-repair-during-a-sync)), and a candidate it does name is `sync_in_progress`, not `owner_unavailable`.+<a id="write-capacity"></a>**Managed writes refused with `queue_capacity`, or doctor warns `persistence_capacity`?** A per-principal or per-brain write-journal limit (`persistence.limits.*`) is full (`queue_capacity`), or doctor sees lifetime request IDs or receipt bytes at 80% or more (`persistence_capacity`). For the cumulative limits (lifetime request IDs and receipt bytes), the warning and the refusal print a `gbrain config set persistence.limits.<limit> <value>` sized for about one more year; run it on the brain host, then retry with the same request ID. For outstanding-request or queued-byte limits, let outstanding writes finish and check `gbrain sources writer status`. Receipt compaction age is `persistence.receipt_retention_days` (default 30). Limits and defaults: [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention).<a id="dream-paid-loop"></a>**Dream keeps skipping one transcript, or doctor warns `dream_paid_loop`?** A dream key died `dream.breaker.max_dead_submissions` times (default 3) in 24 hours and is refused so it stops billing you. Fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'`. See [the paid-loop breaker](../operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax_dead_submissions).@@ -11217,8 +11236,10 @@ hash binds the selected files, their exact before and after bytes, and thepage each import would store (bound to the page revision). The apply deriveseach change again from the file as it is: a file, proposal or page thatchanged since the preview reports `changed_since_preview` and is not written.-The apply refuses while an unfinished managed sync still names a selected file-(`sync_in_progress`; finish it with `gbrain sync --source <id> --no-pull`).+The apply refuses a selected file a write in flight or an unfinished managed+sync's frozen manifest still names (`sync_in_progress`, checked again when the+write is admitted; finish the sync with `gbrain sync --source <id> --no-pull`+or let the next run pick the file up).On a managed brain each file is one coordinated write (`managed_file_repair`):the exact approved bytes, the import, and the hold clear commit together, and@@ -11410,12 +11431,55 @@ with the exact `git add`/`git commit` step until the path is committed; astored page with no file by a revision-bound page write; a read-only mirror inthe database only (the file is never written). Every write's receipt carriesthe actor `fence-repair`, the tier, the classes, rows and columns, the model,-the before and after sha256 and the cost, never a cell value. A source this-host does not own is skipped (`owner_unavailable`), and so is one whose sync is-still running (`sync_in_progress`); the next run picks them up. MCP and+the before and after sha256 and the cost, never a cell value. MCP andthin-client callers cannot run a repair or reach the model; a hold's fix handsthem the owner-host command to give the user.+<a id="fence-repair-during-a-sync"></a>+#### Fence repair during a sync++A running `gbrain sync` of the source no longer stops the repair. Each+candidate is checked on its own against the sync's busy set, and only the+ones below wait as `sync_in_progress`; every other candidate is repaired while+the catch-up runs, including a file the sync held earlier (a held path is not+busy, because the sync retries a held file only once its bytes change, and+the repair is what changes them).++| Busy (waits as `sync_in_progress`) | Why |+| --- | --- |+| A file or page a queued, running or recovering write names, or a finished write whose recovery is still open; both endpoints of a rename | The write is still publishing it. |+| A file still ahead in the running sync's frozen manifest (from the cursor's index on) | The sync admits it later with the raw hash it reads then; a repair that changed the bytes first would make that entry refuse (`source_changed`). |+| Every candidate, when the busy set cannot be read (a failed query, a cursor whose manifest is missing) | The check fails closed; the hold's text says so. |++The busy set is read when the plan is made, again when each item is applied+(a sync may have started since the preview), and once more when the managed+file write is admitted, because a sync can freeze the candidate while the+repair waits on its model call. An item caught at that last check is skipped+`sync_in_progress`, nothing is written, and its model attempt is recorded as+transient, so the next run sends the same bytes again.++<a id="owner-reasons"></a>+#### Owner reasons++Fence repairs write only on the host that owns the source's checkout. When+this host may not, the candidate is skipped with the condition as its reason+(the same reasons `gbrain errors owner_unavailable` lists and chronicle and+the other maintenance writers refuse with), and the hold records it:++| Reason | What it means | Who acts | Next |+| --- | --- | --- | --- |+| `host_mismatch` | Another host id owns the checkout; the text prints both ids' first 8 characters and, for a local caller, the `host.json` path this process read. Two environments on one machine with different `GBRAIN_HOME` values (a launchd or cron worker and a shell) look exactly like this. Not retryable. | host administrator | Run the repair on the owner host (`gbrain sources writer status --source <id> --json` names it), or give the worker and the shell one `GBRAIN_HOME`. Never copy or regenerate `host.json`. |+| `transfer_in_progress` | The worktree is draining for a prepared writer transfer. | nobody | Wait 30 s and retry; the next maintenance run repairs it once the transfer is accepted or cancelled. |+| `clone_in_progress` | A topology clone or reclone is recovering the worktree. | nobody | Wait 30 s and retry; the next run repairs it once the clone finishes. |+| `incarnation_changed` | The checkout binding is from an earlier incarnation of the source (removed and re-added, or restored). | host administrator | Review writer status and re-bind the checkout. |+| `local_path_missing` | This host owns the worktree but has no checkout path registered. | host administrator | Review writer status and register the checkout again. |+| `coordination_path_missing` | This host's registration has no coordination directory. | host administrator | Review writer status and repair the registration. |+| `owner_unavailable` | The generic fallback: a source with no owner at all, or an older hold. | host administrator | Review writer status. |++Nothing in this path claims or transfers ownership to get a repair through;+the fix is always the read-only writer status. Remote callers get the host ids+but never a local path.+Inspect or undo a repair:- Managed sources: `git log --grep 'repair fence in'` lists the repair commits,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 72ccdfe645..6986e1b3a6 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -320,6 +320,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.107.0', text: 'New keys `persistence.sync_preparation_ms` (120000), `persistence.maintenance_preparation_ms` (120000), `persistence.preparation_ceiling_ms` (600000) and `persistence.max_preparation_attempts` (2) bound write preparation, and `gbrain config set` refuses a value out of range; the `preparation_deadlines` write switch (`gbrain config set persistence.preparation_deadlines false`) restores the old behavior exactly (only `remember`, `put_page` and `edit_page` keep a 30 s budget; nothing is counted or held). `persistence.max_claim_ms` keeps its doctor meaning. Migration v220 adds `persistence_requests.preparation_attempts`; restart every `gbrain serve`, jobs worker and autopilot on the new version, because an older owner never gives up a stuck preparation.' },{ since: '0.60.107.0', text: 'Fact-fence adoption (the extract_facts cycle phase and the v0.32.2 backfill) now writes the fence\'s parsed text back into `facts.fact`: a legacy claim with surrounding whitespace or CRLF line endings is adopted with that whitespace trimmed and its line endings folded to LF (the row keeps its id, vectors and provenance). A claim the fence codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or one its page already carries stays a legacy row, active and searchable, and is reported as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: …)` and under doctor `fence_integrity` `unrenderable_legacy_facts`. Only the pages still holding such rows skip destructive fact reconciliation (the whole source skipped before), and the cycle summary names them while keeping the reconcile counts of the other pages.' },{ since: '0.60.107.0', text: 'A managed maintenance write on a page whose body or timeline already carries a fence defect no adoption clears (for example a second facts fence in the timeline) is now refused at submission with its fence reason, so the cycle skips that page in `failed_pages` instead of failing a request on every pass; doctor `fence_integrity` counts the stored defect as a repair candidate.' },+ // #6278 PR 2 (stamped with the branch's VERSION; the integrator restamps `since` to the release that ships it).+ { since: '0.60.108.0', text: '`gbrain repair fences` and the maintenance `fence_repair` phase now run while a managed sync of the source is in progress: only a file a write in flight or the running sync\'s frozen manifest still names waits as `sync_in_progress` (a held file does not), and every other candidate, held files included, is repaired and committed during the catch-up. The busy check is repeated when each item is applied and when its write is admitted, and fails closed when it cannot be read.' },+ { since: '0.60.108.0', text: 'An `owner_unavailable` refusal from fence repair, chronicle, fact-fence adoption or any other maintenance writer now carries a `reason`: `host_mismatch` (both host ids\' first 8 characters, the local `host.json` path for local callers only, `retryable: false`), `transfer_in_progress` or `clone_in_progress` (`fix.next: wait`, 30 s), `binding_missing`, `incarnation_changed`, `local_path_missing` or `coordination_path_missing`; a fence hold records the same reason instead of a bare `owner_unavailable`. Nothing claims or transfers ownership to run maintenance; `gbrain errors owner_unavailable` lists the reasons.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/fence-repair.ts b/src/core/cycle/fence-repair.tsindex 3ea849f714..30fa3fec72 100644--- a/src/core/cycle/fence-repair.ts+++ b/src/core/cycle/fence-repair.ts@@ -3,10 +3,11 @@* kind (src/core/repair/fences.ts) in the global maintenance lane, so fences* that sync held and malformed fences that pages store are repaired with no* operator. The phase has no rule logic of its own: the kind plans from its- * census, skips sources this host does not own (`owner_unavailable`) or that- * are mid-sync (`sync_in_progress`), reads `fences.repair.llm` and the daily- * USD ledger itself, and re-plans on the next run, where items already- * repaired drop out.+ * census, skips sources this host may not write (an owner reason such as+ * `host_mismatch`) and the candidates a running sync still names+ * (`sync_in_progress`; the rest of a syncing source is repaired, #6278),+ * reads `fences.repair.llm` and the daily USD ledger itself, and re-plans on+ * the next run, where items already repaired drop out.** The phase gates on `fences.repair.enabled`, runs the kind through the* shared trusted repair runner (an apply, or a preview on a dry run) with adiff --git a/src/core/repair/frontmatter.ts b/src/core/repair/frontmatter.tsindex 6fb8945ebc..13e1b8fe9f 100644--- a/src/core/repair/frontmatter.ts+++ b/src/core/repair/frontmatter.ts@@ -498,7 +498,8 @@ async function applyRepair(ctx: OperationContext, repair: ApprovedRepair, selectcommitted: persistence?.git_state ?? 'not_requested' } };} catch (error) {if (error instanceof OperationError && ['changed_since_preview', 'revision_conflict', 'page_identity_changed'].includes(error.code)) return changed(error.message);- if (error instanceof OperationError && error.code === 'source_changed') return { applied: false, outcome: 'refused', reason: error.message, detail: { path: repair.path } };+ // #6278: a sync that started since the preview and still names the file is refused at admission, not written.+ if (error instanceof OperationError && (error.code === 'source_changed' || error.code === 'sync_in_progress')) return { applied: false, outcome: 'refused', reason: error.message, detail: { path: repair.path } };throw error;}}diff --git a/test/fence-repair-reasons.test.ts b/test/fence-repair-reasons.test.tsindex c9c44f94ca..af0814df34 100644--- a/test/fence-repair-reasons.test.ts+++ b/test/fence-repair-reasons.test.ts@@ -8,6 +8,7 @@ import {FENCE_REASON_CODES, FENCE_REASONS, GATE_REASONS, fenceMessage, renderFenceFix,} from '../src/core/fence-repair/reasons.ts';import type { FenceReason } from '../src/core/fence-repair/types.ts';+import { OWNER_UNAVAILABLE_REASONS } from '../src/core/persistence/owner-refusal.ts';const SPEC_MANUAL: FenceReason[] = ['missing_begin', 'split_rows', 'repeated_marker', 'takes_in_facts', 'superseded_ambiguous', 'enum_unmapped',@@ -21,6 +22,8 @@ const ADDED_MANUAL: FenceReason[] = ['unclosed_trailing_content', 'marker_near_m*/const EVAL_MANUAL: FenceReason[] = ['extra_cells', 'claim_split'];const SPEC_TIER3: FenceReason[] = ['header_unmapped', 'no_header', 'row_before_header', 'short_row'];+/** #6278: the owner conditions the `owner_unavailable` reasons matrix names (persistence/owner-refusal.ts); `owner_unavailable` stays the generic fallback. */+const OWNER_CONDITIONS: FenceReason[] = ['host_mismatch', 'transfer_in_progress', 'clone_in_progress', 'incarnation_changed', 'local_path_missing', 'coordination_path_missing'];const SPEC_OTHERS: FenceReason[] = ['holder_unresolved','unparseable', 'row_collision', 'quoted_fence_rows', 'stored_row_collision', 'withdrawn_claim_in_malformed_fence',@@ -33,7 +36,17 @@ const SPEC_OTHERS: FenceReason[] = [describe('FENCE_REASONS', () => {test('holds exactly the reasons the spec names (plus the documented additions)', () => {- expect([...FENCE_REASON_CODES].sort()).toEqual([...SPEC_MANUAL, ...ADDED_MANUAL, ...EVAL_MANUAL, ...SPEC_TIER3, ...SPEC_OTHERS].sort());+ expect([...FENCE_REASON_CODES].sort()).toEqual([...SPEC_MANUAL, ...ADDED_MANUAL, ...EVAL_MANUAL, ...SPEC_TIER3, ...OWNER_CONDITIONS, ...SPEC_OTHERS].sort());+ });++ test('owner conditions match the owner_unavailable reasons matrix: host_admin acts, only the in-progress ones retry by themselves', () => {+ expect(OWNER_CONDITIONS.every(reason => (OWNER_UNAVAILABLE_REASONS as readonly string[]).includes(reason))).toBe(true);+ for (const reason of OWNER_CONDITIONS) {+ expect([reason, FENCE_REASONS[reason].actor, FENCE_REASONS[reason].stage, FENCE_REASONS[reason].tier]).toEqual([reason, 'host_admin', 'repair', null]);+ expect([reason, FENCE_REASONS[reason].autoRetry]).toEqual([reason, reason === 'transfer_in_progress' || reason === 'clone_in_progress']);+ expect(FENCE_REASONS[reason].fix).toContain('gbrain sources writer status --source <source> --json');+ }+ expect(FENCE_REASONS.host_mismatch.fix).toContain('never copy or regenerate host.json');});test('screen residual classes carry the spec\'s tier and manual-only flag', () => {diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex db9257d22c..5a25602ef8 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -63,6 +63,7 @@ test/managed-sync-lanes.test.tstest/managed-sync-preparation-stalled-holds.test.tstest/managed-sync-row-parity.test.tstest/managed-sync-stale-group-head.test.ts+test/owner-refusal.test.tstest/pack-relation-direction-engine.test.tstest/page-embedding-install-batch.test.tstest/page-state-engine.test.ts