Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/master' into capy/w14-pr2
garrytand0fb09429c8d
diff --cc CHANGELOG.mdindex f929d765f1,e69debacc5..818e1d9fa7--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -10,41 -10,32 +10,67 @@@ credits are retained; no result has beeidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased] - fix wave 14 PR2 (GBRA-79)++**A managed brain's Git durability is now a recorded owner setting, and the managed-worktree refusals name the command to run instead of a dead end.**+- On a managed brain the persistence owner commits and pushes page writes through its Git effect, but until now that depended on a post-commit hook the owner probed for on every pass, and nothing told an operator how to turn it on (#5182). `gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>]` records the setting on the host binding (migration v232 adds the nullable `git_durability` column; nothing recorded keeps today's probe), `--enable` runs a read-only push probe first and re-queues the Git effects skipped while it was off, and `--pat-file` wires the repo-scoped push credential and retries the parked pushes. `sources push`, `bootstrap verify`'s `push_probe` and the skill-pack writer guard now name that route on a managed worktree instead of a bare `writer_coordinator_required` (#5606). Doctor's new `foreign_ownership_marker` names the stale ownership stamp that blocks a claim (#5808), `writer activate` on an already-managed brain answers `already_enabled` with the owner process to check (#5514), `gbrain repair managed-sync-orphans` retires sync bookkeeping nothing current can resume (#5459), transcript re-ingest deletes a stale part through the coordinator instead of refusing (#5235), `gbrain sources set-strategy <id> <strategy>` persists a code source's sync strategy and refuses under an unfinished managed run (contributed by @rokas-tarasevicius, supersedes #5955), and `bootstrap status` tells a project-scoped Codex MCP connection you manage yourself apart from "nothing wired" (#4082).++On a managed brain the persistence owner commits and pushes page writes through its Git effect, but until now that depended on a post-commit hook the owner probed for on every pass, and nothing told an operator how to turn it on (#5182). `gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>]` records the setting on the host binding (migration v234 adds the nullable `git_durability` column; nothing recorded keeps today's probe), `--enable` runs a read-only push probe first and re-queues the Git effects skipped while it was off, and `--pat-file` wires the repo-scoped push credential and retries the parked pushes. `sources push`, `bootstrap verify`'s `push_probe` and the skill-pack writer guard now name that route on a managed worktree instead of a bare `writer_coordinator_required` (#5606). Doctor's new `foreign_ownership_marker` names the stale ownership stamp that blocks a claim (#5808), `writer activate` on an already-managed brain answers `already_enabled` with the owner process to check (#5514), `gbrain repair managed-sync-orphans` retires sync bookkeeping nothing current can resume (#5459), transcript re-ingest deletes a stale part through the coordinator instead of refusing (#5235), `gbrain sources set-strategy <id> <strategy>` persists a code source's sync strategy and refuses under an unfinished managed run (contributed by @rokas-tarasevicius, supersedes #5955), and `bootstrap status` tells a project-scoped Codex MCP connection you manage yourself apart from "nothing wired" (#4082).++## To take advantage of this release++`gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor`+warns about a partial migration:++```bash- gbrain apply-migrations --yes --no-autopilot-install # v232: persistence_host_bindings.git_durability++gbrain apply-migrations --yes --no-autopilot-install # v234: persistence_host_bindings.git_durability+gbrain doctor --json | grep -E 'schema_version|foreign_ownership_marker|sync_failures'+```++On a managed brain, `gbrain sources writer status <source> --json` now reports `git_durability` (`on`, `off` or `unknown`); `gbrain sources writer git-durability <source> --enable --dry-run` previews the switch.++### Itemized changes+- - **Git durability as an owner setting (#5182, [R7i]/[R7ii]).** `persistence_host_bindings.git_durability` (`enabled` | `disabled` | NULL) via migration v232 on PGLite, Postgres and PgBouncer transaction mode; `gitDurabilityPolicy` resolves `enabled`/`disabled` from the binding and consults the legacy hook probe only when nothing is recorded (fail-closed on probe error). The effect worker's per-root probe routes through it. New verb `writer git-durability` (`writer_git_durability` admin operation; `--enable`, `--disable`, `--pat-file`, `--dry-run`, the usual `--admin-intent`/`--expected-state`) with error codes `git_branch_unborn`, `git_checkout_required`, `git_detached_head`, `pat_file_unreadable`. `writer activate` and `writer status` list `git_durability` per binding. Catch-up re-queues `durability_not_enabled` Git effects without inserting under `UNIQUE(request_id, kind)`.++- **Git durability as an owner setting (#5182, [R7i]/[R7ii]).** `persistence_host_bindings.git_durability` (`enabled` | `disabled` | NULL) via migration v234 on PGLite, Postgres and PgBouncer transaction mode; `gitDurabilityPolicy` resolves `enabled`/`disabled` from the binding and consults the legacy hook probe only when nothing is recorded (fail-closed on probe error). The effect worker's per-root probe routes through it. New verb `writer git-durability` (`writer_git_durability` admin operation; `--enable`, `--disable`, `--pat-file`, `--dry-run`, the usual `--admin-intent`/`--expected-state`) with error codes `git_branch_unborn`, `git_checkout_required`, `git_detached_head`, `pat_file_unreadable`. `writer activate` and `writer status` list `git_durability` per binding. Catch-up re-queues `durability_not_enabled` Git effects without inserting under `UNIQUE(request_id, kind)`.+- **Managed-worktree refusals name the route (#5606).** `gbrain sources push` on a managed canonical worktree refuses with the owner's `writer status` and `writer git-durability` commands; `bootstrap verify`'s `push_probe` reports the managed route instead of a failure; the skill-pack writer guard and doctor's skill checks point at `gbrain call --source <source> import_skill_proposal`.+- **Doctor `foreign_ownership_marker` (#5808).** A stamp or reservation beside a source checkout whose brain or worktree this brain does not know is listed with its path and the operator step (`docs/guides/write-refusals.md#foreign-ownership-marker`).+- **`writer activate` already managed (#5514).** Reason `already_enabled` with a `next_action` naming the owner process to check, instead of a generic refusal.+- **`gbrain repair managed-sync-orphans --source <id>` (#5459).** Explicit-only, preview-bound: retires failure rows with no cursor, cursors recorded by a principal that is no longer an active local writer, and superseded pre-options cursors; live pending requests and resumable cursors are kept. Doctor `sync_failures` names it; `docs/guides/repair.md#managed-sync-orphans` and the sync-unblock runbook explain when.+- **Transcripts on a managed brain (#5235).** A stale transcript part is deleted through the coordinator (`delete_page` with the expected revision) instead of refusing the re-ingest.+- **`gbrain sources set-strategy <id> <markdown|code|auto>` (PR #5955).** Persists the sync strategy on the source; refuses `sync_run_unfinished` (exit 1) while a managed sync run is unfinished, naming the resume and the orphan-repair commands. Contributed by @rokas-tarasevicius.+- **`bootstrap status` and Codex project config (#4082).** A `<workspace>/.codex/config.toml` MCP server is reported `partial` (detected, not verified) with an adopt hint; `gbrain bootstrap hooks --adopt --harness codex` records it after a passing verify in the versioned `<home>/bootstrap/adopted-connections.json` sidecar (sha256 over transport, URL and header names; no tokens) and the phase reads `done`; a drifted or removed table reads `partial` again. Nothing is written to the Codex config and no receipt registration is fabricated.++### For contributors+- - New modules: `src/core/persistence/git-durability-policy.ts`, `git-durability-administration.ts`, `managed-sync-orphans.ts` (+ `src/core/repair/managed-sync-orphans.ts`), `src/commands/sources-strategy.ts`, `src/core/bootstrap/adopted-connections.ts`, `adopt-connection.ts`, `src/core/schema-migrations/v232-persistence-git-durability.ts`.++- New modules: `src/core/persistence/git-durability-policy.ts`, `git-durability-administration.ts`, `managed-sync-orphans.ts` (+ `src/core/repair/managed-sync-orphans.ts`), `src/commands/sources-strategy.ts`, `src/core/bootstrap/adopted-connections.ts`, `adopt-connection.ts`, `src/core/schema-migrations/v234-persistence-git-durability.ts`.+- Tests (each proven failing on master first): `test/persistence-admin-git-durability.test.ts`, `test/doctor-foreign-ownership-marker.test.ts`, `test/persistence-activation.test.ts`, `test/repair-managed-sync-orphans.test.ts`, `test/transcripts-managed-ingest.test.ts`, `test/managed-push-remedy.serial.test.ts`, `test/doctor-skill-checks.test.ts`, `test/sources-strategy.test.ts`, `test/bootstrap-adopted-connection.serial.test.ts`. Doctor goldens regenerated (new check row; schema column count +1).+- Two hunks on wave 13 PR1's files (`effect-git.ts` resolver call, `hardenBrainRepo` managed refusal) ship as patches with the integrator, not in this PR.++ ## [0.60.160.0] - 2026-10-10++ **Keyword search finds words glued to Chinese, Japanese or Korean text, and you choose which source a self-registered agent writes to when you approve it.**++ A note titled `升级PostgreSQL17` used to be invisible to a keyword search for `PostgreSQL17`, because the index stored the whole glued run as one word. The index now splits wherever CJK text meets Latin letters or digits, and upgrading rebuilds only the pages and chunks that contain such a boundary. When an agent registers itself over OAuth and asks to connect, the approval page now has a "Write source" picker, so you decide which source it reads and writes before it gets a token. On a classic self-hosted Postgres brain, an agent whose page write is refused stops retrying and tells you the real fix: write the file, commit it and run `gbrain sync`. After you upgrade, run `gbrain reindex-search-vector` only if you changed `GBRAIN_FTS_LANGUAGE`; it now rebuilds page vectors too.++ ### Itemized changes++ - **CJK/Latin boundaries in keyword search** (#6370). Every indexing `to_tsvector` and the title query read through a new `gbrain_fts_input()` that inserts a space at each CJK↔ASCII letter or digit boundary; text without CJK is unchanged byte for byte. The upgrade migration rebuilds only rows containing a boundary, in checkpointed batches.+ - **`gbrain reindex-search-vector` rebuilds page vectors** (#6374). Pages now get the same vector the write path builds, so a language change reaches titles and timelines, not only chunks. A page edited during the rebuild is skipped and reindexed by its own save, and facts you withdrew stay out of the index.+ - **Choose a self-registered client's source at first consent** (#6202). Clients that registered themselves through dynamic client registration show a "Write source" picker on their first approval, listing your active sources. Approving with or without a change counts as the client's one first consent; later changes go through the Agents page or `gbrain auth rescope --client`. Clients registered before this release keep read-only consent. A migration adds the `oauth_clients.registered_via` marker.+ - **Classic Postgres write refusals ask instead of retrying** (#6277). `owner_unavailable` with `detail: unbound_source` now renders `retryable: false` and `fix.next: ask_user`, and its guidance says write, commit, `gbrain sync --source <id>`. The guide in [write-refusals](docs/guides/write-refusals.md#unbound-sources-on-postgres) and six skills cover the classic path.+ - **One JSON document on stdout** (#6386): `gbrain sync status --json`, `gbrain sync unblock --json` and `gbrain embed --facts --json` write their JSON to stdout, not stderr.+ - **Bootstrap verify waits like a normal write** (#6356): `gbrain bootstrap verify` uses the CLI write wait instead of a fixed 5 seconds, and a write still pending names its next step.+ - **Local reranker setup** (#6381): the llama-server reranker guide points at the llama.cpp maintainers' model file, the recipe's default names the `qwen3-reranker-0.6b` alias the guide uses, and `gbrain models doctor` reports `config` when the server scores a relevant and an unrelated passage the same.+ - **Codex session hooks** (#6399): a Codex rollout that has only a header ends as `empty_session`, not `parser_drift`.+ - **Link validation** (#6266): the link validator resolves relative links from the page's own directory, the same way link extraction does.+ - **Search latency budget** (#6400): the query-embedding deadline starts at the first embed request, so time spent before it no longer eats the vector search's budget.++ ### For contributors++ - CONTRIBUTING warns before the `git reset --hard` in the line-ending refresh.+ - Every pglite-snapshot cache key in `e2e.yml`, `test.yml` and `stress.yml` also hashes `src/core/audit/redact-connection-info.ts`, which the schema closure now imports.++ Contributed by @dovstern, @javieraldape, @daveove, @benswinney and @dhruvatr.+## [0.60.159.0] - 2026-10-10**Captured memory stops leaking away: failed chats retry until they import, long messages stay whole, sessions file under their own source, and fence writers refuse instead of dropping rows.**diff --cc docs/architecture/key-files/core-persistence.mdindex c34d870f99,0afb44e2a2..9e4b45bb6b--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@@ -10,8 -10,6 +10,8 @@@ Connector ingestion, item holds, checkp- `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 active filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards before enabling managed writes. 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 transaction lock. Dry-run reports candidates without deletion. Registration 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 require canonical 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`).- - `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 v232, 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. `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/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. `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/managed-sync-orphans.ts` + `src/core/repair/managed-sync-orphans.ts` — `gbrain repair managed-sync-orphans --source <id>` (#5459), explicit-only and preview-bound (approved set, `preview_changed` on drift). `classifyManagedSyncOrphans` (read-only; doctor `sync_failures` names the repair when it finds any) takes the source's managed-sync bookkeeping and classes each row `no_cursor` (a failure row with no cursor to resume), `principal_unadoptable` (an unfinished cursor recorded by a principal that is no longer an active local writer, by join on the recorded principal) or `superseded` (a pre-options cursor a later run replaced), and keeps `pending_request_live` and `resumable` rows untouched. `retireManagedSyncOrphan` retires one row atomically. `sources set-strategy` points at it when an unfinished run blocks a strategy change. Pinned by `test/repair-managed-sync-orphans.test.ts`; `test/repair-explicit-only.test.ts` pins its place last in `REPAIR_KINDS`.- `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, uncommitted effects, held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `--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. 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 scripts/module-size-limits.tsvindex dab8abc2ea,9186027731..9e2904bea2--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@@ -28,13 -28,13 +28,13 @@@ src/core/minions/queue.ts 2528 ratchetsrc/commands/init.ts 1878 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)-src/commands/bootstrap.ts 2134 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)+src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)src/core/minions/worker.ts 1774 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler)-src/commands/sources.ts 2054 ratchet +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row+src/commands/sources.ts 2059 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row- src/core/link-extraction.ts 2358 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass)+ src/core/link-extraction.ts 2379 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validatorsrc/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh- src/commands/hook.ts 1926 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import+ src/commands/hook.ts 1928 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_driftsrc/core/chunkers/code.ts 1598 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate)src/core/config.ts 1932 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)diff --cc src/core/bootstrap/verify.tsindex 922e107222,f1cb4d7d8f..7f3574fc5b--- a/src/core/bootstrap/verify.ts+++ b/src/core/bootstrap/verify.ts@@@ -28,9 -28,9 +28,10 @@@*/import { managedPersistenceEnabled } from '../persistence/ownership.ts';+import { managedFilesystemRootFor } from '../persistence/filesystem-guard.ts';import { submitPageMutation } from '../persistence/page-mutations.ts';import { withCoordinatedWrite } from '../persistence/context.ts';+ import { pendingReceiptOf, pollCommand, resolveCliWriteWaitMs, WRITE_WAIT_ENV } from '../persistence/write-wait.ts';import { maintenanceAttribution } from '../persistence/attribution.ts';import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';import { createHash, randomUUID } from 'node:crypto';diff --cc src/core/cli-flag-registry.generated.tsindex 8bbe1b518f,b17a2a2249..2e34a49dda--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@@ -47,7 -47,7 +47,7 @@@ export const CLI_FLAG_REGISTRY: Record<'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],++ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],diff --cc src/core/persistence/schema.tsindex e238b2d769,20e68fc583..851fed83d9--- a/src/core/persistence/schema.ts+++ b/src/core/persistence/schema.ts@@@ -193,13 -192,3 +193,13 @@@ export const PERSISTENCE_SCHEMA_STATEMEPERSISTENCE_CONSUMERS_TABLE_SQL,MANAGED_WRITER_GUARD_SQL,] as const;++/**- * #5182: the per-host Git-durability opt-in column, added by v232 on an++ * #5182: the per-host Git-durability opt-in column, added by v234 on an+ * existing brain. Deliberately NOT part of the schema statement list: a fresh+ * install gets the column from CREATE TABLE above, and replaying an ALTER on+ * every init would take an ACCESS EXCLUSIVE lock on the bindings table each+ * time the schema blob runs. NULL means "not recorded" (legacy hook probe+ * decides); 'enabled'/'disabled' is the operator's explicit setting.+ */+export const PERSISTENCE_GIT_DURABILITY_COLUMN_SQL = `ALTER TABLE persistence_host_bindings ADD COLUMN IF NOT EXISTS git_durability text CHECK (git_durability IN ('enabled','disabled'))`;diff --cc src/core/schema-migrations/latest.generated.tsindex ed00b02841,7cdcfafcf0..663df87dfd--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@@ -4,4 -4,4 +4,4 @@@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.- export const LATEST_SCHEMA_VERSION = 232;-export const LATEST_SCHEMA_VERSION = 233;++export const LATEST_SCHEMA_VERSION = 234;diff --cc src/core/schema-migrations/registry.generated.tsindex bb00e2138c,66df0323fc..c9ec792b87--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@@ -232,7 -232,8 +232,9 @@@ import { v228 } from './v228-memory-purimport { v229 } from './v229-trust-allow-rules.ts';import { v230 } from './v230-trust-generation.ts';import { v231 } from './v231-fact-purge-lookup-indexes.ts';- import { v232 } from './v232-persistence-git-durability.ts';+ import { v232 } from './v232-fts-cjk-boundary.ts';+ import { v233 } from './v233-oauth-client-registered-via.ts';++import { v234 } from './v234-persistence-git-durability.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@@ -464,4 -465,5 +466,6 @@@ export const MIGRATIONS: Migration[] =v230,v231,v232,+ v233,++ v234,];diff --cc src/core/schema-migrations/v234-persistence-git-durability.tsindex 5153b752bf,0000000000..4d32011f1fmode 100644,000000..100644--- a/src/core/schema-migrations/v234-persistence-git-durability.ts+++ b/src/core/schema-migrations/v234-persistence-git-durability.ts@@@ -1,26 -1,0 +1,26 @@@+import type { Migration } from './types.ts';+import { PERSISTENCE_GIT_DURABILITY_COLUMN_SQL } from '../persistence/schema.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// #5182 per-host Git-durability opt-in for managed worktrees. The column is+// nullable with no default, so Postgres adds it as a catalog-only change (no+// row rewrite, no table scan). The ALTER lives only here and in CREATE TABLE+// (src/core/persistence/schema.ts), never in the replayed schema blob, so an+// existing brain takes the lock exactly once. Postgres bounds the wait so a+// busy writer makes the migration fail fast and retry instead of queueing+// behind it; PGLite has no concurrent writers and PgBouncer transaction mode+// sees SET LOCAL inside the migration's own transaction.- export const v232: Migration = {- version: 232,++export const v234: Migration = {++ version: 234,+ name: 'persistence_git_durability',+ idempotent: true,+ sql: PERSISTENCE_GIT_DURABILITY_COLUMN_SQL,+ sqlFor: { postgres: `SET LOCAL statement_timeout = '30s'; SET LOCAL lock_timeout = '2s';\n ${PERSISTENCE_GIT_DURABILITY_COLUMN_SQL}` },+ verify: async (engine) => {+ const rows = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM information_schema.columns+ WHERE table_name='persistence_host_bindings' AND column_name='git_durability'`);+ return Number(rows[0]?.n ?? 0) === 1;+ },+};diff --cc test/fixtures/goldens/migrations/records.jsonindex 3921ec6753,e866bdb20c..7fc5a2b23d--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@@ -1,6 -1,6 +1,6 @@@{"golden": {- "count": 227,- "count": 228,++ "count": 229,"gaps": [17,18,@@@ -41,7 -49,7 +49,7 @@@"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 232,- "latest": 233,++ "latest": 234,"records": [{"handler": {@@@ -3456,28 -3464,47 +3464,70 @@@"verify": "absent","version": 231},+ {+ "handler": {+ "form": "arrow",+ "helpers": [+ "CHECKPOINT",+ "FTS_CJK_BOUNDARY_REGEX",+ "FTS_INPUT_FUNCTION_SQL",+ "backfillChunkVectors",+ "backfillPageVectors",+ "checkpointKey",+ "chunkSearchVectorTriggerFnSql",+ "getFtsLanguage",+ "migrationNotice",+ "pageSearchVectorTriggerFnSql",+ "quietMigrationNotices"+ ],+ "sha256": "b7a73381f45a5bcdc68e07cd45b2126cd7091140747f69e224abfc39bf8c7959"+ },+ "idempotent": true,+ "name": "fts_cjk_boundary",+ "sql": {+ "length": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 232+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "oauth_client_registered_via",+ "sql": {+ "length": 489,+ "sha256": "5767fc58a79405b9ff3bbcc291a988f42e6f41553a1bbf062c132b3306f04ba3"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 233++ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "persistence_git_durability",+ "sql": {+ "length": 131,+ "sha256": "7d1ffa9ac4f3f4a8ea7213dd1b49e23d485f193665eac9fdf14077c6680c7291"+ },+ "sqlFor": {+ "pglite": "absent",+ "postgres": {+ "length": 205,+ "sha256": "254cf68f1c5924bf19bbe7ed7951d8e83d9704a2f55611721ca5f08d6e5ff394"+ }+ },+ "transaction": "absent",+ "verify": {+ "form": "arrow",+ "helpers": [],+ "sha256": "22a7e9ac067d3d7821610d62f4f60f1343fd127a8715c0e9ec4c47dd475bdac8"+ },- "version": 232++ "version": 234}],"versions": [@@@ -3707,7 -3734,8 +3757,9 @@@229,230,231,- 232+ 232,- 233++ 233,++ 234]},"normalizer": "migrations-record-v1"diff --cc test/persistence-admin-git-durability.test.tsindex 0c661d7c5e,0000000000..6b74345306mode 100644,000000..100644--- a/test/persistence-admin-git-durability.test.ts+++ b/test/persistence-admin-git-durability.test.ts@@@ -1,252 -1,0 +1,252 @@@+/**+ * #5182 / #5808: per-host Git-durability opt-in for managed worktrees.+ *+ * [R7i] The policy resolver is tri-state and fail-closed: a recorded setting+ * wins over the legacy hook probe in both directions, and an absent+ * setting defers to the probe, whose failure is an error, not "durable".+ * [R7ii] `writer git-durability` is a real admin verb: it refuses an unclaimed+ * source, names an unborn branch as unborn (not "detached HEAD"),+ * requires the admin-intent handshake, records the setting on the+ * binding, re-queues the Git effects skipped while durability was off+ * and the worker then commits them; `--disable` wins over a hook.+ * `--pat-file` refuses a readable token file before writing anything.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';+import { PERSISTENCE_ADMIN_OPERATIONS } from '../src/core/persistence/admin-contract.ts';+import { parsePersistenceAdminArgs } from '../src/commands/persistence-admin.ts';+import { gitDurabilityPolicy, gitDurabilityState, planGitDurabilityCatchUp } from '../src/core/persistence/git-durability-policy.ts';+import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';+import { submissionAuthority } from '../src/core/persistence/authority.ts';+import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';+import { publishMutation } from '../src/core/persistence/coordinator.ts';+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';+import { serializePageToMarkdown } from '../src/core/markdown.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';- import { v232 } from '../src/core/schema-migrations/v232-persistence-git-durability.ts';++import { v234 } from '../src/core/schema-migrations/v234-persistence-git-durability.ts';+import { PERSISTENCE_GIT_DURABILITY_COLUMN_SQL, PERSISTENCE_SCHEMA_STATEMENTS } from '../src/core/persistence/schema.ts';+import { gitAsync } from './helpers/git-publication.ts';+import { withEnv } from './helpers/with-env.ts';+import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';++let engine: PGLiteEngine;+const roots: string[] = [];+const config = { engine: 'pglite' as const, embedding_disabled: true };+const page = (body: string) => ({ type: 'note', title: 'Example', compiled_truth: body.trim(), timeline: '', frontmatter: {} });+beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+}, 120_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); for (const root of roots) rmSync(root, { recursive: true, force: true }); });++/** Everything runs under a private GBRAIN_HOME so the host identity, the credential store and the file-transport flag are the test's own. */+async function isolated<T>(run: (home: string) => Promise<T>): Promise<T> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-git-durability-')); roots.push(home);+ try {+ return await withEnv({ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,+ GBRAIN_GIT_ALLOW_FILE_TRANSPORT: '1' }, async () => { await registerLocalWriter(engine, 'cli'); return run(home); });+ } finally { await disposePersistenceConsumer(engine); }+}++async function gitRoot(home: string, opts: { commit?: boolean; remote?: boolean } = {}): Promise<string> {+ const root = join(home, `root-${randomUUID().slice(0, 8)}`); mkdirSync(root);+ await gitAsync(root, 'init', '-q', '-b', 'main');+ await gitAsync(root, 'config', 'user.name', 'Example Writer');+ await gitAsync(root, 'config', 'user.email', '[email protected]');+ if (opts.commit !== false) {+ writeFileSync(join(root, 'initial.md'), 'Initial\n');+ await gitAsync(root, 'add', 'initial.md'); await gitAsync(root, 'commit', '-q', '-m', 'Initial');+ }+ if (opts.remote) {+ const remote = join(home, `remote-${randomUUID().slice(0, 8)}.git`); mkdirSync(remote);+ await gitAsync(remote, 'init', '-q', '--bare');+ await gitAsync(root, 'remote', 'add', 'origin', remote); await gitAsync(root, 'push', '-q', '-u', 'origin', 'main');+ }+ return root;+}++async function claimedSource(root: string) {+ const sourceId = `durability-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ const binding = await claimWorktree(engine, sourceId, root, localHostId());+ return { sourceId, binding };+}++/** A committed page write whose Git effect is queued (the persistence-effects fixture, minus the hook). */+async function committedWrite(root: string, sourceId: string, slug: string) {+ const binding = (await getWorktreeBinding(engine, sourceId, localHostId()))!;+ await engine.putPage(slug, page('Before'), { sourceId });+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const file = join(root, `${slug}.md`); mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, serializePageToMarkdown(snapshot.page, snapshot.tags));+ const ctx: OperationContext = { engine, config, remote: false, dryRun: false, sourceId, logger: { info() {}, warn() {}, error() {} } };+ const authority = await submissionAuthority(ctx, 'put_page', sourceId, binding.source_incarnation, slug);+ const admitted = await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId,+ sourceIncarnation: binding.source_incarnation, slug, pageId: snapshot.page.id, requestId: randomUUID(),+ callerIntent: { content: 'After' }, intent: { content: 'After' }, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });+ const row = (await claimNextWrite(engine, localHostId()))!;+ expect(row.id).toBe(admitted.id);+ const result = await publishMutation(engine, row, { observedRevision: snapshot.revision, file: { path: file, root, content: 'After' },+ apply: async tx => { await tx.putPage(slug, page('After'), { sourceId }); return {}; } }, localHostId());+ expect(result.state).toBe('committed');+ return row.id;+}+async function gitOutcome(requestId: string) {+ const [row] = await engine.executeRaw<{ state: string; outcome: Record<string, unknown> | null; data: Record<string, unknown> }>(+ "SELECT state,outcome,data FROM persistence_effects WHERE request_id=$1::uuid AND kind='git'", [requestId]);+ return row;+}+async function runEffects() {+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='git'");+ await runPersistenceEffects(engine, config, { hostId: localHostId(), limit: 10 });+}++describe('[R7i] git durability policy is tri-state and fail-closed', () => {+ const probeCalls: string[] = [];+ const probe = (answer: boolean | Error) => async (root: string) => { probeCalls.push(root); if (answer instanceof Error) throw answer; return answer; };++ test('a recorded setting wins over the legacy hook probe in both directions, and the probe is not consulted', async () => {+ probeCalls.length = 0;+ expect(await gitDurabilityPolicy({ git_durability: 'enabled' }, '/srv/a', probe(false))).toEqual({ durable: true, source: 'binding' });+ expect(await gitDurabilityPolicy({ git_durability: 'disabled' }, '/srv/a', probe(true))).toEqual({ durable: false, source: 'binding' });+ expect(probeCalls).toEqual([]);+ });++ test('an absent setting defers to the probe, and a probe failure is an error rather than durable', async () => {+ expect(await gitDurabilityPolicy({ git_durability: null }, '/srv/b', probe(true))).toEqual({ durable: true, source: 'legacy_hook' });+ expect(await gitDurabilityPolicy(null, '/srv/b', probe(false))).toEqual({ durable: false, source: 'no_hook' });+ await expect(gitDurabilityPolicy(undefined, '/srv/b', probe(new Error('hooks dir unreadable')))).rejects.toThrow('hooks dir unreadable');+ expect(gitDurabilityState({ git_durability: 'enabled' })).toBe('on');+ expect(gitDurabilityState({ git_durability: 'disabled' })).toBe('off');+ expect(gitDurabilityState(null)).toBe('unknown');+ });+- test('the column is created by CREATE TABLE on a fresh brain and by v232 on an existing one, never by the replayed schema blob', async () => {++ test('the column is created by CREATE TABLE on a fresh brain and by v234 on an existing one, never by the replayed schema blob', async () => {+ const [column] = await engine.executeRaw<{ data_type: string; is_nullable: string }>(+ "SELECT data_type,is_nullable FROM information_schema.columns WHERE table_name='persistence_host_bindings' AND column_name='git_durability'");+ expect(column).toEqual({ data_type: 'text', is_nullable: 'YES' });- expect(v232.sql).toBe(PERSISTENCE_GIT_DURABILITY_COLUMN_SQL);- expect(v232.sqlFor?.postgres).toContain("lock_timeout = '2s'");- expect(v232.idempotent).toBe(true);- expect(await v232.verify!(engine)).toBe(true);++ expect(v234.sql).toBe(PERSISTENCE_GIT_DURABILITY_COLUMN_SQL);++ expect(v234.sqlFor?.postgres).toContain("lock_timeout = '2s'");++ expect(v234.idempotent).toBe(true);++ expect(await v234.verify!(engine)).toBe(true);+ expect(PERSISTENCE_SCHEMA_STATEMENTS.some(statement => statement.includes('ADD COLUMN IF NOT EXISTS git_durability'))).toBe(false);+ await expect(engine.executeRaw("UPDATE persistence_host_bindings SET git_durability='maybe' WHERE false")).resolves.toBeDefined();+ const [{ ok }] = await engine.executeRaw<{ ok: boolean }>(+ `SELECT EXISTS(SELECT 1 FROM information_schema.check_constraints WHERE check_clause LIKE '%git_durability%') AS ok`);+ expect(ok).toBe(true);+ });+});++describe('[R7ii] writer git-durability verb', () => {+ test('the verb is an admin operation with a CLI spelling, and its flags parse', () => {+ expect(PERSISTENCE_ADMIN_OPERATIONS).toContain('writer_git_durability');+ const parsed = parsePersistenceAdminArgs('writer', ['git-durability', 'notes', '--enable', '--dry-run', '--json']);+ expect(parsed).toMatchObject({ operation: 'writer_git_durability', params: { source_id: 'notes', enable: true, dry_run: true }, json: true });+ expect(parsePersistenceAdminArgs('writer', ['git-durability', 'notes', '--pat-file', '/tmp/token']).params.pat_file).toBe('/tmp/token');+ expect(() => parsePersistenceAdminArgs('writer', ['git-durability', 'notes', '--enable=yes'])).toThrow(/does not accept a value/);+ });++ test('an unclaimed source is refused with the claim as the next step; --enable and --disable together are refused', () => isolated(async () => {+ await expect(runPersistenceAdministration(engine, 'writer_git_durability', { source_id: `nobody-${randomUUID().slice(0, 6)}`, enable: true, dry_run: true }))+ .rejects.toMatchObject({ code: 'writer_registration_required' });+ await expect(runPersistenceAdministration(engine, 'writer_git_durability', { source_id: 'x', enable: true, disable: true, dry_run: true }))+ .rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('not both') });+ await expect(runPersistenceAdministration(engine, 'writer_git_durability', { source_id: 'x', dry_run: true }))+ .rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('--enable, --disable, or --pat-file') });+ }));++ test('an unborn branch is named as unborn, a detached HEAD as detached, and a plain directory as not a checkout', () => isolated(async home => {+ const unborn = await claimedSource(await gitRoot(home, { commit: false }));+ const refusal = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: unborn.sourceId, enable: true, dry_run: true }).catch(error => error);+ expect(refusal).toMatchObject({ code: 'git_branch_unborn' });+ expect(refusal.message).toContain('unborn');+ expect(refusal.message).not.toContain('detached');+ expect(refusal.suggestion).toContain('git add -A && git commit');+ const detachedRoot = await gitRoot(home);+ await gitAsync(detachedRoot, 'checkout', '-q', '--detach');+ const detached = await claimedSource(detachedRoot);+ await expect(runPersistenceAdministration(engine, 'writer_git_durability', { source_id: detached.sourceId, enable: true, dry_run: true }))+ .rejects.toMatchObject({ code: 'git_detached_head' });+ const plain = join(home, 'plain'); mkdirSync(plain);+ const notGit = await claimedSource(plain);+ await expect(runPersistenceAdministration(engine, 'writer_git_durability', { source_id: notGit.sourceId, enable: true, dry_run: true }))+ .rejects.toMatchObject({ code: 'git_checkout_required' });+ // A refused preview recorded nothing.+ for (const { sourceId } of [unborn, detached, notGit]) expect((await getWorktreeBinding(engine, sourceId, localHostId()))!.git_durability).toBeNull();+ }));++ test('enable needs the admin-intent handshake, records the setting, re-queues skipped Git effects and the worker commits them', () => isolated(async home => {+ const root = await gitRoot(home, { remote: true });+ const { sourceId } = await claimedSource(root);+ // Without a hook and nothing recorded, a managed write's Git effect completes as skipped.+ const first = await committedWrite(root, sourceId, 'alpha');+ const second = await committedWrite(root, sourceId, 'beta');+ await runEffects();+ expect(await gitOutcome(first)).toMatchObject({ state: 'committed', outcome: { reason: 'durability_not_enabled' } });+ expect(await gitOutcome(second)).toMatchObject({ state: 'committed', outcome: { reason: 'durability_not_enabled' } });+ expect((await gitAsync(root, 'status', '--porcelain', '--', 'alpha.md', 'beta.md')).trim()).not.toBe('');++ const preview = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, dry_run: true });+ expect(preview).toMatchObject({ dry_run: true, git_durability: { before: null, after: 'enabled' }, current_policy: { durable: false, source: 'no_hook' },+ branch: 'main', tracking_remote: 'origin', push_probe: { ok: true }, catch_up: { planned: 2 }, queued_catch_up: 0 });+ expect((preview.fix as { argv: string[] }).argv.join(' ')).toContain('--admin-intent writer_git_durability --expected-state ');+ expect((await getWorktreeBinding(engine, sourceId, localHostId()))!.git_durability).toBeNull();+ expect((await planGitDurabilityCatchUp(engine, (await getWorktreeBinding(engine, sourceId, localHostId()))!)).map(effect => effect.relative_path).sort()).toEqual(['alpha.md', 'beta.md']);++ await expect(runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true }))+ .rejects.toMatchObject({ code: 'writer_admin_intent_required' });+ await expect(runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, admin_intent: 'writer_activate', expected_state: 'f'.repeat(64) }))+ .rejects.toMatchObject({ code: 'writer_admin_intent_required' });+ const stale = await reviewedWriterIntent(engine, 'writer_git_durability');+ const applied = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, ...stale });+ expect(applied).toMatchObject({ applied: true, git_durability: { before: null, after: 'enabled' }, queued_catch_up: 2 });+ expect((await getWorktreeBinding(engine, sourceId, localHostId()))!.git_durability).toBe('enabled');+ expect(await gitOutcome(first)).toMatchObject({ state: 'queued', outcome: null, data: { durability_catch_up: 1 } });++ // The recorded setting is part of the admin state: the pre-apply fingerprint is stale now.+ await expect(runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, disable: true, ...stale }))+ .rejects.toMatchObject({ code: 'writer_admin_state_changed' });+ const status = await runPersistenceAdministration(engine, 'writer_status', { source_id: sourceId }) as { bindings: Array<Record<string, unknown>> };+ expect(status.bindings.find(binding => binding.source_id === sourceId)).toMatchObject({ git_durability: 'enabled', git_durability_state: 'on' });++ // The worker runs the re-queued effects: both files are committed and pushed, with no hook anywhere.+ await runEffects();+ expect(await gitOutcome(first)).toMatchObject({ state: 'committed', outcome: { git: 'committed' } });+ expect(await gitOutcome(second)).toMatchObject({ state: 'committed', outcome: { git: 'committed' } });+ expect((await gitAsync(root, 'status', '--porcelain', '--', 'alpha.md', 'beta.md')).trim()).toBe('');+ expect(await gitAsync(root, 'ls-tree', '--name-only', 'origin/main')).toContain('alpha.md');+ expect(await gitAsync(root, 'ls-tree', '--name-only', 'origin/main')).toContain('beta.md');+ // Enabling again plans nothing: the caught-up effects are no longer skipped.+ const again = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, dry_run: true });+ expect(again).toMatchObject({ catch_up: { planned: 0 }, why: expect.stringContaining('already as requested') });+ }), 120_000);++ test('--disable wins over a legacy hook: the next Git effect completes as skipped; --pat-file refuses a readable token file first', () => isolated(async home => {+ const root = await gitRoot(home);+ const hook = join(root, '.git', 'hooks', 'post-commit');+ writeFileSync(hook, '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n'); chmodSync(hook, 0o755);+ const { sourceId } = await claimedSource(root);+ expect(await gitDurabilityPolicy(await getWorktreeBinding(engine, sourceId, localHostId()), root)).toEqual({ durable: true, source: 'legacy_hook' });+ const disabled = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, disable: true, ...await reviewedWriterIntent(engine, 'writer_git_durability') });+ expect(disabled).toMatchObject({ applied: true, git_durability: { before: null, after: 'disabled' }, queued_catch_up: 0 });+ const request = await committedWrite(root, sourceId, 'gamma');+ await runEffects();+ expect(await gitOutcome(request)).toMatchObject({ state: 'committed', outcome: { reason: 'durability_not_enabled' } });+ expect(await gitAsync(root, 'log', '--oneline')).not.toContain('gamma');++ const token = join(home, 'token'); writeFileSync(token, 'ghp_exampletoken\n'); chmodSync(token, 0o644);+ const refusal = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, pat_file: token, dry_run: true }).catch(error => error);+ expect(refusal).toMatchObject({ code: 'pat_file_unreadable' });+ expect(refusal.message).not.toContain('ghp_exampletoken');+ expect(refusal.suggestion).toContain('chmod 600');+ expect((await gitAsync(root, 'config', '--local', '--get', 'credential.helper').catch(() => '')).trim()).toBe('');+ await expect(runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, disable: true, pat_file: token, dry_run: true }))+ .rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('--pat-file cannot be combined with --disable') });+ }), 120_000);+});