Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs(key-files): GBRA-150 entries move to managed-sync-bookkeeping (persistence-stalls over its size cap)
garrytan2f2ebdb15e77
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 7fc6138037..c6639636db 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -37,9 +37,6 @@- `src/core/repair/legacy-twins.ts` — `gbrain repair legacy-twins --source <id>` (#6885): explicit-only, preview-bound, destructive consent (`LEGACY_TWINS_CONSENT_TEXT`). `scanLegacyTwins` reads a source's live pages with no recorded origin and no `database_only_reason` in id batches (at most `LEGACY_TWINS_SCAN_LIMIT`), keeps those whose slug `slugifyPath` folds differently, and pairs each with the live page at the folded slug that records a file (at most `LEGACY_TWINS_LIMIT` pairs and decisions). `pairVerdict` lists a pair as a decision (never merged) for differing `content_hash`, several legacy candidates, a twin file `liveFileDrift` does not call `agrees`, a file at the twin's own slug path, twin withdrawals, a legacy `file:` URI or a twin slug outside the op grammar. The preview binds pairs to the owner (host, worktree, owner epoch, incarnation) and both pages' ids, slugs and revisions; the apply refuses `not_owner_host`, `legacy_twins_storage_unknown`, `preview_changed` and `legacy_twin_mass_merge_refused` (`massTwins`, the sync valve). Each pair re-checks with `pairNow`, then a managed brain submits one `managed_maintenance_merge_legacy_twin` request on the twin (`prepareLegacyTwinMerge`, dispatched from `prepared-maintenance.ts`: no file target, `databaseOnlyReason: 'shared_origin'`, the legacy key in `additionalPageKeys`, `pairLocked` under the publication locks); an unmanaged brain merges in `maintenanceTransaction` under both page locks. `applyTwinMerge` records the twin's `source_path` on the legacy page, clears the twin's origin (so its tombstone's retention purge is database-only, never a `shared_origin` refusal), moves links (deduplicated; pair links stay), timeline rows, raw data, attachments, page aliases and facts about the twin, records the twin slug as a `slug_aliases` row, versions and soft-deletes the twin, and moves the twin's `sync-import-provenance` record to the legacy page at its post-write revision. Outcomes `merged`, `changed_since_preview`. Tests: `test/repair-legacy-twins-6885.test.ts` (Postgres: `test/e2e/repair-legacy-twins-6885-postgres.test.ts`).- `src/core/persistence/unindexed-files.ts` — #6865 the unindexed-file detector: `findUnindexedFiles(engine, sourceId, opts)` streams `git ls-tree -r -l -z` of the source's last synced commit, filters it through discovery's own `loadSyncEligibility`, and in batches (one `pages.source_path = ANY` read on `pages_source_path_idx`, one hold read by fingerprint) keeps files with no live page recording their origin (source-path space, with the legacy Git-root spelling in source-root mode), no hold and no scheduled re-screen (`readGitHoldRetryPaths`; those count as `scheduled`); a file whose path slug belongs to a live page with another or no origin is still unindexed and counted `slug_taken`. Found files are screened read-only with `screenImportContent` (at most 2,000 per pass, the rest `unscreened`). Folder-scaffolding names sync skips on purpose (`isSyncMetafile`) that would otherwise be eligible (checked against a probe name in the same directory plus `sync.exclude` and the reserved skill paths) and carry a frontmatter `type:` or `title:` are counted apart as `metafile_skipped` (only under `sync.metafile_pages off`: under the default `typed` the eligibility predicate admits a nested one, so it is an ordinary unindexed file; each tree batch primes its metafile heads) with samples, and never scheduled. A time or count budget stops it with `complete: false` and a cursor (the last Git path, compared in byte order, which is Git's recursive tree order). `refreshUnindexedFiles` continues an incomplete stored result, schedules the found paths (`requestGitHoldRetry`, a scheduling write only) and stores one `op_checkpoints` row per source (op `unindexed-files`, fingerprint the source id; the 7-day checkpoint purge applies). `judgeUnindexedFiles` is doctor's read: unscheduled finds, scheduled paths still in the retry row (waiting for a sync), and consumed paths that still have no page and no hold, without scanning. Test: `test/unindexed-files.test.ts`.- `src/commands/doctor/checks/unindexed-files.ts` — #6865 doctor `unindexed_files` (BRAIN, after `missing_recorded_files`): reads `judgeUnindexedFiles` for each bound managed Git source; `ok` when every result is complete, recent and nothing is missing; `warn` with counts by code, samples and age when files are unindexed (fix `gbrain sources retry-held <id> --unindexed`, `then` the follow-up sync from `gitFollowUpSync`, verify `gbrain doctor --only unindexed_files --json`) or scheduled and waiting (fix the sync); info `unknown` when a result is missing, older than 7 days or incomplete with nothing found, naming the maintenance phase and the command; info `not_applicable` on a classic brain. `metafile_skipped` files are named in the message and details and never make it warn; alone they are info `degraded` with a `user` fix (rename the file, then the sync). Test: `test/unindexed-files.test.ts`.-- `src/core/persistence/resolve-paths.ts` — GBRA-150 `resolveSourcePaths`: what gbrain did with each file path of a source, by its own rules, so a landing check stops copying them. Per path: the sync slug (`resolveSlugForPath`), presence in the last synced commit and at HEAD (Git object reads), the skip reason (`unsyncableReason`, plus `typed_frontmatter` for a skipped metafile), the open hold, the live page by origin (`source_path`) and by slug (`slug_owner` when another file owns it, so a case-folded twin never reads as this file's page), a differing frontmatter `slug:`, chunk and embedding counts (`listEmbeddingStateRows` with its `slugs` filter), and one of `RESOLVE_PATH_STATES` with `searchable` (true / 'keyword' / false), `why` and an existing-command `fix`. Bounded: at most 200 paths, indexed lookups only, nothing written. Tests: `test/sources-resolve-path.test.ts`.-- `src/core/persistence/landing-gaps.ts` — GBRA-150 `readLandingGaps`: committed managed_sync receipts of the last 24 h (at most 2,000, newest first through the watermark index, 2 s statement probe; a timeout reads `unknown`, never ok) whose page is still missing, has chunks waiting for vectors, has no chunks, or is quarantined past `sync.freshness_target_seconds`; one row per page with reason and fix. Consumers: `sync status --detail` `landing` / `landing_read` (`sync-status.ts`) and doctor `sync_landing_gaps`. Tests: `test/sync-landing-gaps.test.ts`.-- `src/commands/doctor/checks/landing-gaps.ts` — GBRA-150 doctor `sync_landing_gaps` (registered after `partial_embedding`, one of `CHEAP_INCIDENT_CHECKS`): warns per source with the gap count by reason and the first fix from `readLandingGaps`; `unknown` read stays a warning, never ok. Tests: `test/doctor-sync-landing-gaps.test.ts`.- `src/commands/doctor/checks/missing-recorded-files.ts` — #6609 doctor `missing_recorded_files` (BRAIN, after `ghost_pages`): the classic-brain counterpart of `ghost_pages`. Read-only; per source with a checkout on this host and managed persistence off it runs `scanMissingRecordedFiles` (`src/core/persistence/detached-pages.ts`) and warns with counts, samples and an `ask_user` fix (put the file back and sync, or `gbrain delete` then `gbrain restore <slug> --source-id <id> --detach`) for live pages whose recorded file a `gbrain sync --full` would not find; `ok` + `not_applicable` when no source qualifies. Test: `test/restore-detach-6609.test.ts`.- `src/core/persistence/overwritten-edits.ts` — #6712 follow-up: `scanOverwrittenEdits` finds live pages whose database-only revision a managed-sync import replaced with different content and no hold, from durable rows only (it survives receipt compaction): `page_versions.write_request_id` / `archived_write_request_id`, the writer's committed receipt (`outcome.persistence.mode = 'database'`, not an import, no `git` effect for that revision, not a read-only mirror write), the archiving request recognised as a managed-sync import by intent kind or, once compacted, by operation `submit_job` + `outcome.imported_file` without `connector_database`, and `reconcileCanonical` digests (the import's own revision differs; no later revision holds the edit again). `high` or `unknown` (`no_persistence_outcome`, `import_content_unreadable`, `segmented`); the newest open overwrite per page; at most `OVERWRITE_SCAN_LIMIT` candidate versions per source. Revisions with no recorded writer are not reported.- `src/commands/doctor/checks/overwritten-edits.ts` — doctor `sync_overwritten_db_edits` (BRAIN, after `missing_recorded_files`): per source count and first slugs from `scanOverwrittenEdits`; `warn` only for `high` findings, with the read-only `gbrain repair overwritten-edits --source <id>` preview as an `ask_user` fix; `unknown` findings are counted in `details` and never warn.diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.mdindex 08f3e86970..95057afd0d 100644--- a/docs/architecture/key-files/managed-sync-bookkeeping.md+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md@@ -45,3 +45,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The- `src/commands/doctor/checks/managed-sync-movement.ts` + `src/core/persistence/sync-movement.ts` — #6317 (B4, I2): the movement reader and its doctor check. `readManagedSyncMovement` snapshots, per active managed source, the newest `completed_at` of committed `managed_sync_*` receipts in the current source incarnation (the watermark: one probe of the partial index `persistence_requests_sync_watermark`, v223; a count would shrink under compaction), the head claim's `step_since`, the `managed-sync` cursor (`index/total`, `held`) and `sources.last_sync_at`/`last_commit`, and whether a drain or full consumer is live on the owner host. `data_moving` is false when an unfinished cursor has had neither a committed receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` while a consumer is live; with none live the state is `parked` (informational). `sources status --json` and `writer status --json` print `data_moving`, `not_moving_since` and `movement_state` beside `sync_running`, and `sources status` prints the writer-status command beside `data_moving: false`; doctor `managed_sync_not_moving` (warn, scored for `not_moving` only) uses the same rule and command as its fix, and fails on a parked cursor whose admitted queue has no consumer past the ceiling (#6552; fix: the resume sync); `serve` prints one `[gbrain notice]` when a source flips. A failed backlog read is `unknown`, never `nothing_pending` (doctor warns). `/health` stays liveness-only.- `src/commands/sources-writer-movement.ts` — #6317 (I2): `gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]`, the deploy gate `gbrain upgrade` and `post-upgrade` end by printing (bare, so it inherits the default window; neither runs it, because neither restarts the resident processes). The printed step is `MOVEMENT_SUPERVISOR_STEP` from the import-free leaf `src/commands/movement-step.ts` (re-exported here), so upgrade loads it before the swap (#6604). Same source selection as `writer status` (`persistence-admin.ts`). It snapshots through `sync-movement.ts`, waits `max(300 s, preparation budget + 60 s)` (printed as the effective budget; `--wait <dur>` takes sync's duration syntax) and judges each source: `moved` (a new committed publication; a cursor advanced only by holds or a `last_sync_at` touched by an up-to-date check is not movement) and `current` exit 0; `held` exits 0 with a warning and the hold kind's route (`gbrain repair fences --source <id>`; `preparation_stalled` → writer status, then `gbrain sources retry-held <id>`); `within_allowance` (the head's step advanced inside the window) exits 0 with `retry_after_ms`; `not_moving` exits 1 with `managed_sync_not_moving` (`reason: movement_check`, `fix.argv` the writer-status command, `fix.verify` this command); `unknown` (backlog unreadable) exits 1 with `movement_unknown`; other read failures keep their code. `--warn-only` prints the same envelopes and exits 0. Flags are regenerated into `src/core/cli-flag-registry.generated.ts` with `bun run build:flag-registry`.- `src/core/serve-head-watcher.ts` + `src/core/persistence/sync-freshness.ts` + `src/commands/doctor/checks/managed-sync-latency.ts` — #6858 ask 6: on-commit sync and its latency metric. `startServeHeadWatcher` (two call sites: `installResidentTickers` in `src/commands/serve.ts`, stopped before `shutdownDelegatedSync`, and `runServeHttp` in `src/commands/serve-http.ts`, beside `startMovementWatch` and stopped on the same shutdown path) re-reads `sync.on_commit` every 30 s; while on it polls `git rev-parse HEAD` in each managed source checkout this host owns (`GBRAIN_SERVE_HEAD_POLL_MS`, default 3 s; an `fs.watch` on the git dir only nudges the poll), debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the unchanged `startDelegatedSync` with this host's `cli` registration. It never starts beside a running delegated sync or a held drain lease (the move stays pending and fires once after), skips a HEAD `sources.last_commit` already has, resumes a resumable stop up to `MAX_RESUMES`, and logs each distinct error once. `readSyncFreshness` samples committed `managed_sync_import` receipts of the last 24 h (not first syncs or working-tree entries): commit time is the git committer time of `intent.target`, searchable is `completed_at`, embedded is the page's newest `content_chunks.embedded_at` once every chunk has one, sampled only from a receipt no later committed write to the same page supersedes and only at or after its `completed_at`; p50/p95 in one aggregate over the `persistence_requests_sync_watermark` predicate. `gbrain sync status` (the `freshness` block) and `gbrain status` print it; doctor `managed_sync_latency` grades p95 against `sync.freshness_target_seconds` (default 300; fail over max(1 h, target)) only with `sync.on_commit` on or a target set. Tests: `test/serve-head-watcher.test.ts`, `test/serve-head-watcher-managed.serial.test.ts`, `test/serve-http-head-watcher.serial.test.ts`, `test/sync-freshness-6858.test.ts`. #7189: each `SourceFreshness` carries `behind` (`readGitBehind`, injectable `BehindReader`: `rev-list --count <last_commit>..HEAD` and the oldest of those commits' committer age; null without a checkout or a synced commit), printed by `formatSyncFreshness`.+- `src/core/persistence/sync-status.ts` (status coherence) — GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error.+- `src/core/persistence/resolve-paths.ts` — GBRA-150 `resolveSourcePaths`: what gbrain did with each file path of a source, by its own rules, so a landing check stops copying them. Per path: the sync slug (`resolveSlugForPath`), presence in the last synced commit and at HEAD (Git object reads), the skip reason (`unsyncableReason`, plus `typed_frontmatter` for a skipped metafile), the open hold, the live page by origin (`source_path`) and by slug (`slug_owner` when another file owns it, so a case-folded twin never reads as this file's page), a differing frontmatter `slug:`, chunk and embedding counts (`listEmbeddingStateRows` with its `slugs` filter), and one of `RESOLVE_PATH_STATES` with `searchable` (true / 'keyword' / false), `why` and an existing-command `fix`. Bounded: at most 200 paths, indexed lookups only, nothing written. Tests: `test/sources-resolve-path.test.ts`.+- `src/core/persistence/landing-gaps.ts` — GBRA-150 `readLandingGaps`: committed managed_sync receipts of the last 24 h (at most 2,000, newest first through the watermark index, 2 s statement probe; a timeout reads `unknown`, never ok) whose page is still missing, has chunks waiting for vectors, has no chunks, or is quarantined past `sync.freshness_target_seconds`; one row per page with reason and fix. Consumers: `sync status --detail` `landing` / `landing_read` (`sync-status.ts`) and doctor `sync_landing_gaps`. Tests: `test/sync-landing-gaps.test.ts`.+- `src/commands/doctor/checks/landing-gaps.ts` — GBRA-150 doctor `sync_landing_gaps` (registered after `partial_embedding`, one of `CHEAP_INCIDENT_CHECKS`): warns per source with the gap count by reason and the first fix from `readLandingGaps`; `unknown` read stays a warning, never ok. Tests: `test/doctor-sync-landing-gaps.test.ts`.diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex 772067f524..a1222e95c4 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -35,7 +35,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks with `identity: 'reservation'` (#5914: it publishes nothing, so a recreated directory whose reservation names the worktree and whose stamp carries the same token releases; a token mismatch refuses), then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`). In `deactivation.ts`: on a brain whose managed persistence was never activated, `--dry-run` reports the real `source_bindings` and each claim as `pre_activation_claims` (and `apply_command` when clean), and the state-bound run releases them through `pre-activation-release.ts`; with no claims a rerun still only cleans retired markers. Tests: `test/persistence-preactivation-claim.test.ts`. In `unbound-source.ts`: on a brain whose managed persistence is not activated, the hint offers editing the page's file plus `gbrain sync --source <id>` (and `persistence.unbound_write=database_only` where it applies) instead of the claim, and says a claim alone would block classic sync until activation or `gbrain sources writer deactivate`.- `src/core/persistence/sync-concurrent-write.ts` — #6194 (D4): `concurrentWriteProof` decides whether a managed sync import's `revision_conflict` receipt came from a concurrent database-only write. The proof is revision-linked: the page's live revision differs from the import's frozen `expected_revision`, and `pages.revision_write_request_id` names a committed non-sync request for the same source incarnation and page id (a delete or recreate of that page included; admission order is never used). `concurrentWriteHold` builds the `concurrent_write` hold (competing request id, operation and revision in `meta`; identifiers only). `sync-run.ts` `holdFailedFenceRequest` (the receipt branch) holds such a file exactly as it holds a prepare-time fence refusal; imports only (a held deletion would be re-screened at once), and without proof the failure still blocks. `sync-holds.ts` routes it (`gitHoldFix`: `gbrain sources reconcile <source> <slug> --preview`, then `sources retry-held`; `HoldRepairRoute.concurrent` from the summary's `concurrent` counter, read by `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the remote host-operator fix). Tests: `test/managed-sync-concurrent-write-hold.test.ts`.- `src/core/persistence/sync-page-fault.ts` — #6340: a page that moved under a managed catch-up holds the page, not the run. `headCommittedBytes` returns the working-tree bytes of a path when their blob id equals `HEAD:<path>` (sha1 or sha256 by HEAD's id length), so `freezeEntry` imports bytes committed past the pinned target as HEAD has them (the later pin..HEAD diff re-imports them as a no-op; idea and first test from PR #6323, which this supersedes) and `prepareManagedSyncMutation`'s `newerWorkingTree` screen never sees them. `pageChangeProof` is #6194's revision-linked proof usable at freeze time; `pageChangedHold` builds the `concurrent_write` hold for a database page that was edited, deleted or re-bound after enumeration (with the competing request when proven, else `page_revision` + `expected_revision`), `worktreeDirtyHold` the new `worktree_dirty` hold (pinned `blob_oid`, `working_hash`) for uncommitted bytes that match neither the pin nor the page, `pinnedWorktreeConflict` recognizes that receipt and `pageMovedSinceAdmission` a `revision_conflict` receipt whose page really moved (a run-level conflict with the page where it was still blocks). In `sync-run.ts`: `freezeEntry` resolves the three freeze-time throws (`page_identity_changed`, `revision_conflict`, the renamed-source conflict) into holds when holds are on (a page that still holds exactly what the import carries is re-bound to its new revision and passed by the waiver screen; `sync.holds=fail` and company-brain cursors keep the refusals), `holdFailedFenceRequest` converts the two receipts (imports and deletes) through `receiptPageFaultHold`, re-freezes an entry once under a fresh request when its file changed between admission and publication (`fileChangedAfterAdmission`, the `raw_file_changed` receipt: committed bytes then import as HEAD has them, a second change under the re-frozen request is held `worktree_dirty`; `holdUnderGate` takes `refrozen` in place of `hold` and records the conversion as `refrozen`), `convertBlockedCursor` converts a cursor an older release left blocked (re-freezing a dirty file that is committed now), `originFaultHold` holds an entry whose recorded origin no longer identifies the enumerated page (`assertSyncPageOrigin` at freeze), every page-fault hold marks the cursor `overtaken` (#5522: another cursor may have checkpointed this target), and the `--retry-failed` start tries that conversion before rediscovering, so the frozen manifest survives. `writeGitHold` counts `meta.attempts` per re-hold with the same code; `HOLD_ATTEMPTS_NEEDS_HUMAN` (3) turns a page hold into `needs_human`. The run's catch skips the failure ledger for `isRetryableConnError` / statement timeouts. Tests: `test/managed-sync-page-fault-holds.test.ts` (freeze-time DB edit → hold, same content → re-bind, dirty → `worktree_dirty` → commit → import, committed past pin → HEAD bytes, old blocked cursor → in-place conversion with attempts, connection death → no ledger row, same run on relaunch, one extra pass), the updated expectations in `test/persistence-managed-sync.test.ts` and `test/managed-sync-concurrent-write-hold.test.ts`.-- `src/core/persistence/sync-fault-class.ts` + `sync-status.ts` + `src/commands/sync/operator.ts` — #6340: the operator contract. `SYNC_FAULT_TABLE` / `classifySyncFault` turn a code (plus a receipt `detail`, a hold's `attempts`, an error message) into `{ class: page | connection | systemic, safe_actions, needs_human, human_reason }`; `docs/guides/sync-unblock-runbook.md` renders the table between `sync-fault-table` markers and `test/sync-runbook-table.test.ts` pins the two. `readSyncStatus` joins the cursor header (index/total, pinned target, last advance, rate; #6518: the newest cursor recorded under the source's *current* incarnation, the only one a current sync can select), `committed_last_10m` (committed managed page requests of the source), every hold (with `gitHoldFix`) and the last ledger failure (never the read view's `sync_incomplete`) into `SyncStatus` with one `next` action (a human's fix with `user_message`, else `gbrain sync unblock --apply`, else the resume command, `--retry-failed` when a ledger row exists). When no current-incarnation cursor or failure exists but an unfinished cursor stands under an older incarnation, the status is `cursor: null` with `last_error.code: cursor_incarnation_retired` (table row: systemic, `repair`, no human) and `next` is the `gbrain repair managed-sync-orphans --source <id>` preview, never a sync that selects nothing. #6712 PR 2 (L5): `state`/`reason` (`SYNC_STATUS_REASONS`), the bounded `oldest_blocker` (the drain's head probe) and `recovery` probes; `readSyncStatus(…, { detail })` skips the terminal summary, blocker list and cursor join when false (the plain CLI), each with a `<field>_read` `not_read` sibling; `syncStatusHeadline` is the text headline. `unblockSync(engine, sourceId, { apply, noRepair?, noLlm?, maxLlmUsd?, registry? })` schedules a re-screen (`requestGitHoldRetry`) for a `worktree_dirty` hold whose file is committed at HEAD now and for a `preparation_stalled` hold; for a repair-class hold whose code `CONTENT_REPAIR_HOLD_KINDS` maps to a content-repair lane kind (#6377; `invalid_fence` → `fences`) it runs that kind on exactly those paths through `runContentLane` as one bounded apply (`UNBLOCK_REPAIR_BUDGET_MS` = 120 s, the `fences.repair` caps, `noLlm` for the free tiers), re-reads the holds, and reports each path as `applied[].action: 'repair'` with `repair: { kind, outcome: repaired | held | needs_human | skipped, reason?, tier?, llm_usd?, receipt? (the write's location-only detail), next }` (a path the kind kept out of its plan takes the reason the kind recorded on the hold); repaired paths join the re-screen. It refuses `still_dirty`, `concurrent_write`, exhausted holds, repair-class holds no lane kind clears yet (or all of them under `noRepair`), and holds whose stored repair state says a person decides (`contentHoldDisposition`: a manual or paid fence state, a recommended merge; these are listed, never retried) by name with their fix; previews without `--apply` (repair holds listed as `skipped` / `preview`); and is idempotent. `holdVerdict` makes `readSyncStatus` report such a hold `needs_human` with the paragraph (the fault table's when it names the lane's codes, else a sentence naming the state), and `next` says when unblock would write hash-bound repairs with a receipt per file. The CLI subcommands `gbrain sync status --source <id> [--json]` and `gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]` (routed in `sync/run.ts` like `sync trigger`; `cli.ts` skips the sync watchdog and the serve delegations for them; `syncOperatorVerb` makes `sync --status` the status read) print the envelope with `next` (and each repair outcome's `next`) rendered through `renderAction`, plus a receipt line per repaired file; `--json` writes the envelope through `writeJsonDocument`, so under the D2 guard it is the one stdout document. Tests: `test/sync-status-unblock.test.ts`, `test/cli-json-guard.test.ts`. #6402: `cancelled` (a knock-on window cancel) is a `page` / `retry` row, not needs_human, so `sync status` hands the loop the same retry sync's own `Next:` prints (`sync-cancelled-knock-on.test.ts`). GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error.+- `src/core/persistence/sync-fault-class.ts` + `sync-status.ts` + `src/commands/sync/operator.ts` — #6340: the operator contract. `SYNC_FAULT_TABLE` / `classifySyncFault` turn a code (plus a receipt `detail`, a hold's `attempts`, an error message) into `{ class: page | connection | systemic, safe_actions, needs_human, human_reason }`; `docs/guides/sync-unblock-runbook.md` renders the table between `sync-fault-table` markers and `test/sync-runbook-table.test.ts` pins the two. `readSyncStatus` joins the cursor header (index/total, pinned target, last advance, rate; #6518: the newest cursor recorded under the source's *current* incarnation, the only one a current sync can select), `committed_last_10m` (committed managed page requests of the source), every hold (with `gitHoldFix`) and the last ledger failure (never the read view's `sync_incomplete`) into `SyncStatus` with one `next` action (a human's fix with `user_message`, else `gbrain sync unblock --apply`, else the resume command, `--retry-failed` when a ledger row exists). When no current-incarnation cursor or failure exists but an unfinished cursor stands under an older incarnation, the status is `cursor: null` with `last_error.code: cursor_incarnation_retired` (table row: systemic, `repair`, no human) and `next` is the `gbrain repair managed-sync-orphans --source <id>` preview, never a sync that selects nothing. #6712 PR 2 (L5): `state`/`reason` (`SYNC_STATUS_REASONS`), the bounded `oldest_blocker` (the drain's head probe) and `recovery` probes; `readSyncStatus(…, { detail })` skips the terminal summary, blocker list and cursor join when false (the plain CLI), each with a `<field>_read` `not_read` sibling; `syncStatusHeadline` is the text headline. `unblockSync(engine, sourceId, { apply, noRepair?, noLlm?, maxLlmUsd?, registry? })` schedules a re-screen (`requestGitHoldRetry`) for a `worktree_dirty` hold whose file is committed at HEAD now and for a `preparation_stalled` hold; for a repair-class hold whose code `CONTENT_REPAIR_HOLD_KINDS` maps to a content-repair lane kind (#6377; `invalid_fence` → `fences`) it runs that kind on exactly those paths through `runContentLane` as one bounded apply (`UNBLOCK_REPAIR_BUDGET_MS` = 120 s, the `fences.repair` caps, `noLlm` for the free tiers), re-reads the holds, and reports each path as `applied[].action: 'repair'` with `repair: { kind, outcome: repaired | held | needs_human | skipped, reason?, tier?, llm_usd?, receipt? (the write's location-only detail), next }` (a path the kind kept out of its plan takes the reason the kind recorded on the hold); repaired paths join the re-screen. It refuses `still_dirty`, `concurrent_write`, exhausted holds, repair-class holds no lane kind clears yet (or all of them under `noRepair`), and holds whose stored repair state says a person decides (`contentHoldDisposition`: a manual or paid fence state, a recommended merge; these are listed, never retried) by name with their fix; previews without `--apply` (repair holds listed as `skipped` / `preview`); and is idempotent. `holdVerdict` makes `readSyncStatus` report such a hold `needs_human` with the paragraph (the fault table's when it names the lane's codes, else a sentence naming the state), and `next` says when unblock would write hash-bound repairs with a receipt per file. The CLI subcommands `gbrain sync status --source <id> [--json]` and `gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]` (routed in `sync/run.ts` like `sync trigger`; `cli.ts` skips the sync watchdog and the serve delegations for them; `syncOperatorVerb` makes `sync --status` the status read) print the envelope with `next` (and each repair outcome's `next`) rendered through `renderAction`, plus a receipt line per repaired file; `--json` writes the envelope through `writeJsonDocument`, so under the D2 guard it is the one stdout document. Tests: `test/sync-status-unblock.test.ts`, `test/cli-json-guard.test.ts`. #6402: `cancelled` (a knock-on window cancel) is a `page` / `retry` row, not needs_human, so `sync status` hands the loop the same retry sync's own `Next:` prints (`sync-cancelled-knock-on.test.ts`).- `src/core/persistence/sync-drain.ts` (#6340 additions) — `isConnectionDrop` (a retryable connection error that is not #6329's `CONNECTION_DESTROYED` / `CONNECTION_CLOSED` settle discard; `retry-matcher.ts` now matches `ECONNABORTED`, `ETIMEDOUT` and `EPIPE` beside `ECONNRESET`); `runDrain` reconnects (`DrainInput.reconnect`, `engine.reconnect` from `drainManagedSync`) and retries a dropped pass on `CONNECTION_RETRY_MS` (5/15/45 s), resets the count on every committed page, and after `CONNECTION_STRIKES` drops with no commit between them ends `blocked` / `connection_lost` with `drain.connection { drops, last_error }` (URLs stripped) and the resume command as a loopable `next` (`sync_drain_connection_lost` in the catalogue, `connection_lost` in the registry). `drainManagedSync` takes exactly one extra pass (`drain.extra_pass { from, to }`, counts merged by `mergeExtraPass`) when HEAD moved past the pinned target during a `synced` run, so a live checkout ends at HEAD without looping. Tests: `test/sync-drain-connection.test.ts`. In-pass governor: `src/core/persistence/drain-step.ts` — `runDrain` races every pass against a governor that runs with or without `announce`: the pass gets its own `AbortController`, the governor's head read is bounded (`GOVERN_PROBE_MS`, or the window when shorter), and on a stop the pass signal is aborted with `DrainPassAbandoned` (the pass's `assertActive` / `stampDrainStep` boundaries throw it, so it admits and writes nothing more; `stampDrainStep` does not throw the caller's own cancel, which still banks admitted work) and its late result or rejection is dropped. A head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; `PUBLICATION_CEILING_DEFAULT_MS`) stops `blocked` / `drain_stalled` / `publication_overdue` with `stall.in_pass` and a `next` that says restart (never a promised reclaim); a pass with no commit and nothing changing for `IN_PASS_NO_PROGRESS_MS` (5 min) stops `no_progress` / `owner_missing` (#6712 PR 2 retired `no_admission`); a live preparation is left to its own budget and ceiling. The pass returns at the checkpoint commit (`managed_sync.finish` counts as a commit); its tail runs after the lease is released (`sync-tail.ts`). `drain-step.ts` holds the process-local step (`freeze`, `waiver_run`, `admission`, `await_receipt`, stamped in `sync-run.ts`) and the last statement label (`noteDrainSql`, from `waiveNoopRun`). `enterClaimPhase(clock, 'publishing')` stamps `waiting_on: 'publication'`. `sync-waivers.ts` `waiveNoopRun` pipelines at most `WAIVER_PIPELINE_MAX` (64) calls per round trip and sends the next chunk only while the prefix holds. `commands/sync-delegate.ts` reports a delegated stop as it is. Tests: `test/sync-drain-inpass-stall.test.ts`, `test/sync-drain-no-admission.test.ts`, `test/sync-drain-finish-tail.test.ts`, `test/sync-waivers-chunk.test.ts`.- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). W4.4: when `git rev-parse` fails for a directory that holds a `.git` entry (damaged HEAD, dubious ownership, timeout, Git missing), `detectManifestScope` refuses `writer_manifest_unsafe` with a `git -C <dir> status` fix instead of falling back to `tree` (which read ignored files); only a directory that `git-checkout.ts` `classifyGitCheckout` reads as `not_git` (no `.git` entry at or above it, no `GIT_DIR`) keeps `tree` scope. Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v218 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`); W4.3: `assertHardenedGitArgs` allows only filter-free plumbing (`rev-parse`, `ls-files`, `ls-tree`, `cat-file` without `--filters`/`--textconv`, `hash-object --no-filters`, `check-attr`, `diff-index --cached`) in both wrappers, and `hardenedPathDirty` is the `git status -- <path>` equivalent (untracked, staged incl. unborn HEAD, worktree vs index; `null` for conversion attributes, CRLF bytes, symlinks/gitlinks and exec-bit-only changes). #6510: `trackedBytes` checks for symlinks with `lstat` on every directory component between the canonical root and the leaf, then the leaf, on every read (no cache across files: a parent swapped to a symlink after the first file would otherwise let a later leaf read outside the root), reading through the Git spelling; the former `realpath(path) === path` proxy refused a checkout whose volume spells a name differently (APFS NFC/NFD, case-insensitive volumes) with no symlink anywhere. Tests: `test/persistence-manifest-git-scope.test.ts`, `test/worktree-manifest-unicode.test.ts` (synthetic realpath-spelling spy on Linux, parent-swap, case-spelling where the tmpdir is case-insensitive), `test/hardened-git-filters.test.ts`.- `src/core/git-checkout.ts` — #6210 (fix wave 12): `classifyGitCheckout(dir, env = process.env): 'git' | 'not_git' | 'unknown'` decides from the filesystem alone whether a directory is inside a Git checkout: `not_git` only when the directory exists and no `.git` entry (directory or gitdir file) is at or above it and `GIT_DIR` is unset; `unknown` for a missing directory or any lookup error other than absence. Git's own exit 128 is locale-dependent and also means a damaged HEAD, a bad gitdir or dubious ownership, so callers that soften "not a checkout" use this instead. `isDurabilityHardenedAsync` (`brain-repo-durability.ts`) returns false only for `not_git` or an absent hook; every other failure (a git probe run with `LC_ALL=C` failing, a timeout, an unreadable hook) rejects `git_unavailable`, and `runPersistenceEffects` (`persistence/effects.ts`) settles each cached per-root probe to `{durable}|{error}` and records the error on every coalesced effect, so the effects stay queued (and park after repeated failures) instead of completing as `durability_not_enabled`. Tests: `test/git-checkout.test.ts`, `test/persistence-git-durability-probe-6210.slow.test.ts` (Postgres via `test/e2e/persistence-git-durability-probe-6210-postgres.test.ts`; fix wave 16 split it out of the 5530 coalescing file, whose fixture both share through `test/helpers/git-coalescing-fixture.ts`).