Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/master' into capy/gbra191-verified-bug-wave
garrytanb5637a6fc0e1
diff --cc docs/architecture/key-files/canonical-reconciliation.mdindex 1fe923e1ae,d0003526bf..7c7beb65aa--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@@ -18,9 -18,9 +18,9 @@@ See [generations](generations.md)- `src/core/persistence/sync-slices.ts` — #6349 path-sliced staging for a managed target that exceeds the cursor bound with no commit axis to stage on (a first sync, a `--full` tree walk, one commit above the bound). `sliceEntries` cuts the whole resolved manifest in `(phase, code-unit path)` order: every import slice, then bounded deletion slices, the longest prefix the bound admits. The slice cursor `{ phase, after, head, target }` lives in `op_checkpoints` (`managed-sync-slice`, keyed by source, incarnation and the run's cursor options so a resumed invocation with other exclusions starts over), written or cleared by the slice's checkpoint in the same transaction that leaves `last_commit` untouched until the last slice settles; `sync-discovery.ts` resumes an unfinished target pinned at its recorded commit.- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision/liveness snapshots. #6517: `selectOriginClaimant` (sync-origin.ts) is the one origin rule, applied by the discovery census and by `assertSyncPageOrigin` at preparation and publication: a live page wins over tombstones, several live pages refuse `page_identity_changed` naming the soft-delete exit (`sharedOriginExit`), a single tombstone may be reused, several tombstones stay ambiguous. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. #6278 (B7): `retryTaken` lists every scheduled path the discovery read (screened as an entry, as a candidate, or no longer eligible); `sync-run.ts` clears them in the transaction that saves the fresh cursor. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032). `resolveManagedSyncContext` refuses `skipFailed` / `includeGitignored` on a managed source with `managed_sync_flag_refused` (`managed-sync-flags.ts`, `detail` = the flag, fix = the same `gbrain sync` argv without it), the one refusal jobs, MCP and the cycle reach; `gbrain sync` raises it at parse, before the legacy ledger acknowledgement and the cost gate, `--all` included (#6696). #6865: the per-path eligibility (scope, `sync.exclude`, `sync.include_hidden`, strategy, reserved skillpack paths) and the origin a path maps to under the slug mode come from one exported `loadSyncEligibility(engine, context, opts?, company?)`, which the unindexed-file detector shares.- - `src/core/hardened-git.ts` (#6712 additions; base entry in [persistence-stalls](persistence-stalls.md)) — `assertHardenedGitArgs` now checks exact options in every wrapper: `cat-file` with at most `--batch` (never `--filters`, `--textconv` or `--batch-command`), `hash-object --no-filters` optionally with `--stdin-paths`, `check-attr` with `-z`/`--stdin`, and `diff-tree` only as `-r -z --no-renames`. `hardenedGitStream` is the third wrapper: it spawns asynchronously, streams stdout to a callback, feeds stdin with backpressure, SIGKILLs past its timeout or byte cap and rejects when the consumer or the stdin iterable throws; `NulRecordSplitter` and `hardenedStreamComplete` give the completeness rule (exit 0, no signal, output ending at a NUL or empty). Tests: `test/hardened-git-stream-6712.test.ts`, `test/hardened-git-filters.test.ts`.+ - `src/core/hardened-git.ts` (#6712 additions; base entry in [persistence-stalls](persistence-stalls.md)) — `assertHardenedGitArgs` checks exact options in every wrapper: `cat-file` with at most `--batch` (never `--filters`, `--textconv` or `--batch-command`), `hash-object --no-filters` optionally with `--stdin-paths`, `check-attr`/`check-ignore` with `-z`/`--stdin`, and `diff-tree` only as `-r -z --no-renames`. `hardenedGitStream` is a third wrapper: it spawns async, streams stdout to a callback, feeds stdin with backpressure, SIGKILLs past its timeout or byte cap and rejects when the consumer or stdin iterable throws; `NulRecordSplitter` and `hardenedStreamComplete` give the completeness rule (exit 0, no signal, output ending at a NUL or empty). Tests: `test/hardened-git-stream-6712.test.ts`, `test/hardened-git-filters.test.ts`.- `src/core/persistence/sync-git-stream.ts` — the managed-sync reconcile's Git level reads (#6712), all through `hardenedGitStream` (allow-listed, filter-free plumbing; the checkout's clean/process filters and textconv never run) and parsed as they stream, so memory is the result maps. `readTreeLevel` (`ls-tree -r -z <commit> -- <scope>`: blobs plus symlinks and gitlinks with their mode), `readIndexLevel` (`ls-files -s -z`, the index only; a conflicted path keeps its highest stage) and `readRenameHints` (`diff-tree -r -z --no-renames`: a deleted and an added regular file paired only when their blob OID is unique to them; hints, never candidates) throw `SyncTreeReadIncomplete` (code `reconcile_read_incomplete`) unless Git exited 0, was not signalled and its output ended at a NUL. `readBlobs` reads contents through one `cat-file --batch`, leaving out missing, oversized and over-total objects. `probeDirtiness` is the batched `hardenedPathDirty` (`Dp`): per batch of 2,000 paths one `hash-object --no-filters --stdin-paths` and one `check-attr -z --stdin`, presence and bytes from `readSyncFile`; verdicts in order `untracked`, `staged` (index and tree differ in OID or mode, a non-zero stage, or one side missing), `deleted`, `unknown` (symlink or gitlink, unreadable file, a path with a newline or a leading quote, any Git failure, an OID that disagrees with the bytes read), then `clean` (raw OID equals the tree with the executable bit matching), `clean_eol` (only `text`/`eol` set and the CRLF-folded bytes hash to the tree), `clean_lfs` (a valid pointer whose sha256 and size match the bytes) or `modified`; another filter, `working-tree-encoding`, an executable-bit-only change or CRLF bytes that fold to the tree with no attribute are `unknown`, never clean. Tests: `test/hardened-git-stream-6712.test.ts` (every verdict, completeness, and a forced probe that 1,000 passes of every read never run a configured filter or textconv while `git status`/`git diff` on the same checkout do). Working mode: `probeDirtiness(..., { working: true })` never reads the index (a path with no file is `deleted`, a present file outside the tree `untracked` with its raw OID, every other present file judged from its bytes against the tree through the same `clean_eol`/`clean_lfs` domains), so a staged edit, a staged new file, `git rm --cached`, a staged deletion and a staged file removed from disk probe as the same disk does with a pristine index: the working level is the physical bytes (design v3.2 §2.1). `hashWorkingLevel` hashes every path of a working round that way with hash-then-restat (a path whose bigint `lstat` moved across the hash is rehashed, up to three attempts) and returns the stat cache it leaves: `WorkingStatCache` is plain JSON (`{v: 1, root, entries: {path: 'dev:ino:mode:uid:size:mtime_ns:ctime_ns' | 'absent'}}`), an entry is written only for a stable stat whose `mtime` and `ctime` are older than 2 s before the attempt began (Git's racy rule) and a probe with a level, and at most `WORKING_STAT_CACHE_MAX_ENTRIES` (100,000) entries are kept in path order. `workingChanged(cache, paths)` is the idle tick's check: a path the cache does not hold, a moved stat, a failed stat, a zero `ctime`, a missing cache or a moved root all read as changed, never as unchanged. `parseWorkingStatCache` validates a serialized copy (junk is null, so everything reads changed); `rememberWorkingStatCache`/`recallWorkingStatCache` keep up to 64 caches per process. Working-mode tests: `test/sync-working-level-6712.test.ts` (probe 41, on the Git reads and on a managed PGLite pass), `test/sync-working-stat-cache-6712.test.ts` (probe 42); the probe 28 marker test also runs `hashWorkingLevel`.-- `src/core/persistence/sync-classify.ts` — the managed-sync level classifier (#6712 PR 4, design v3.2 §2.3): pure (no I/O), total, ordered, first match over one path's facts (`SyncPathState`: mode, `T[p]`, the level `L`, presence, `Dp`, the page and its import record, the attestation of its revision, hold, deletion marker, baseline blob, open work). Rows in order: `held`, `spelling`, `untracked`, `kept`, `delete`, `delete_drift`, `gone`, `deleted_same`, `deleted_edited`, `legacy_same`, `dirty`, `matched`, `adopt`, `reparse`, `db_ahead` (sub-labels `pending`/`db_only`/`unproven`; keep_db writes only `db_only` on a clean committed path; an open full obligation skips `db_only`/`unproven`), `import`, `legacy_unverified`, `keep_db`, `drift` (side `both` or `unknown`); then the overlay (unsettled with open work is `in_flight`). `syncClassAction` is the glossary tag (`none`, `owner`, `repair`); `syncPassKind` decides `idle`, `hold_only` or `full` from the converged state and every obligation. Tests: `test/sync-classify-6712.test.ts` (each row, and the cross product against a reference model built from the state space).+- `src/core/persistence/sync-classify.ts` — the managed-sync level classifier (#6712 PR 4, design v3.2 §2.3): pure (no I/O), total, ordered, first match over one path's facts (`SyncPathState`: mode, `T[p]`, the level `L`, presence, `Dp`, the page and its import record, the attestation of its revision, hold, deletion marker, baseline blob, open work). Rows in order: `held`, `spelling`, `untracked`, `kept` (and an absent db_only page), `delete`, `delete_drift`, `gone`, `deleted_same`, `deleted_edited`, `legacy_same`, `dirty`, `matched`, `adopt`, `reparse`, `db_ahead` (sub-labels `pending`/`db_only`/`unproven`; keep_db writes only `db_only` on a clean committed path; an open full obligation skips `db_only`/`unproven`), `import`, `legacy_unverified`, `keep_db`, `drift` (side `both` or `unknown`); then the overlay (unsettled with open work is `in_flight`). `syncClassAction` is the glossary tag (`none`, `owner`, `repair`); `syncPassKind` decides `idle`, `hold_only` or `full` from the converged state and every obligation. Tests: `test/sync-classify-6712.test.ts` (each row, and a cross product against a reference model).- `src/core/persistence/sync-pass.ts` — the read-only shadow of the level-triggered pass (#6712 PR 4a): `readShadowLevel` reads one managed source's level (`T` via `readTreeLevel`, `X`, working-mode untracked files, `Dp` for committed candidates only or every path in working mode, pages keyset on `pages.id` with the import record by a LATERAL primary-key probe and the revision's attestation in the same statement, holds and retry rows, open requests and pending Git effects, deletion markers) and classifies every path with `sync-classify.ts`; it writes and admits nothing. Postgres reads share one `REPEATABLE READ, READ ONLY` transaction; PGLite runs bounded 2,000-row statements. A company-brain source returns null (it keeps its frozen manifest). `shadowConvergence` wraps it in the receipt, `dryRunConvergence` backs `gbrain sync --dry-run --json`'s `convergence` (with the read-only screen), `statusConvergence` backs `sync status --detail` and doctor, and `idleTickProbe` times the idle tick's reads for the bench (`scripts/bench/sync-convergence.ts`). Tests: `test/sync-pass-shadow-6712.test.ts`.- `src/core/persistence/sync-convergence.ts` — the convergence receipt (#6712 PR 4a, schema `convergence/1`, always `dry_run: true`): per-class `counts` and `classes` with action tags (`in_flight`, `keep_db_pending` beyond 200 per pass, and `deletes_withheld` when #2828's valve trips are classes too), predicted `decisions` by side after `readOnlySameContentScreen` (the dry run's `sameContentAtOrigin`: a screening request through `prepareManagedSyncMutation(..., { unsaved: true })`, at most 200 paths; one call's preparations share group-publish.ts's `preparationReads` memo plus the binding, trust-config and purge-tombstone reads, read their pages through `importGroupReads`' batch (`reread`), and answer each page's origin, timeline, take-collision and safe-chunk-fence reads from one read per kind per call (`sliceReads`), so a call costs a constant, not a statement per page (GBRA-108); equal content is `same_content_noops`, unscreened is `screen_unknown`), `would_hold`, `db_ahead` by prefix, `legacy_unverified`, `legacy_pageless`, `deletes` with the valve verdict and set hash, up to 20 samples per non-matched class, timings and statement count. `--redact-paths` replaces paths with sha256 prefixes and drops slugs.- `src/core/persistence/sync-dry-run-writer.ts` — #7167: `readDryRunWriterState(engine, sourceId)`, the writer state a managed dry run reports (`SyncResult.writer`: open queued/running/recovering requests of the source, the oldest one's age, and `gbrain sources writer status` as the next step) instead of waiting on the writer. A CLI dry run runs once outside the drain (`commands/sync/perform.ts`), so the drain's no-progress governor never abandons a long read as a writer stall, and a dry run that is not delegated to a serve says it previews in this process (`commands/sync-delegate.ts`). Test: `test/sync-dry-run-drain-7167.test.ts`.diff --cc docs/architecture/key-files/commands-2.mdindex e7f8ff169c,d8c940d0f7..e981bfe99b--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@@ -23,8 -23,8 +23,8 @@@ Doctor's embedding-dimension warning tr- `src/commands/doctor/checks/auto-chronicle.ts` — `auto_chronicle`, `chronicle_config_invalid` and `auto_chronicle_default_on` (#5876), registered after `unlinked_facts`, config-plane only (no provider calls). `auto_chronicle`: off by choice is ok with `severity: info`, `readiness: disabled_by_choice`; an invalid word warns `auto_chronicle_invalid`; when on it reads `core/chronicle/ledger-stats.ts` and warns `judge_llm_unavailable` (pending pages, no chat provider) or the top failure reason with that reason's fix, else reports ok with 24 h use of the daily limit, the largest writer's share, 7-day outcomes and spend, and `gbrain dream --phase chronicle`. Every warn carries `details.fix` (an Action: argv/consent/actor) and `fix_hint`. `chronicle_config_invalid` warns on an out-of-range stored `chronicle.*` value. `auto_chronicle_default_on` is ok/info with `ask_user` and keep/opt-out decisions until `gbrain config set auto_chronicle` acknowledges. Test: `test/auto-chronicle-surfaces-5876.test.ts`.- `src/commands/doctor/checks/vector-coverage.ts` — `fact_take_vectors` (#5188, #5885), registered after `auto_chronicle`: per unarchived source (honoring `--source`), active facts (`eligibleFactEmbedding` + `staleFactEmbedding`) and takes (`countStaleTakes` with the DB-plane model and width) with no vector for their current text, split into missing versus other-model, plus `facts.partially_embedded` (current vectors of facts over `EMBED_MAX_CHARS`, `partiallyEmbeddedFact`; reported, never re-embedded, #6975); warns with code `stale_vectors` and `details.fix` (`gbrain embed --stale`, or `gbrain takes embed` when `takes.auto_embed` is off; per-source `gbrain embed --facts --stale --source <id> --dry-run --json`). Keyless brains report `applicable: false`; a brain with no recorded model or width warns `vectors_not_verified`.- - `src/commands/doctor/checks/git-holds.ts` + `checks/frontmatter-repairable.ts` + `checks/frontmatter-hook.ts` — the #5988 hold and frontmatter checks. `git_held_files` (wave, host-only, `resolution: 'repair'`): Git-source holds per source from `readHeldCoverage` (missing vs stale counts) and the first five paths from `readGitHoldListing` with each one's code and `gitHoldFix` step, the put_page read-only note, `gbrain sources status <id>` and each source's repair command from the hold router (`holdRepairSteps`: `gbrain repair frontmatter --source <id>`, `gbrain repair fences --source <id>` for `invalid_fence` holds, both for a mixed source; with fence holds the details add `fences` and `auto_repair`, and the banner line names the fence repair through the wave entry's `bannerHow`); `fail` once a source holds more than `sync.hold_escalate_count`; connector holds stay on `connector_held_items`. `frontmatter_repairable` (registered inline: emitted by the `frontmatter_integrity` entry from the same `scanBrainSources` walk, whose `PerSourceReport.repairable` counts files by repairable cause: recoverable `YAML_PARSE`, `needs_interpretation`, `FRONTMATTER_COMMENT_VALUE` on title/name/description/summary, `NESTED_QUOTES`, `NULL_BYTES`, `MISSING_CLOSE`, `SLUG_MISMATCH`); a deadline-partial scan sets `details.partial`; the doctor scan passes `frontmatterOnly`, so each file's head through its closing fence is validated when `frontmatterScanHead` proves the findings equal, else the whole file (`test/brain-writer-frontmatter-scan-head.test.ts`). Both list `details.source_ids` and belong to the explicit-only `frontmatter` kind, so remediation classifies them `explicit_kind_required` with `--source <id>` when one source is named. `frontmatter_hook` (wave, operator): installed gbrain pre-commit hooks older than `FRONTMATTER_HOOK_VERSION`, fix `gbrain frontmatter install-hook --source <id> --force`. `frontmatterHoldsBannerNote` (a `POST_UPGRADE_NOTES` entry) names sources whose unfinished managed cursor stopped on a failed content refusal: the next sync recovers them, `gbrain sync --source <id> --no-pull` does it now, plus the repair preview and the hook refresh. `fenceHoldsBannerNote` (a separate `POST_UPGRADE_NOTES` entry, #6188 D7) names sources whose cursor stopped on a fence receipt (typed or the message an older gbrain stored): the next sync recovers them with no command, `gbrain sync --source <id> --no-pull` does it now, the malformed fences the stored census knows and whether the next maintenance run repairs them, the read-only `gbrain repair fences` preview and the pause command `gbrain config set fences.repair.enabled false`; never an applying command. Tests: `test/doctor-frontmatter-holds.test.ts`, `test/persistence-sync-fence-holds.test.ts`.+ - `src/commands/doctor/checks/git-holds.ts` + `checks/frontmatter-repairable.ts` + `checks/frontmatter-hook.ts` — the #5988 hold and frontmatter checks. `git_held_files` (wave, host-only, `resolution: 'repair'`): Git-source holds per source from `readHeldCoverage` (missing vs stale counts) and the first five paths from `readGitHoldListing` with each one's code and `gitHoldFix` step, the put_page read-only note, `gbrain sources status <id>` and each source's repair command from the hold router (`holdRepairSteps`: `gbrain repair frontmatter --source <id>`, `gbrain repair fences --source <id>` for `invalid_fence` holds, both for a mixed source; with fence holds the details add `fences` and `auto_repair`, and the banner line names the fence repair through the wave entry's `bannerHow`); `fail` once a source holds more than `sync.hold_escalate_count`; `details.visibility_noncanonical` counts held files and stored non-canonical private pages; connector holds stay on `connector_held_items`. `frontmatter_repairable` (emitted inline by the `frontmatter_integrity` entry from the same `scanBrainSources` walk, whose `PerSourceReport.repairable` counts files by repairable cause: recoverable `YAML_PARSE`, `needs_interpretation`, `FRONTMATTER_COMMENT_VALUE` on title/name/description/summary, `NESTED_QUOTES`, `NULL_BYTES`, `MISSING_CLOSE`, `SLUG_MISMATCH`); a deadline-partial scan sets `details.partial`; the doctor scan passes `frontmatterOnly`, so each file's head through its closing fence is validated when `frontmatterScanHead` proves the findings equal, else the whole file (`test/brain-writer-frontmatter-scan-head.test.ts`). Both list `details.source_ids` and belong to the explicit-only `frontmatter` kind, so remediation classifies them `explicit_kind_required` with `--source <id>` when one source is named. `frontmatter_hook` (wave, operator): gbrain pre-commit hooks older than `FRONTMATTER_HOOK_VERSION`, fix `gbrain frontmatter install-hook --source <id> --force`. `frontmatterHoldsBannerNote` (a `POST_UPGRADE_NOTES` entry) names sources whose unfinished managed cursor stopped on a failed content refusal: the next sync (or `gbrain sync --source <id> --no-pull` now) recovers them, plus the repair preview and the hook refresh. `fenceHoldsBannerNote` (a separate `POST_UPGRADE_NOTES` entry) names sources whose cursor stopped on a fence receipt (typed or legacy): the next sync recovers them with no command (`gbrain sync --source <id> --no-pull` now), the stored census's malformed fences and whether the next maintenance run repairs them, the read-only `gbrain repair fences` preview and the pause command `gbrain config set fences.repair.enabled false`; never an apply. Tests: `test/doctor-frontmatter-holds.test.ts`, `test/persistence-sync-fence-holds.test.ts`.-- `src/commands/doctor/wave-checks.ts` — `WAVE_CHECKS`, the table of managed-persistence wave checks (stable id, `resolution` `repair`/`operator`/`unsupported`, count-free remote `impact`, operator `instruction`, `count` for banners, `bannerHow` when a finding's details change the banner's parenthetical, `registration` inline-in-doctor.ts or from this table). `fence_integrity` (#6188, `repair`, registered inline) counts `details.total`; its banner line says "repaired automatically by the next maintenance run" while one is active (from `details.auto_repair`), else why not, with `gbrain repair fences` as the preview; a fence-only `git_held_files` finding gets the same wording, a mixed one adds it to the frontmatter preview. `runWaveChecks` turns a throwing check into an `unknown` finding; `checkHealthUnknown` reads `details.health === 'unknown'`. `remoteWaveHandoff` returns one line per remotely offered check with `details.host_action` {`check_id`, `state` ok/action_required/unknown, `preview_command`} and no paths, rows, SQL, emails or installation ids. Consumers: doctor.ts, `report-remote.ts`, `remediate.ts`, `upgrade-banner.ts`. Tests: `test/recovery-layer.test.ts`, `test/e2e/recovery-layer.test.ts`.+- `src/commands/doctor/wave-checks.ts` — `WAVE_CHECKS`, the table of managed-persistence wave checks (stable id, `resolution` `repair`/`operator`/`unsupported`, count-free remote `impact`, operator `instruction`, `count` for banners, `bannerHow` when a finding's details change the banner's parenthetical, `registration` inline-in-doctor.ts or from this table). `fence_integrity` (#6188, `repair`, registered inline) counts `details.total`; its banner line says "repaired automatically by the next maintenance run" while one is active (from `details.auto_repair`), else why not, with `gbrain repair fences` as the preview; a fence-only `git_held_files` finding gets the same wording, a mixed one adds it to the frontmatter preview. `runWaveChecks` (`ids` for `--only`, #7343) turns a throwing check into an `unknown` finding; `checkHealthUnknown` reads `details.health === 'unknown'`. `remoteWaveHandoff` returns one line per remotely offered check with `details.host_action` {`check_id`, `state` ok/action_required/unknown, `preview_command`} and no paths, rows, SQL, emails or installation ids. Consumers: doctor.ts, `report-remote.ts`, `remediate.ts`, `upgrade-banner.ts`. Tests: `test/recovery-layer.test.ts`, `test/e2e/recovery-layer.test.ts`.- `src/commands/doctor/remediate.ts` — the `--remediation-plan` / `--remediate` CLI shell (re-exported from doctor.ts): per-step `command` (`gbrain jobs submit …` for job steps, `gbrain repair <kind> --apply` for repair steps; a repair step with `llm_usd` names its paid chat model spend, and any embedding part, in its fix and plan line), `combinedRemediateCommand` (with repair steps it ends `--expect <plan_hash>`, the same hash `--remediation-plan --json` reports as `plan_hash`), a `Repair kinds whose preview failed` block for `repair_preview_failures` (each `{kind, code, message, why, fix}`; such a kind is not planned, so a plan approved while it failed refuses `preview_changed` once it succeeds), `REMEDIATE_HELP`, `--include-repairs`/`--no-embed`/`--resume` handling, the resume command after budget exhaustion (repeats the recorded cap and consent), `classifyWaveFindings` (cleared / pending / consent_required / operator_required / explicit_kind_required / unsupported, from wave checks run before and after; `details.partial` is pending; an explicit-only kind's preview gets `--source <id>` via `findingSource` when the finding names one source; `--remediation-plan` runs the wave checks too and reports the same classification as `findings`) and `remediationExitStatus` (0 when no repairable finding remains and no step failed; 1 otherwise, on budget exhaustion or when a repair preview failed; 2 when the target is unreachable with no repair step, or a resume is refused), set through `setCliExitVerdict`; 3 when consent is required), set through `setCliExitVerdict`. Consent (agent operator wave C1) lives in `doctor/remediate-consent.ts`: the CLI connects probe-only (no migrations) and computes the plan; when anything would run it calls `requireConsent` (effects `paid`, plus `destructive` with `--include-repairs`, bound to a `plan_hash` over the brain id, job step ids, repair kinds and pending counts, and the parameters, and persisted with the approval). Non-TTY without authorization changes nothing and exits 3 with the consent payload; `--json` never implies consent; `--yes` without `--max-usd` runs under the derived cap (estimate ×1.5, floor $0.25; the default cap when unpriced), and derived-cap exhaustion prints the `--max-usd` resume command. Startup (migrations) completes only after consent. A `--resume` is bound by its checkpoint manifest, not a new plan hash. Pinned by `test/doctor-remediate-consent.test.ts`.@@@ -40,8 -40,8 +40,8 @@@- `src/commands/doctor.ts` — `gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit] [--no-migrate]`: health checks. `checkPostgresCancellationDriver` (`postgres_cancellation_driver`) inspects a real reserved runtime owner through the shared cancellation helper: unsupported `discard()` is a typed local failure with a repair link, connection/deadline failure is a warning, and PGLite is exempt. The bounded reserve releases late arrivals and does not make general engine connect require cancellation, preserving broken-install diagnostics. `--no-migrate` keeps doctor observational: the CLI connects with `probeOnly` so a clean-or-behind schema is reported as-is instead of being auto-migrated before the checks run. The file is a façade carrying `buildChecks` (flag parse into a `DoctorContext`, then `runDoctorRegistry`), `runDoctor` and output rendering; the checks run as the ordered registry in `src/commands/doctor/registry.ts` (see that entry), the check-function library lives in bundles under `src/commands/doctor/checks/` plus four tail-cluster modules under `src/commands/doctor/` (see that entry), all re-exported here so the full surface is unchanged — structural guards pin its source text via `test/helpers/doctor-source.ts`, never by reading this file alone. Checks include `jsonb_integrity` + `markdown_body_completeness` (reliability), `schema_version` (fails loudly when `version=0`, routes to `gbrain apply-migrations --yes`; a version AHEAD of this client's `LATEST_VERSION` warns "upgrade this client"; and when the ledger reads current, a read-only `detectMissingColumns` diff from `src/core/schema-verify.ts` runs INSIDE the ledger-current branch — a PgBouncer-swallowed ALTER TABLE can advance `config.version` over a physically narrower table, so missing live columns downgrade the ok to a warn naming them with the `gbrain init --migrate-only` hint; diff failure is best-effort and the ledger ok stands; positional wiring pinned by `test/doctor-schema-column-diff.test.ts`), `upgrade_errors` (async `checkUpgradeErrors(engine)` over `~/.gbrain/upgrade-errors.jsonl`: the warn downgrades to an EXPLICIT status-ok line — never silence — only when the past failure is provably superseded, i.e. the running binary is at/past the failed target version AND the schema verifies current via `engine.getConfig('version')`; a missing engine or unverifiable schema keeps the warn, fail-closed, because `self-upgrade` swaps the binary before `post-upgrade` runs migrations and the binary alone can lie; pinned by `test/doctor-upgrade-errors.test.ts` + `test/doctor-upgrade-errors-stale.test.ts`), `queue_health` (Postgres-only: stalled-forever active jobs started_at > 1h, waiting-depth-per-name > threshold default 10 via `GBRAIN_QUEUE_WAITING_THRESHOLD`, and dead-lettered subagent jobs with `last_error` matching the `prompt_too_long` classifier in last 24h), `sync_failures` (`[CODE=N, ...]` breakdown for unacked-warn + acked-ok; severity comes from the shared `decideSyncFailureSeverity` in `src/core/sync-failure-ledger.ts` so the LOCAL and REMOTE/thin-client doctor surfaces can never drift — a stuck bookmark escalates to FAIL once an OPEN failure has blocked past the staleness window or ≥10 files block, while already `auto_skipped` rows stay a visible WARN), `rls_event_trigger` (healthy `evtenabled` set is `('O','A')` only; fix hint `gbrain apply-migrations --force-retry 35`), `graph_coverage` (short-circuits to ok when `SELECT COUNT(*) FROM pages WHERE type IN ('entity','person','company','organization')` returns 0; WARN hint is `gbrain extract all`), `embedding_column_registry` (probes each declared column via Postgres `format_type(atttypid, atttypmod)` to catch dim mismatch with a paste-ready `gbrain config set embedding_columns '{...}'` hint, probes HNSW index presence via `pg_indexes`, computes default-column population via `COUNT(*) FILTER (WHERE <col> IS NOT NULL) / COUNT(*)` warning below 90% except empty brains where chunk_count=0 short-circuits to ok; PGLite parity via `executeRaw`), and `skill_brain_first` (walks SKILL.md via `autoDetectSkillsDirReadOnly`, calls `analyzeSkillBrainFirst()` from `src/core/skill-brain-first.ts` per file with structured `Check.issues[]`; warn states `missing_brain_first`/`brain_first_typo`, ok states `compliant_callout`/`compliant_phase`/`compliant_position`/`exempt_frontmatter`/`no_external`; snapshot+diff audit at `~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl`). `--fix` delegates inlined cross-cutting rules to `> **Convention:** see [path](../path).` callouts via `src/core/dry-fix.ts` (and MISSING_RULE_PATTERNS for the brain-first callout); `--fix --dry-run` previews. `--index-audit` (Postgres-only, informational, no auto-drop) reports zero-scan indexes from `pg_stat_user_indexes`. Every DB check runs under a progress phase; `markdown_body_completeness` runs under a 1s heartbeat. `runDoctor` uses `autoDetectSkillsDirReadOnly` (from `src/core/repo-root.ts`; install-path fallback so `cd ~ && gbrain doctor` finds bundled skills); `--fix` carries a D6 install-path safety gate that refuses auto-repair when `detected.source === 'install_path'` (would rewrite the bundled tree). The Lane D supervisor check (`doctor/checks/supervisor-health.ts`) consumes `summarizeCrashes(events)` from `src/core/minions/handlers/supervisor-audit.ts` (warn at `>=1` real crash; ok message has `clean_exits_24h=N`; warn message has `runtime=A oom=B unknown=C legacy=D` per-cause breakdown) so OOM/runtime/unknown crashes are distinguishable from clean code=0 worker drains; cross-surface parity with `gbrain jobs supervisor status` is pinned by source-grep wiring assertions requiring the breakdown substrings on the doctor surface and in `jobs.ts`. `checkSyncFreshness` (exported, in `runDoctor` local + `doctorReportRemote` thin-client) is a staleness probe: warns at 24h, fails at 72h or never-synced; future-`last_sync_at` warns ("clock skew") instead of falling through ok; env overrides `GBRAIN_SYNC_FRESHNESS_WARN_HOURS`/`GBRAIN_SYNC_FRESHNESS_FAIL_HOURS` (invalid fall back with once-per-process stderr warn via `_resolveSyncFreshnessHours`); failure messages embed `source.id` so the printed `gbrain sync --source <id>` matches. A source holding a LIVE, non-expired per-source sync lock (`inspectLock(engine, syncLockId(source.id))` from `src/core/db-lock.ts`) is reported as actively syncing (the message names the holder pid + host) and counted in `synced_recently_count`, NOT flagged stale — the live lock is the only honest in-progress signal (checkpoint banking can't distinguish in-progress from wedged: a blocked sync banks its files but writes no anchor). A blocked/failed sync's process has exited (no lock row) and a wedged holder stops refreshing (TTL lapses), so either falls through to the stale path and is never masked; the dynamic `db-lock` import is swallowed to a no-op on a stub engine or pre-lock-table brain, so this can only ADD an in-progress verdict, never suppress a real stale one. The in-progress note is appended to whatever verdict the buckets produce and is empty when nothing is syncing, so steady-state messages stay byte-for-byte unchanged. It has a `localOnly`-gated git short-circuit (`runDoctor` passes `localOnly: true`; `doctorReportRemote` runs in the HTTP MCP server `src/commands/serve-http.ts` and keeps default `false` so that path never walks DB-supplied `local_path` via subprocess — trust boundary). The local predicate mirrors sync's "do work?" gate (HEAD == `last_commit` AND working tree clean via `requireCleanWorkingTree: 'ignore-untracked'` so a quiet repo with only untracked dirs is `unchanged` not SEVERE, AND `chunker_version === CURRENT`); the inline SELECT carries `last_commit + chunker_version + newest_content_at`. The REMOTE path computes lag via `lagFromContentMs(newest_content_at, lastSync, now)` from the stored column, NO git subprocess; LOCAL fall-through and the `< 0` clock-skew check stay on raw wall-clock. Three-bucket count math populates `Check.details = {unchanged_count, synced_recently_count, stale_count}` with the invariant `sum === sources.length`. `checkCycleFreshness` is DELIBERATELY NOT git-short-circuited or content-relativized (`last_commit == HEAD` can't answer "did the full cycle complete?"; a sync can succeed while later cycle phases fail; different axis `last_full_cycle_at`). Pinned by `test/doctor.test.ts` (incl. the IRON-RULE guard banning stale verb names, the sync_freshness boundary matrix, the D4 guard verifying git probes are NEVER called when `localOnly` is unset/false, the three-bucket invariant, and the untracked-folders / remote-never-shells-out trust-boundary cases). `pglite_data_dir` check: fs-only check that runs when a PGLite brain FAILS to connect (`!fastMode && !engine && config.engine === 'pglite'`, placed after `orphan_clones`, before the DB-checks gate; `pgliteDataDirEntry` in `doctor/checks/db-connection.ts`): `computePgliteDataDirCheck(dataDir, diagnosis)` (exported pure fn, `computeWorkerOomLoopCheck` convention) maps the `inspectPgliteDataDir` verdict to a Check — corruption-likely/looks-healthy-but-unopenable/unsupported-layout → `fail` naming `gbrain pglite-repair --dry-run`/`--yes` or the rebuild path, live-lock/missing-dir → `warn`; all `remediation_status: 'human_only'` (Minion remediation needs the DB that is down). Escalates when ≥2 repair attempts failed inside 7 days (unclean-shutdown genesis still active → engine-switch pointer) and reports retained backup-dir inventory (orphan_clones disk-visibility class). Registered in `doctor-categories.ts` OPS_CHECK_NAMES. Pinned by `test/doctor-pglite-datadir.test.ts`. silent-failure checks: `content_hash_duplicates` (single GROUP BY over `(source_id, content_hash)` with FILTER aggregates — never N² — flagging hash groups that hold BOTH a bare and a path-prefixed slug, the wrong-import-root pattern; warn carries sample pairs + the `pages delete` → `purge-deleted --older-than 0` remediation); `undeclared_db_only_pages` (per source with a local repo: markdown pages with no backing file outside every declared + derive-phase-default db_only prefix — the one check deliberately allowed to stat the repo; it finds each source's Git root once with `sourceGitScope` and passes it to `resolveSourceLocalFilePath` as `gitScope`; `connector_database` sources are skipped and counted in the message); `db_only_collector_collision` (configured recipe `output_paths` inside a declared db_only dir — auto-gitignore means sync AND import silently skip the collector's files; same warning fires in sync's `manageGitignore` at config-write time). All warn-level, engine-parity pinned by `test/e2e/doctor-silent-death-parity.test.ts`; units in `test/doctor-silent-death-checks.test.ts`. `graph_signals_coverage` check wired into both `runDoctor` (local) and `doctorReportRemote` (HTTP/JSON thin-client path). Reads `search.graph_signals` config first, falls back to mode default; silent `ok` when disabled. Computes inbound link coverage on the page set; warns at <10% with `gbrain extract all` fix hint; `ok` at ≥30% ("fire on most queries") and 10-29% ("fire occasionally"), each with the percentage embedded. Pinned by cases in `test/doctor.test.ts`. `subagent_capability` check (layer 3 of 3). Resolves subagent model config in runtime order (`models.subagent` > `models.default` > `models.tier.subagent` > built-in default) and warns when the selected model lacks native tool-loop capability (message names the bad value + paste-ready fix `gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6`); also warns when `models.default` would sneak `subagent` into a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests in `test/doctor.test.ts`. `computeWorkerOomLoopCheck(engine)` is the single authoritative OOM-loop signal, unioning supervised `summarizeCrashes(readRecentSupervisorEvents(24)).by_cause.rss_watchdog` (cross-week read via `readRecentSupervisorEvents` so a Monday window can't lose Sunday) + bare-worker `minion_jobs error_text='aborted: watchdog'` count (Postgres-only; the same source `queue_health` subcheck 3 reads). Cap comes from the latest `rss_watchdog_loop` breaker alert's `max_rss_mb`, else `resolveDefaultMaxRssMb()` fallback. fail at breaker-tripped or oomKills≥5, warn at ≥1, null otherwise. `computePoolReapHealthCheck(engine)` is the Postgres-only `pool_reap_health` check reading `readRecentPoolRecoveries(1)` — fail when reconnect failures>0 (reconnect throwing is the actionable signal), warn at ≥10 reaps/hr (pooler thrash), null otherwise. Both registered by the `supervisor` registry entry after the `supervisor` block. The `supervisor` causeStr carries `rss=N (see worker_oom_loop)` and `queue_health`'s watchdog message cross-references `worker_oom_loop`. `DoctorReport.top_issues` + the cause-ranked render header. `worker_oom_loop` + `pool_reap_health` registered under ops in `doctor-categories.ts`. Pinned by `test/doctor-worker-oom-loop.test.ts`, `test/doctor-pool-reap-health.test.ts`. `supervisor_singleton` check, a SEPARATE check from `supervisor` (same split precedent as the niceness check) so a singleton-divergence warn can't clobber the crash/liveness precedence. Runs only when a `started` supervisor event was seen in the last 24h and a live engine is available. Reads the queue-scoped DB lock row (`gbrain_cycle_locks WHERE id = supervisorLockId(queue)`) and compares the lock holder (`holder_host:holder_pid`) against the local pidfile holder via the pure `classifySupervisorSingleton`. `mismatch` → warn (a second supervisor may be running with a different `--max-rss`; message names both holders, the effective cap from the `started` event's `max_rss_mb`, and the fix `gbrain jobs supervisor stop`); `single` → ok (names holder + cap); `no_lock` → no check. PR #6463: `pidfileHost` (PID-file line 3) makes the same pid under a drifted hostname `single` → `ok` + `host_label_drift`; a two-line legacy file warns `same_pid_host_label_differs`; another pid keeps the warning emitted. Best-effort try/catch (silent skip on brains without the lock table). Registered under ops in `doctor-categories.ts` as `supervisor_singleton`. Pinned by `test/supervisor-db-lock.test.ts` + `test/doctor.test.ts`. `checkBatchRetryHealth`: `batch_retry_health` check surfacing Supavisor circuit-breaker incidents. Wired into both `runDoctor` (local) and `doctorReportRemote` (thin-client). Reads last 24h. States: `ok` (zero exhausted in 24h OR <3 from a single site), `warn` (>=3 same-site OR >=5 cross-site), `fail` (>=20 sustained breaker). Surfaces bad `GBRAIN_BULK_*` env at doctor startup. Corrupt-JSONL tolerant. Paste-ready fix hints in every warn/fail message. Also reads `readRecentDbDisconnects(24)` and appends `Disconnect-call audit: N call(s) in 24h (most recent caller: <frame>).` to ALL three message paths so connection-incident signal is greppable from one `gbrain doctor --json` call (module-import wrapped in try/catch so older brains without the audit file degrade silently). Pinned by `test/doctor-batch-retry.test.ts` (10 cases). three checks wired into `runDoctor()` and the JSON envelope, all warn-only with paste-ready fix hints. (1) `checkSourceRoutingHealth(engine)` scans up to 200 pages on federated brains and flags pages whose `source_id` doesn't match what `resolveSourceWithTier()` would have picked for their `source_path`; single-source brains short-circuit to `ok`; the 200-page cap is total across the brain so doctor stays under 5s. (2) `checkOauthConfidentialHealth(engine)` probes registered confidential clients for `/token` reachability. (3) `checkAutopilotLockScope()` (pure, no engine) compares the resolved lock path to `$GBRAIN_HOME`; warns when set but the lock lives elsewhere, with a PID-safe inspection hint (`kill -0 <pid>` before deletion). Pinned by `test/doctor-v0_37_7_checks.test.ts`. `buildChecks(engine, args, dbSource, connectError?): Promise<Check[]>` exported as a test seam; the optional `connectError` is the connect failure captured by the CLI's dead-DB fallback, which the null-engine path turns into a SYNTHESIZED classified `connection` fail entry (so `checks[name=="connection"]` exists in every failure shape — smoke-test branches on it). The `connection` check's failure path classifies via `src/core/pg-access-classify.ts` into a redacted message + `details: {reason, transient, fix_hint}` naming `gbrain db-repair` (deliberately NOT `remediation[]`/`makeRemediationStep` — that lane feeds `--remediate`, whose Minion jobs need the very DB that's down; applicator boundary: `--remediate` = brain-DATA quality with a live engine, `db-repair` = DB ACCESS engine-free). The URL-only `pgbouncerPrepareCheck` helper and the engine-free `db_repair_recurrence` check run BOTH before the connection check and in the dead-DB filesystem lane; `pglite_scale` (engine-fit, warn at ≥1000 pages on pglite) runs in the DB phase. `computeDoctorReport(checks, extras?)` accepts optional `{engine, db_url_source}` which land as additive `DoctorReport.engine` / `DoctorReport.db_url_source` JSON fields (schema_version stays 2). `runDoctor` is a thin wrapper: `buildChecks → computeDoctorReport → render + process.exit`. All 10 `process.exit` sites stay in the wrapper; the two early-return paths (no engine, connection failure) return partial check lists instead of inline exits (observable output identical). Pinned by `test/doctor-behavioral.test.ts` (13 cases: pure aggregation math over `computeDoctorReport`, orchestrator cases for `--fast` skip set + `--json` flag + no-engine partial path + snapshot of load-bearing check names) and `test/doctor-cli-smoke.test.ts` (1 subprocess case spawning `bun run src/cli.ts doctor --json` against a fresh PGLite tempdir, asserting schema_version=2 envelope, status enum, non-empty checks array — the render-path coverage buildChecks-only tests miss; quarantined `.serial` because PGLite write-locks don't play with parallel runners). three checks wired into `runDoctor()` and the JSON envelope: `oversized_pages` (warns on pages exceeding `content_sanity.bytes_warn`), `scraper_junk_pages` (warns on live DB pages matching any junk pattern that escaped ingest), and `content_sanity_audit_recent` (reads the last 7 days of audit events, aggregates by pattern+source). Default scans the 1000 most-recent pages; `--content-audit` opts into a full scan. All three warn-only with paste-ready fix hints (junk → `gbrain sources audit <id>` + `git rm` source-of-truth, oversize → split or accept). two checks wired into `runDoctor()` + the JSON envelope: `quarantined_pages` (counts pages carrying the `quarantine` marker via `engine.executeRaw` JSONB `?` existence, works on PGLite + Postgres; warn-only with a `gbrain quarantine list` hint) and `flagged_pages` (counts `content_flag` pages — searchable but odd; warn-only). Both skip gracefully (status ok, "Skipped") on engines/brains where the probe errors. Pinned by `test/doctor.test.ts`. `home_dir_in_worktree`: filesystem check walking up from `gbrainPath()` toward `$HOME` looking for a `.git` directory (main repo) or `.git` file (linked worktree pointer; Conductor + git-worktrees topology). Walk terminates at `$HOME` so a `.git` above the user's home doesn't false-positive. Honors `GBRAIN_HOME` (appends `.gbrain` to the override). Warn (not fail) with worktree-root path + paste-ready fix pointing at `GBRAIN_HOME` override or moving the brain. `--remediation-plan [--json] [--target-score N]` prints what would run (stable `id`, `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on`); `--remediate [--yes] [--target-score N] [--max-usd N]` submits each plan step as a Minion job in dependency order, re-checking score between steps. `--target-score N` defaults to 90; refuses to start when target exceeds `maxReachableScore()` and lists what's missing. `--max-usd N` is the cron-safety guard — submission refuses when the plan's `est_total_usd_cost` exceeds the cap. JSON envelope adds a `Check.remediation` field (additive, schema_version unchanged). Pinned by tests in `test/doctor.test.ts`. 4 checks: `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` (mitigation surface; math ships later), `voice_gate_health`. Schema health is a two-check pair: `schema_version` resolves through `schemaVersionHealth` (`src/core/schema-version-health.ts`, shared with the remote doctor report; a DB AHEAD of the client warns with an upgrade-this-client hint rather than suggesting migrations), and on ledger-current brains a read-only `schema_columns` check diffs live columns against the expected schema (`detectMissingColumns`, dynamically imported inside the ledger-current branch — positional guard in `test/doctor-schema-column-diff.test.ts`) and warns naming the missing columns with the `gbrain init --migrate-only` hint.Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers the façade: re-exports, `Check`/`DoctorReport` and report scoring, the `buildChecks` flag parse, `runDoctor`, output rendering and `--locks`; every check block lives in a registry entry under `doctor/checks/*` (refactor wave 1 W4 doctor), remediation in `doctor/remediate.ts`, wave checks in `doctor/wave-checks.ts`.-- `src/commands/doctor/check-fix.ts` (+ `heartbeat.ts`, `checks/harness-wiring.ts`, `checks/agent-contract.ts`) — doctor speaks agent contract v1. `Check` carries optional `fix` (stored `Action`; `computeDoctorReport` renders it for the report's transport via `finalizeCheckFixes`, redacted on http), `fix_unavailable_reason` (`check_errored`, `operator_judgement`, `no_safe_automatic_fix`, `unstructured` for legacy prose-only warns), `severity: 'info'` and `readiness_state`; `schema_version` stays 2 and status stays `ok | warn | fail`. Capabilities that are off by choice or not applicable yet (keyless embeddings and their staleness/vector checks, opt-in takes, no serve running, 0 pages, never-cycled empty or <24 h sources, backup before 25 pages+facts or 7 days via `backupCoachingDue`) report `ok` + `info` with the enable command as `fix`; the report adds `capped_by: ['embeddings_disabled']` and, when the `connection` check is present and not ok, `unknown_scores: ['brain']`. `top_issues[]` gain `action` (the rendered fix) beside the legacy `fix` string. `checkError(name, what, err)` is the one "Could not …" shape (a `gbrain db-repair` fix when the error classifies as DB access). `gbrain doctor --only <check>[,…] [--json]` (`parseOnlyChecks`, `onlyNeedsEngine`, CLI `runDoctorOnly`) runs only the entries that emit those names plus the connection lane, engine-free when every name is a filesystem check, else `connectEngine({ probeOnly: true })`; unknown names exit 2 with the valid list; a requested check that produced nothing reports `info`/`not_applicable` (or `check_errored` after an early stop). It is every doctor fix's `verify`. `harness_wiring` reads the gbrain registration from `~/.claude.json`, Codex `config.toml` and `opencode.json`; under `--only harness_wiring` it smoke-tests it (live serve lock owner → `wired_running`; else spawn the registered argv, 15 s, initialize + tools/list + `recall`; `gbrain_status` replies reported with their reason/fix); it writes nothing. #6453: with no PGLite lock, an HTTP registration gets a credential-free 3 s GET of `/health` (`probeHttpRegistration`): gbrain `ok` → `wired_running` + `mcp_access: 'unverified'`; refused loopback `http:` → `http_serve_missing` + fix; else `http_serve_unreachable`/`http_serve_unhealthy`, no fix. `redactRegistrationUrl` strips userinfo, query and fragment from every printed URL (`test/harness-wiring-redaction-6453.test.ts`). `agent_contract` reads the whole size-bounded log (`readAgentContractEvents(Infinity)`, 7-day window) and warns on `internal_error`/suggestion-less envelopes, consent refusals, `derived_cap_exhausted` and `json_document_missing`, with the user-only `consent.preapprove.*` command as fix. `throttleDoctorHeartbeat`: piped doctor progress emits at most one heartbeat per 5 s. Tests: `test/doctor-status-set.test.ts`, `test/doctor-harness-smoke.test.ts`, `test/doctor-day-zero.test.ts` (keyless init then doctor: 0 WARN, health ≥ 90), `test/doctor-remote-parity.test.ts` (run_doctor and CLI agree per shared check; run_doctor renders fixes for its transport). `harness_wiring` with no registration drops every detected harness an enabled plugin lane covers (`enabledPluginLanes`): all covered → `ok`, `reason: plugin_lane_enabled` with the plugins, harnesses and a verify hint (plugin lanes are not smoke-tested); partly covered → the missing-registration warning for the uncovered harnesses only. Claude Code detection also honors `CLAUDE_CONFIG_DIR`.+- `src/commands/doctor/check-fix.ts` (+ `heartbeat.ts`, `checks/harness-wiring.ts`, `checks/agent-contract.ts`) — doctor speaks agent contract v1. `Check` carries optional `fix` (stored `Action`; `computeDoctorReport` renders it for the report's transport via `finalizeCheckFixes`, redacted on http), `fix_unavailable_reason` (`check_errored`, `operator_judgement`, `no_safe_automatic_fix`, `unstructured` for legacy prose-only warns), `severity: 'info'` and `readiness_state`; `schema_version` stays 2 and status stays `ok | warn | fail`. Capabilities that are off by choice or not applicable yet (keyless embeddings and their staleness/vector checks, opt-in takes, no serve running, 0 pages, never-cycled empty or <24 h sources, backup before 25 pages+facts or 7 days via `backupCoachingDue`) report `ok` + `info` with the enable command as `fix`; the report adds `capped_by: ['embeddings_disabled']` and, when the `connection` check is present and not ok, `unknown_scores: ['brain']`. `top_issues[]` gain `action` (the rendered fix) beside the legacy `fix` string. `checkError(name, what, err)` is the one "Could not …" shape (a `gbrain db-repair` fix when the error classifies as DB access). `gbrain doctor --only <check>[,…] [--json]` (`parseOnlyChecks`, `onlyNeedsEngine`, CLI `runDoctorOnly`) runs only the entries that emit those names plus the connection lane, engine-free when every name is a filesystem check, else `connectEngine({ probeOnly: true })`; unknown names exit 2 with the valid list; a requested check that produced nothing reports `info`/`not_applicable` (or `check_errored` after an early stop). It is every doctor fix's `verify`. `harness_wiring` reads the gbrain registration from `~/.claude.json` (+ receipt workspace `.mcp.json`), Codex `config.toml` and `opencode.json`; under `--only harness_wiring` it smoke-tests it (live serve lock owner → `wired_running`; else spawn the registered argv, 15 s, initialize + tools/list + `recall`; `gbrain_status` replies reported with their reason/fix); it writes nothing. #6453: with no PGLite lock, an HTTP registration gets a credential-free 3 s GET of `/health` (`probeHttpRegistration`): gbrain `ok` → `wired_running` + `mcp_access: 'unverified'`; refused loopback `http:` → `http_serve_missing` + fix; else `http_serve_unreachable`/`http_serve_unhealthy`, no fix. `redactRegistrationUrl` strips userinfo, query and fragment from every printed URL (`test/harness-wiring-redaction-6453.test.ts`). `agent_contract` reads the whole size-bounded log (`readAgentContractEvents(Infinity)`, 7-day window) and warns on `internal_error`/suggestion-less envelopes, consent refusals, `derived_cap_exhausted` and `json_document_missing`, with the user-only `consent.preapprove.*` command as fix. `throttleDoctorHeartbeat`: piped doctor progress emits at most one heartbeat per 5 s. Tests: `test/doctor-status-set.test.ts`, `test/doctor-harness-smoke.test.ts`, `test/doctor-day-zero.test.ts` (keyless init then doctor: 0 WARN, health ≥ 90), `test/doctor-remote-parity.test.ts` (run_doctor and CLI agree per shared check; run_doctor renders fixes for its transport). `harness_wiring` with no registration drops each detected harness a plugin lane covers (`enabledPluginLanes`; all → `ok` `plugin_lane_enabled`, not smoke-tested) or whose receipt-recorded config it cannot read (#7422; all → `info` `registration_recorded`); the warning names the rest. Claude Code detection also honors `CLAUDE_CONFIG_DIR`.- - `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. The run is one `withGitListingCache` scope (`src/core/git-visible-files.ts`), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share one `git ls-files` per listing and one "not a git repository" verdict per directory (`ls-files`, `discoverGitRoot`, the census HEAD probe; any repository-changing `sync-git.ts` command or `invalidateGitListingCache()` drops the scope's memo: `test/git-listing-memo.serial.test.ts`). Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` — a live serve owner warns with the exclusive two-step fix, a `pglite_busy` reason `legacy_owner_unverified` fails with details.reason and the refusal's ask_user preview fix, anything else is classified for `db-repair` — and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/grant-new-ops.ts` (D4) emits `grant_new_ops_available` (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; `--operations all` is a disclosed choice, never the fix); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). A pre-gate entry declares the names it only emits with a connected engine in `engineChecks` (#6303), so `onlyNeedsEngine` connects for `--only` of them; `test/doctor-only-engine-checks.test.ts` is the drift guard. To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.+ - `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 126 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. The run is one `withGitListingCache` scope (`src/core/git-visible-files.ts`), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share one `git ls-files` per listing and one "not a git repository" verdict per directory (`ls-files`, `discoverGitRoot`, the census HEAD probe; any repository-changing `sync-git.ts` command or `invalidateGitListingCache()` drops the scope's memo: `test/git-listing-memo.serial.test.ts`). Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` — a live serve owner warns with the exclusive two-step fix, a `pglite_busy` reason `legacy_owner_unverified` fails with details.reason and the refusal's ask_user preview fix, anything else is classified for `db-repair` — and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/grant-new-ops.ts` (D4) emits `grant_new_ops_available` (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; `--operations all` is a disclosed choice, never the fix); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). A pre-gate entry declares the names it only emits with a connected engine in `engineChecks` (#6303), so `onlyNeedsEngine` connects for `--only` of them; `test/doctor-only-engine-checks.test.ts` is the drift guard. To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig` and adds `--no-pull` to its sync hint on a managed brain; `content_hash_duplicates` prescribes `GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force` per wrong-root pair, naming each source when pairs span several, and never a hard purge; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts` (`source_routing_health` exempts zero-page skill-pack sources), `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run, cursor in config `doctor.timeline_history.scan:<sources>` so runs finish a pass (a clean pass stays `ok` until a newer row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts, non-round-trippable rows informational, repair `gbrain repair timeline`; segmented pages counted apart (`segmented_*`), no repair advice), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). `harness-hook-checks.ts` (`harnessHookCarrierChecks`, called from `bootstrap_harness_health`) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warns `harness_hook_duplicates` with a consented re-run carrying the install's `--project`/`--no-capture` choices, a lookalike it did not write warns `harness_hook_unowned` (operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are an `ok` info row; `plugin_lane_collision` iterates `enabledPluginLanes`. `multiSourceDriftCheck` is the one local/remote `multi_source_drift` verdict: on a managed brain (`managedPersistenceEnabled`) its sync advice names `--no-pull` and drops `--include-gitignored`, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. `src/core/multi-source-drift.ts` derives a `git-root`-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (`git_root_skipped`). It drops every walked path sync would refuse (`unsyncableReason(prefix + relPath)`: metafiles such as root `AGENTS.md`/`CLAUDE.md`, pruned dirs, malformed names) before probing, so a same-slug page on `default` is not reported for a file sync never imports (#6681). `graph-health.ts` `graph_coverage`, like onboard's link and timeline coverage, is `ok` (not applicable, with the count) below `MIN_ENTITY_PAGES_FOR_COVERAGE` (5) eligible entity pages. `graph_coverage` and `orphan_ratio` count the entity types the active schema pack declares (#4772, `src/core/schema-pack/entity-types.ts`, resolved per source: brain-wide for `graph_coverage`, the asked source for `orphan_ratio --source`); a pack that does not load makes `graph_coverage` a warn naming the pack (never the old hardcoded list) and `orphan_ratio` answers with an "entity count unknown" caveat instead of a vacuous ok. All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped). `checks/graph-embedding.ts` `checkJunkEntityHubs` (#6158) splits connector contact pages (frontmatter `google_contact_id` or a connector source kind) into `details.connector_twins` with their main-brain `canonical_twin`, never calls them extractor-minted or offers `junk_hub_exempt`, and carries `fix_unavailable_reason: 'operator_judgement'` while the defer-to-twin policy is open.diff --cc docs/architecture/key-files/core-persistence-continued.mdindex 1e90340dc2,b303cb0d36..e6e0fb60d8--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@@ -4,11 -4,13 +4,14 @@@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.The #6188 fence check and fence repair live in [fence repair](core-fence-repair.md). Managed connector ingestion, connector item holds and the no-op kernel (checkpoint validation and the fault seams: [request indexes and fault seams](core-persistence-request-indexes.md)). Also the persistence verb types and errors, database-write and manual links, write attribution and loop-fact retirement; the managed purge of deleted pages is under [memory purge](memory-purge.md).+- `src/core/persistence/effect-settle.ts` — `gbrain sources writer settle-effects <source> (--request-id|--parked-code) [--unsettle] [--dry-run|--apply --expect <plan_hash>]` (`writer_settle_effects`, an administration extension) (#7423, #7378): records `data.settled` (and appends to `data.settlements`) on a failed Git effect no retry can move, never touching its failure, parked targets, request or bytes. It settles only on an exact-target proof re-checked under row locks at apply: each target declared `db_only` in the current binding's gbrain.yml (`sourceDbOnlyDir`), or, for an effect `guardEffectSource` refuses `source_changed` because the source moved to a new worktree (same incarnation, this host owning the active binding), a later committed and pushed Git effect of the current worktree whose `expected_hash` equals the canonical file now and a blob at the already-fetched `@{upstream}` equal to it (no fetch). Withdrawal effects, claims, open recovery records, revoked writers, replaced sources and unknown targets refuse; an effect of the current binding that is not db_only refuses `retry_instead`. The plan hash is doctor --remediate's `computePlanHash` over the brain, source, selector, owner epoch and each proof (`preview_changed` otherwise). Readers that skip settled rows: doctor `parked_effects`, `readParkedGroups`, `readGitPushHolds`, `retryParkedPushes`/`--parked-code`, `retryIndexLockParks`, `sync status`, `failedEffectHistory`; `retryParkedEffects` reports a settled effect as `action: settled`. `retryParkedPushes` also reaches a push that failed without parked targets (#7378, `failedCodes`). Tests: `test/persistence-effect-settle.test.ts` (scenarios in `test/helpers/effect-settle-scenarios.ts`) + the Postgres arm in `test/e2e/w5-persistence-postgres.test.ts`.- - `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target or descends from it, or with `outcome.sync_blocked` when a member sync blocks. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies`, so on owner start) touches only interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command), which the refusal hints point at. Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts`; while a resident PGLite owner (`gbrain serve`, stdio MCP) holds the database, `src/commands/sources-refresh-delegate.ts` runs the refresh inside it through the `writer_refresh` administration operation (trusted CLI registration only) and prints the same result or refusal. The consumer's idle probe applies `refreshFenceClear` to effects like the claims, so a fenced worktree's queued effects do not wake it. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge), Postgres via `test/e2e/worktree-refresh-postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.+ - `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target or descends from it, or with `outcome.sync_blocked` when a member sync blocks. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies` on every consumer topology scan) touches interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. #7679: each row records its holder (`outcome.holder`: host id, hostname, pid, process start; `previous_holder` after a recovery adopts it). A row whose lock is free is orphaned: `resumeWorktreeRefreshes` (every consumer topology scan) also completes an orphaned `syncing` row once every member's `last_commit` reached the target or a descendant, and a plain `gbrain sources refresh` on the owner host finishes any orphaned non-`recovery_required` row through the `--resume` path (`adoptOrphanedRefresh` + `resumeHeld`) before its own refresh, reporting it as `recovered`. A holder recorded on another host is never adopted. `refreshHolderReport` (writer status `worktree_refreshes`, sync status `worktree_refresh`) names the holder, `liveness` (`live` / `orphaned` / `unknown` off the lock's host, from an instant probe of the refresh lock) and a fix naming `--resume`. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command), which the refusal hints point at. Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts` (#7685: `--json` prints a refusal's structured fix as the v1 `fix` RenderedAction when it has one, else the legacy command string; `refresh_in_progress` carries the writer-status read); while a resident PGLite owner (`gbrain serve`, stdio MCP) holds the database, `src/commands/sources-refresh-delegate.ts` runs the refresh inside it through the `writer_refresh` administration operation (trusted CLI registration only) and prints the same result or refusal. The consumer's idle probe applies `refreshFenceClear` to effects like the claims, so a fenced worktree's queued effects do not wake it. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge), `test/worktree-refresh-orphan-7679.test.ts` (SIGKILL mid-syncing, live-holder no-steal), Postgres via `test/e2e/worktree-refresh-postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.+ - `src/core/persistence/git-gap.ts` + `src/commands/sources-git-gap.ts` + `src/commands/doctor/checks/db-ahead-of-git.ts` — git-canonical memory, wave G1 (`docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census`), read-only. `declaredDatabaseOnly` is the one predicate for pages that may not have a tracked file, tested in order: a read-only mirror source, a private page (`isPrivatePage`), an alias-private page (`isDerivationPrivate`), lineage-private (computed in SQL from `privatePagesFilterFragment`), `database_only_reason`, a `storage.db_only` prefix (`isSourceDbOnlySlug`, refusing an invalid gbrain.yml), a never-filed derive-phase page (page-prepare.ts `isNeverFiledDerivedPage`: no `source_path`/`source_uri` under `DERIVE_PHASE_DB_ONLY_DEFAULTS`), a path the checkout's Git ignores (`ignoredPaths`: filter-free `check-ignore -z --stdin`, tracked files never reported, exit 1 = none, null when Git cannot answer). The equality contract compares a committed blob with the page's export view (`readExportPage`, withdrawals overlaid; the census reads a batch's views with `readExportPages`, the same snapshots in two statements, #7617): an inline blob parsed as reconcile parses a canonical file, aligned with the stored type, subtype and #6429 stamp and compared by `reconcileCanonical` digest; a segmented page by the Git blob id of its streamed export. HEAD is read with hardened plumbing only (`readHeadTree`: one `ls-tree -r -l -z --full-tree` under the source's directory; `readBlobs`: `cat-file --batch` in calls of at most 64 MiB) and the working tree by hashing raw bytes (`worktreeBlobOid`), never `git status`/`git diff`, so no repository filter, textconv or fsmonitor runs. `gbrain sources git-gap <id> [--sample n] [--json]` (trusted local CLI, not an MCP op) puts every live page in one state (`equal`, `database_ahead`, `git_ahead` when the sync import record's `blob_oid`/`disk_blob_oid` differs from HEAD, else folded into `database_ahead` and counted in `database_ahead_without_import_record`, `declared_database_only` per class, `undeclared_database_only`, `worktree_only`, `unparseable`, `unsafe_path`), reports the working tree separately, and counts rows with no Git home (unfenced active facts, fenced facts on a missing page or a page without a committed file, links whose `link_source` is not in `DERIVED_LINK_SOURCES`, timeline rows on pages without a file), open `sync-hold` records by code and parked effect targets by kind and code. Each 256-page batch reads in its own read-only transaction. Doctor `db_ahead_of_git` runs the census per non-archived source whose directory is a Git checkout (others are only counted) under `GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS` (default 10 s) and the entry deadline; it is always `ok` (informational) and lists totals only, a source the budget stopped or never reached as partial. Tests: `test/git-gap-census.test.ts` (PGLite and Postgres).+ - `src/core/persistence/git-declared.ts` + `src/core/persistence/git-canonical-schema.ts` (migration `git_canonical_declared`) — git-canonical memory, wave G7a: the declared database-only classes of a strict source (`sources.config.canonical = "git"`, default off). `strictPageClass` judges a page by its slug and prior file (`declaredPathClass`: `db_only_prefix` for a `storage.db_only` dir, `derive_folder` for a never-filed derive-phase page; G3's indexer reads the same function) and then its rendered content (`privacyClass`: `private`, `alias_private`, or `lineage_private` from the same SQL remote reads use, `privatePagesFilterFragment`, over the page's own values). `page-prepare.ts` `prepareFileTarget` asks it before it builds a strict file target: a declared page gets no target (no file, no door commit, no Git effect), an untracked ignored target is `git_ignored`, a page turning private gets the removal of the file it still has in the worktree or at HEAD, and a path whose `filter` attribute is `lfs` passes `assertLfsTarget` only with `storage.git_lfs` and a checkout that configures the LFS filter (`git_lfs_not_enabled`). `preparePrivateTransition` (page-prepare.ts) is that removal for other writers (GBRA-60). In `publishMutation` and `publishGroup`, `assertNoPrivateCommit` refuses a file target carrying a private page's bytes before anything is written (`git_private_commit_refused`; a group rolls back whole), and `declareStrictPublication` (after apply, before the door commit) refuses a declared page's file or an undeclared file-less page (`git_home_required`), stamps `pages.database_only_reason` and, for a privacy class, clears `source_path`/`source_uri` in the transaction of the door commit that removed the file. A managed import builds its own file target, so it meets only these publication checks. `assertStrictGitHome` is the refusal for writers with no file form yet (G4, G5). The managed writer guard (`writer-guard-schema.ts`) refuses rows of a strict source unless the writer declares `gbrain.git_protocol` (`withCoordinatedWrite` does), behind the `git_canonical_brain.strict_sources` counter kept by `sources` triggers (`git_protocol_required`, mapped in `publication-failure.ts`). The guard reads its state as the writing role and fails closed: a hidden or missing `persistence_brain` or `git_canonical_brain` row, or a source or page row hidden by row-level security, raises `writer_coordinator_required` (`managed_writer_guard:unreadable_state`), and the counter refuses a recount under RLS on `sources` (`test/writer-fence-fail-closed-7636.test.ts`). The census (`git-gap.ts`) adds `database_only_source` (a source with no checkout) and maps the stamped reasons to their own classes. Tests: `test/git-canonical-declared-g7a.test.ts` (both engines).- `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`; `page_body_segmented` is a write error code, so a verb refused by a segmented target keeps it as `write_error` and canonical code under the frozen `invalid_params` (caller class, not retryable) on both the receipt and the pre-admission path (`runMemoryWrite`). `remember` reads a segmented entity page up to PAGE_MAX_BYTES back whole (`materializedPage`) for its inferred-target checks and fence write; over it, a named or inferred entity refuses before admission with `segmentedRememberRefusal` (fix: remember with `infer_entity: false`), never a silent `NO_ENTITY` (`test/large-pages/segmented-remember-refusal.test.ts`); `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.- - `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.+ - `src/core/persistence/database-write.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `ontology_propose` (one entity page key) uses 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. Unmanaged brains keep the engine calls. Tests: `test/managed-ontology-propose.test.ts`.+ - `src/core/persistence/manual-links.ts` — `prepareManualLinkMutation`, the preparer of the `add_link` / `remove_link` page mutations a managed brain submits (G5, dispatched from `service.ts`; on the IPC and semantic re-prepare lists, kept-tier fence edits in `trust/page-write.ts`). The authored edge is a row of the from page's `## Links` fence (`links-fence.ts`): the preparer upserts or removes the row at the snapshot's revision (a segmented page read back whole through `wholeBodySnapshot`) and publishes the page with `preparePageMutation`; the publication's canonical projection and the apply both project the fence (`links-fence-projection.ts`), so an idempotent add (fence unchanged, a no-op publication) still has its edge. `add_link` also deletes the database-only twin of the edge it fences (same endpoints, type and provenance, no origin); `remove_link` deletes the matching database-only edges (origin_field not `links_fence`, a provenance outside `MANAGED_LINK_SOURCES`) and, when the body has no fence, the orphaned fence edges, with their manual dated statements, and reports `removed` as the edge count it took away; edges a reconciliation producer derives from the text stay, and the result names them (`derived_from_text: [{ link_type, link_source }]` plus a `message` to edit the page text instead). The op handlers keep their validation, `dry_run` and result shape (`{ status }`, `{ status, removed }`); unmanaged brains keep the engine calls. Tests: `test/managed-links-fence.test.ts` (+ Postgres arm), `test/managed-writers-w3.test.ts`.- `src/core/persistence/{attribution,attribution-schema,context}.ts` — write attribution. `withCoordinatedWrite(engine, sourceIds, fn, attribution)` sets `gbrain.write_sources` and the transaction-local actor (`gbrain.write_request`, `gbrain.write_principal_kind`, `gbrain.write_principal_id`) in one round trip and restores them on exit; a nested scope keeps the outer actor. The argument is required: `requestAttribution(row)` for journaled publication (coordinator, forget), `maintenanceAttribution(engine)` (verified local writer, else the CLI registration, else `application`/`host:<id>`; no request) for derived facts, takes/timeline/link extraction, materialization, concept provenance, connector freshness and verify cleanup, `principalAttribution` for manual links (the caller) and source lifecycle (the topology principal). `withWriteAttribution` sets only the actor, for unmanaged legacy transactions; `maintenanceTransaction(engine, fn)` wraps it in one transaction, and every unmanaged direct writer runs its write (or one bounded batch) in it (the `system-of-record.md` "unattributed" list is empty; derivers pass their taint as `maintenanceTransaction(engine, fn, trust)`, see `trust/taint.ts`). `attribution-schema.ts` (migration `f1_write_attribution`; migration-only like the facts DDL, so columns land last on fresh and upgraded brains) adds nullable columns and BEFORE ROW triggers: `facts`/`takes`/`timeline_entries` carry `write_*` (created_by, immutable once set) and `last_write_*` + `last_written_at` (moved only when a classified content column changes; a NULL actor records an unattributed writer; under `gbrain.fact_withdrawal_stamp`, which only the facts insert guard sets, a facts update of `expired_at`/`valid_until` alone keeps them, migration v264); `pages.revision_*` is stamped when `knowledge_revision` changes; `page_versions.write_*` copies the snapshotted revision's actor and `archived_*` names the archiving write. `write_request_id` is `persistence_requests.id` with no foreign key; all-NULL reads as unrecorded. Every column of the three tables is classified content, projection (embeddings, `takes.updated_at`) or attribution, and a new column must be classified and the function re-created; the writer guard treats attribution-only facts/takes updates as projections. Tests: `test/write-attribution.test.ts`, `test/write-attribution-legacy.test.ts` (writer inventory) and `test/write-attribution-<family>.test.ts` (each routed unmanaged writer path; `write-attribution-timeline-10k.slow.test.ts` checks bounded batches at 10k pages) on PGLite; Postgres direct and PgBouncer through `test/e2e/write-attribution-postgres.test.ts`.- `src/core/persistence/loop-fact-retirement.ts` — #5869 commitment-fact retirement for closed loops, one coordinator mutation on every brain (operation `loops_close`, intent `retire_loop_fact`, dispatched from `service.ts`): expires the fact and strikes its `## Facts` fence row (context `loop closed: <status>`) through the entity page publication in one transaction; no withdrawal tombstone. The shared rule (also `loopFactDrift`, used by doctor `loop_facts_drift` and `gbrain repair loop-facts`): only a fact in the loop's source that no other open loop references, re-checked under row locks at publication (`shared_with_open_loop`, `source_mismatch` otherwise). `retireLoopFact(ctx, loopId)` submits with the caller's grant and maps a refusal or pending write to `fact_expired: false, retryable: true, reason`. Tests: `test/loops-close-fact.serial.test.ts` (+ Postgres twin).- `src/core/persistence/connector-authority.ts` -- classifies each Google/GitHub source as `connector_database` (managed, unbound), `bound` or `unmanaged` from `persistence_brain.enabled` and the source binding row. File-lane audits (doctor `undeclared_db_only_pages`, backup coverage) read it so a leftover cache directory at `local_path` is never taken for canonical files. Tests: `test/doctor-silent-death-checks.test.ts`, `test/backup-coverage.serial.test.ts`.diff --cc docs/architecture/key-files/core-persistence.mdindex 6ec1682538,f58abe7055..10a7f1d069--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@@ -6,13 -6,11 +6,11 @@@ The page operations that submit througConnector ingestion, item holds, checkpoint validation and the single-write fast path (`switches.ts`) continue in [Core Persistence (continued)](core-persistence-continued.md).Managed facts extraction (withdrawn-candidate skip and recovery, conversation facts batches, the unmanaged derived index) is in [Core Persistence (managed facts)](core-persistence-facts.md).- - `src/core/persistence/connector-google-receipts.ts` — the managed Google attachment-repair preparer checks account/thread/message ownership from the current canonical snapshot, changes only the owned receipt frontmatter field, and installs provider-free text projections under the existing source-before-page publication locks. Page identity/revision, current authorization, source incarnation and file recovery guards remain mandatory; body, unrelated frontmatter, tags and the withdrawal ledger are preserved. It schedules no embeddings, loop detection or fact extraction. `connector-sync.ts` admits this narrow mutation and banks its committed receipts through the existing managed connector checkpoints.-- `src/core/persistence/authority.ts` — durable write authority. `submissionAuthority` records the caller's grant ceiling on every write request (scopes, operations, slug prefixes, delegated namespace and, for a delegated job, its native `subagentId` when a positive safe integer); `authorizeWrite` re-checks it against the CURRENT principal at publication and replay. For a delegated OAuth client the current namespace is the stored `delegated_slug_prefixes` in `prefixes` mode, or only `wiki/agents/<retained subagentId>/*` for the native `job` form (prefixes NULL); anything else allows nothing, and it always intersects the original accepted prefixes, bound tools, scope and source, so a revoked, narrowed or switched grant or a foreign or invalid job id denies (`test/persistence-page-authority.test.ts`, Postgres: `test/e2e/minions-authority-parity.test.ts`). #5994: a context carrying `replayAuthority` (set only by `gbrain repair failed-writes`) gets that stored authority back from `submissionAuthority` (`replayedAuthority`): same source incarnation or refused, `databaseOnlyReason`/`takeHoldersUsed` dropped for admission to recompute, then `authorizeWrite` and page visibility against the live grant.- - `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders under the lease lock. Dry-run deletes nothing. Never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still need physical-root checks. Activation increments `persistence_brain.mode_epoch` (migration 183), which the writer admin-state hash includes. A non-connector source whose recorded `local_path` no longer exists (unclaimed, or claimed by this host) refuses `source_changed` with detail `source_path_missing`, naming the source, the path and the `sources set-path` / `sources remove` exits (the claimed checkout filled in), in `--dry-run` too (#5206, `test/activation-missing-source-path.test.ts`). The report's `warnings[]` (dry run and real run) carries one `git_durability_not_enabled` entry per filesystem source the effect runner's policy (`gitDurabilityPolicy`) would leave non-durable, with `enable_command`, a read-only `git-durability --enable --dry-run` fix and the note that enabling re-queues skipped Git effects; `persistence-admin.ts` also prints them to stderr without `--json`, and activation proceeds (#5182, `test/writer-activate-durability-warnings-5182.test.ts`).+ - `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders under the lease lock. Dry-run deletes nothing. Never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still need physical-root checks. Activation increments `persistence_brain.mode_epoch` (migration 183), which the writer admin-state hash includes. A non-connector source whose recorded `local_path` no longer exists or is relative (unclaimed, or claimed by this host) refuses `source_changed` with detail `source_path_missing`, naming the source, the path and the `sources set-path` / `sources remove` exits (the claimed checkout filled in), in `--dry-run` too (#5206, `test/activation-missing-source-path.test.ts`). The report's `warnings[]` (dry run and real run) carries one `git_durability_not_enabled` entry per filesystem source the effect runner's policy (`gitDurabilityPolicy`) would leave non-durable, with `enable_command`, a read-only `git-durability --enable --dry-run` fix and the note that enabling re-queues skipped Git effects; `persistence-admin.ts` also prints them to stderr without `--json`, and activation proceeds (#5182, `test/writer-activate-durability-warnings-5182.test.ts`).- `src/core/persistence/git-durability-policy.ts` + `git-durability-administration.ts` — whether the persistence owner commits and pushes page writes through its Git effect is a per-host-binding setting (#5182): `persistence_host_bindings.git_durability` (`enabled` | `disabled` | NULL, migration v234, column SQL kept out of the replayed schema blob as `PERSISTENCE_GIT_DURABILITY_COLUMN_SQL`). `gitDurabilityPolicy(binding, root)` is tri-state and fail-closed: a recorded value wins, NULL falls back to the legacy post-commit-hook probe, a probe error fails the effect instead of skipping it; `effects.ts` takes its per-root verdict from it. `gitDurabilityState` renders `on`/`off`/`unknown` for `writer status` and `writer activate`'s `git_durability` listing. `planGitDurabilityCatchUp`/`requeueGitDurabilityCatchUp` re-queue the Git effects completed `durability_not_enabled` while the setting was off by resetting the existing rows, never inserting under `UNIQUE(request_id, kind)`. The verb `writer_git_durability` (`gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [--dry-run]`, administration-gated like the other writer verbs) runs a read-only `git push --dry-run` probe before enabling (codes `git_branch_unborn`, `git_checkout_required`, `git_detached_head`), wires the repo-scoped credential under `gbrain.durability.managedcredential` from a 0600 `--pat-file` (`pat_file_unreadable` otherwise) and retries the worktree's parked pushes (codes in `GIT_PUSH_CODES`; `retry-effects <source> --parked-pushes` does the same without a credential). `sources push` (`managedPushRefusal` in `workspace-push.ts`), `bootstrap verify`'s `checkPushProbe` and the skill-pack writer guard name this route on a managed worktree (#5606). Pinned by `test/persistence-admin-git-durability.test.ts`, `test/managed-push-remedy.serial.test.ts`.-- `src/core/persistence/effect-git.ts` (`pushGitRoot`) + `git-push-holds.ts` — a Git effect's push tries a plain push first; a non-fast-forward rejection runs this executable's `gbrain git commit-push --push-only --keep-checkout` as a child (never on the owner's event loop, never a `gbrain` from PATH), which merges the moved remote in memory and pushes without moving the checkout or running its pre-push hook, so `sources refresh` stays the only importer. A true conflict holds the effect `integrate_conflict` with the user's `--keep-checkout --resolve` choice. `readGitPushHolds` counts, per source, Git effects retrying or parked on a push code with the conflict state and one fix; read by doctor `parked_effects` and `sync status` `git_push_holds` (`next` falls back to a parked or conflicted hold's fix). Pinned by `test/pathological/h2-git-effect-moved-remote.test.ts`.+- `src/core/persistence/effect-git.ts` (`pushGitRoot`) + `git-push-holds.ts` — a Git effect's push tries a plain push first; a non-fast-forward rejection runs this executable's `gbrain git commit-push --push-only --keep-checkout` as a child (never on the owner's event loop, never a `gbrain` from PATH), which merges the moved remote in memory and pushes without moving the checkout or running its pre-push hook, so `sources refresh` stays the only importer. A true conflict holds the effect `integrate_conflict` with the user's `--keep-checkout --resolve` choice. `readGitPushHolds` counts, per source, Git effects retrying or parked on a push code with the conflict state and one fix; read by doctor `parked_effects` and `sync status` `git_push_holds` (`next` falls back to a parked or conflicted hold's fix). A hold in a worktree the source is no longer bound to is `former_worktree` and its fix is the settle preview (#7378). Pinned by `test/pathological/h2-git-effect-moved-remote.test.ts`.- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, queued, running or recovering effects (the predicate activation uses; each exit says what clears it, and a failing links or facts-backstop effect settles after five attempts), held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `failedEffectHistory` lists terminally failed effects as history (`failed_effects` on the dry run and the applied report, never blockers), each with its code and the exit that retries it: retry-effects for parked targets and failed Git, withdrawal, links and facts-backstop effects, `repair embedding-effects` for a failed embedding effect, none for `embedding_zero_norm` or an effect whose source was archived, replaced or removed (`test/pathological/a15-deactivate-exits.test.ts` runs every printed exit and checks it clears its entry); `physicalRootBlockers(engine, mode)` (#5914 [R9a]) adds `physical_root` for this host's owned checkouts, probed as the mode's real run will: strict `assertPhysicalRoot` for managed, `assertPhysicalRootReservation` for the classic pre-activation release, so each preview lists exactly what its real operation refuses on; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`. See [persistence stalls](persistence-stalls.md).- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. `SEGMENTED_WRITER_FLOOR` (`page-body/writer-floor.ts`): a seven-day writer below it or unmarked keeps `pages.segmented_storage` off (`page-body/limits.ts`, doctor `segmented_storage`); marked rows of any role meet the floor (ingest log: two partial indexes, v254/v259). Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.diff --cc src/commands/persistence-admin.tsindex d538527cd8,ae81516444..0ae079d4c9--- a/src/commands/persistence-admin.ts+++ b/src/commands/persistence-admin.ts@@@ -169,7 -163,7 +170,7 @@@ export function parsePersistenceAdminAr'--source-ids': 'source_ids', '--scopes': 'scopes', '--allowed-operations': 'allowed_operations','--slug-prefixes': 'slug_prefixes', '--limit': 'limit', '--before': 'before','--admin-intent': 'admin_intent', '--expected-state': 'expected_state', '--request-id': 'request_id', '--pat-file': 'pat_file', '--parked-code': 'parked_code',- '--state': 'state', '--group-by': 'group_by', '--since': 'since', '--code': 'code', '--origin': 'origin', '--category': 'category', '--expect': 'expect',- '--state': 'state', '--group-by': 'group_by', '--since': 'since', '--code': 'code', '--origin': 'origin', '--category': 'category', '--operation': 'operation',++ '--state': 'state', '--group-by': 'group_by', '--since': 'since', '--code': 'code', '--origin': 'origin', '--category': 'category', '--expect': 'expect', '--operation': 'operation',};const arrays = new Set(['source_ids', 'scopes', 'allowed_operations', 'slug_prefixes']);const seen = new Set<string>();diff --cc src/core/cli-flag-registry.generated.tsindex b991035336,e413979d9b..f71f7354e7--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@@ -19,8 -19,8 +19,8 @@@ export const CLI_FLAG_REGISTRY: Record<'anomalies': ['--all', '--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--request-id', '--sigma', '--since', '--source'],'append': ['--brain', '--expect-tail', '--expected-revision', '--file', '--force', '--help', '--json', '--region', '--request-id', '--separator', '--source'],'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--install', '--json', '--legacy-lock', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--only', '--path', '--prefer-postgres', '--probe', '--repo', '--require-db', '--skip-verify', '--source', '--statement-timeout', '--uninstall', '--url', '--yes'],- 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--apply', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expect', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--unsettle', '--usage', '--wait', '--warn-only', '--yes'],- 'autopilot': ['--apply', '--batch', '--brain', '--channel', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--quiet', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--restart-only', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],- 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operation', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],++ 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--apply', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expect', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operation', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--unsettle', '--usage', '--wait', '--warn-only', '--yes'],+ 'autopilot': ['--apply', '--batch', '--brain', '--channel', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--pause', '--phase', '--quiet', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--restart-only', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--timings', '--wait'],'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--since', '--source'],@@@ -113,7 -113,7 +113,7 @@@'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--day', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--run', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],++ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--timings', '--to', '--wait', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],@@@ -127,7 -127,7 +127,7 @@@'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--timings', '--wait', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],++ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],diff --cc src/core/persistence/page-mutations.tsindex f989d98173,df5428c676..9e238637ca--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@@ -391,18 -399,11 +401,19 @@@ export async function preparePageAdmisslet binding = boundAtStart;const sandbox = ctx.viaSubagent === true && !(ctx.allowedSlugPrefixes?.length);const configuredWriteThrough = !/^(false|0|off|no)$/i.test(writeThroughSetting ?? 'true');- const root = source.local_path || repoPath;- const writeThrough = configuredWriteThrough && !sandbox && !input.databaseOnly;+ const configuredRoot = source.local_path || repoPath;+ const root = configuredRoot && isAbsolute(configuredRoot) ? configuredRoot : null;+ // Checkout paths belong to a host binding; sources.local_path may name+ // another host's original checkout after a verified ownership transfer.+ const localRoot = binding ? binding.owner_host_id === localHostId() && binding.local_path+ ? join(binding.local_path, binding.relative_path) : null : root;+ // #7324: a declared db_only page is canonical in the database, so its detach restore publishes database-only even+ // where write-through would re-create its file (a managed checkout); assertRestoreOrigin still requires the file gone.+ const databaseOnly = input.databaseOnly ?? (input.operation === 'restore_page' && p.detach === true && localRoot+ && isSourceDbOnlySlug(localRoot, slug, 'not_db_only') ? 'detached' : undefined);+ const writeThrough = configuredWriteThrough && !sandbox && !databaseOnly;if (sandbox) authority.databaseOnlyReason = 'subagent_sandbox';- else if (input.databaseOnly) authority.databaseOnlyReason = input.databaseOnly;+ else if (databaseOnly) authority.databaseOnlyReason = databaseOnly;else if (!configuredWriteThrough) authority.databaseOnlyReason = 'disabled_by_config';else if (!root && !binding) authority.databaseOnlyReason = 'no_repo_configured';if (p.local_dir !== undefined) {diff --cc src/core/persistence/sync-pass.tsindex 3f330a7c0c,36242c23ed..df3747d2ae--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@@ -628,7 -639,7 +639,7 @@@ export async function readShadowLevel(econst settings = await readLevelSettings(engine, context, scope, input);timings.setup = t();if (!settings) return null;- const { slugMode, exclude, pack, mirror, strategy, includeHidden, keepDbPrefixes, storage, workingConfig, metafilePages } = settings;- const { slugMode, exclude, pack, mirror, strategy, includeHidden, keepDbPrefixes, workingConfig, metafilePages, strict } = settings;++ const { slugMode, exclude, pack, mirror, strategy, includeHidden, keepDbPrefixes, storage, workingConfig, metafilePages, strict } = settings;const sourceRelative = (gitPath: string) => (scope ? gitPath.slice(scope.length + 1) : gitPath);let metafilePage: (gitPath: string) => boolean = () => false;// Eligibility of a path outside the cached tree (every path of the tree is eligible); origins validate per call: a@@@ -797,9 -809,8 +809,9 @@@spelling: legacySpelling.has(path) ? 'legacy' : twins.has(path),episodeUnsatisfied: input.pass ? !!input.pass.episodeFullId && live && (record ? pages.fullEpisode[at!] : undefined) !== input.pass.episodeFullId: input.full === true && live,- fullObligation: input.pass ? !!input.pass.episodeFullId : input.full === true,+ derivedCurrent: live && pages.derivedCurrent(at!), fullObligation: input.pass ? !!input.pass.episodeFullId : input.full === true,keepDb: !mirror && keepDbPrefixes.length > 0 && row && isKeepDbSlug(pages.slug[at!]!, keepDbPrefixes),+ dbOnly: row && isDeclaredDbOnlySlug(pages.slug[at!]!, storage),openWork: row && open.pageIds.has(Number(pages.id[at!])) || open.origins.has(origin),};return { state, ...(row ? { at } : {}), ...(legacyPageless ? { legacyPageless } : {}) };@@@ -818,7 -829,7 +830,7 @@@}).then(found => { timings.legacy = t(); return found; }): new Map<string, string>();- const classifiedKey = JSON.stringify([treeKey, mode, input.pass?.episodeFullId ?? null, input.full === true, mirror, keepDbPrefixes, storage?.db_only ?? [], pack?.identity ?? null, baselineCommit, !!input.pass?.bootstrap, [...colonRefused].sort()]);- const classifiedKey = JSON.stringify([treeKey, mode, strict, input.pass?.episodeFullId ?? null, input.full === true, mirror, keepDbPrefixes, pack?.identity ?? null, baselineCommit, !!input.pass?.bootstrap, [...colonRefused].sort()]);++ const classifiedKey = JSON.stringify([treeKey, mode, strict, input.pass?.episodeFullId ?? null, input.full === true, mirror, keepDbPrefixes, storage?.db_only ?? [], pack?.identity ?? null, baselineCommit, !!input.pass?.bootstrap, [...colonRefused].sort()]);const reuse = snapshot.changed && priorClassified?.key === classifiedKey ? reusableMatched(priorClassified.paths, matchedUnchanged({ pages, tree, byOrigin, claimants, holds: holdByGitPath, markers, open,changed: confirmChangedPaths(pages, snapshot.changed, (sourcePath, slug) => gitPathOf(pageOrigin(sourcePath, slug))), indexDelta, spelled: path => twins.has(path) || legacySpelling.has(path), originOf })) : null;// A round that reuses nothing lets the previous round's paths go before it builds its own: one level held, not two.@@@ -952,11 -963,10 +964,11 @@@ async function readLevelSettings(engine]);const settled = <T>(read: PromiseSettledResult<T>): T => { if (read.status === 'rejected') throw read.reason; return read.value; };if (settled(company)) return null;+ const storage = (() => { try { return loadStorageConfig(root); } catch { return null; } })();return { slugMode: settled(slugModeRead), exclude: settled(excludeRead), pack: settled(packRead), mirror: settled(mirrorRead), workingConfig: settled(workingRead),- metafilePages: settled(metafilePagesRead), strategy: input.pass?.strategy ?? (context.source.config?.strategy as string | undefined) ?? 'markdown',+ metafilePages: settled(metafilePagesRead), strict: context.source.config?.canonical === 'git', strategy: input.pass?.strategy ?? (context.source.config?.strategy as string | undefined) ?? 'markdown',includeHidden: [...new Set([...input.pass?.includeHidden ?? [], ...(settled(includeHiddenRead) ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)].map(v => v.endsWith('/') ? `${v}**` : v))],- keepDbPrefixes: (() => { try { return loadStorageConfig(root)?.keep_db ?? []; } catch { return []; } })() };+ keepDbPrefixes: storage?.keep_db ?? [], storage };}/** A failed mark, proof or delta read: the round reads again without them (it aborted a Postgres snapshot). */diff --cc src/core/persistence/sync-status.tsindex 520e396f93,a962f4e027..32390f5955--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@@ -319,12 -335,14 +335,14 @@@ export async function readSyncStatus(enconst admissionSql = syncAdmissionSettingSql(4);const [source] = await engine.executeRaw<{ incarnation: string; last_commit: string | null; last_sync_at: Date | string | null; drain_lock: boolean; pass_value: PassRow['value'] | null; pass_updated_at: Date | string | null; withheld: DeletesWithheld | null;admission_stored: string | null; admission_row_value: string | null; admission_set_at: string | null; admission_pinned: boolean | null; admission_destructive: boolean | null;- writeback_failed: string | null }>(+ writeback_failed: string | null; refresh: RefreshProbeRow | string | null }>(`SELECT s.incarnation::text AS incarnation, s.last_commit, s.last_sync_at, EXISTS (SELECT 1 FROM gbrain_cycle_locks l WHERE l.id=$7) AS drain_lock,p.completed_keys->0 AS pass_value, p.updated_at AS pass_updated_at, w.completed_keys->0 AS withheld, ${admissionSql.columns}, ${syncAdmissionEffectSql(7, 's')},- (SELECT r.request_id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='git' AND e.state='failed'+ (SELECT r.request_id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='git' AND e.state='failed' AND NOT (e.data ? 'settled')AND e.request_id IN (SELECT id::uuid FROM jsonb_array_elements_text(CASE WHEN jsonb_typeof(p.completed_keys->0->'obligations'->'converged'->'writeback')='array'- THEN p.completed_keys->0->'obligations'->'converged'->'writeback' ELSE '[]'::jsonb END) AS w(id)) ORDER BY e.id LIMIT 1) AS writeback_failed FROM sources s+ THEN p.completed_keys->0->'obligations'->'converged'->'writeback' ELSE '[]'::jsonb END) AS w(id)) ORDER BY e.id LIMIT 1) AS writeback_failed,+ (SELECT row_to_json(f) FROM (SELECT r.id,r.worktree_id,r.state,r.source_ids,r.outcome,r.updated_at,w.owner_host_id FROM persistence_worktree_refreshes r+ LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id WHERE s.id=ANY(r.source_ids) AND r.state IN ${ACTIVE_REFRESH_STATES_SQL} LIMIT 1) f) AS refresh FROM sources sLEFT JOIN op_checkpoints p ON p.op=$2 AND p.fingerprint=s.id||':'||s.incarnation::textLEFT JOIN op_checkpoints w ON w.op=$3 AND w.fingerprint=s.id||':'||s.incarnation::text${admissionSql.joins}diff --cc test/fixtures/goldens/cli/tools-json.jsonindex 3040885ed2,0f55a875dc..258c9c0361--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@@ -2,8 -2,8 +2,8 @@@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 262792,- "stdoutSha256": "812ee4d094e1ff2456bfea1cd565a32bce5fb60c85419c766c8f46ae378055db",- "stdoutBytes": 264473,- "stdoutSha256": "f5647f0a0d45a36ed8685afa000792cef233379d012eeceec6fa2f9366d1b0ee",++ "stdoutBytes": 264563,++ "stdoutSha256": "0d71d7f1367627c5f9c27d3d7a9b09513131117000012eed0d35ab9ede69095f","toolNames": ["remember","entity",