Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(refresh): abandon checks partial imports under member drain leases; diverged and unplaceable members get their own way out (GST-1465, GST-1472, GST-1477)

garrytan276230a5cd9d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8cadb056cf..d457d416b7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,16 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**`gbrain sources refresh --abandon` no longer leaves the database ahead of the checkout, and every way out an interrupted refresh names now finishes it.** A refresh stopped mid-sync with the checkout reset to its start commit could still be abandoned when a member's sync had imported part of the upstream commit but stopped (on its budget) before recording it: the imported pages stayed live with no file at HEAD. Abandoning while a sync pass that read the upstream commit was still running could also let that pass record the upstream commit after the fence lifted. Both now refuse and change nothing: the first names the fast-forward and `--resume`, the second `sync_drain_lease_held` until the pass ends. The other ways out are fixed too: `--abandon` at a HEAD past the upstream commit names `--resume` (which finishes in one run) instead of a reset; members synced to diverged lines get a refusal naming each commit and a merge of them instead of a fast-forward `--resume` would refuse again; a member commit git cannot place gets its own refusal and a fetch; writer status read off the owner host says the check needs the owner host; and the refusals name the revert route for an operator who rolled back on purpose (fast-forward, `git revert` on top, `--resume`). `--abandon` is never loosened and has no override.
+
+### Itemized changes
+
+- `src/core/persistence/worktree-refresh.ts`: `membersPastStart` also counts a member with a managed-sync import or delete admitted after the row's `barrier_sequence` (GST-1465 #1), and reads `git merge-base --is-ancestor` as exit 0, exit 1 or "cannot place" (GST-1472 #3). `--abandon` of a `recovery_required` row checks the members and aborts under the topology locks and every member's drain lease (`underMemberLeases`); a live holder refuses `sync_drain_lease_held` and an expired lease is taken over (GST-1465 #2). `keepPagesWayOut` replaces `keepPagesHead`: a fast-forward to the newest member commit on the target's line, a merge of diverged member lines (`ask_user`, GST-1472 #2), or a fetch when a member commit cannot be placed; `--resume` recomputes that refusal at any readable HEAD instead of repeating the stored text. `adoptsHead` is the one recovery-adopts-this-HEAD check, and `--abandon` reads it to name `--resume` at a HEAD past the target (GST-1472 #1). `refreshHolderReport` names writer status on the owner host (`actor: host_admin`) when it has no checkout for a `recovery_required` row (GST-1477 #1). The fast-forward refusal's suggestion and `user_message` name the revert route (GST-1477 #2).
+- Docs: `docs/guides/write-refusals.md` (`refresh_recovery_required`, `sync_drain_lease_held`), `docs/architecture/key-files/core-persistence-git.md`.
+- Tests: `test/refresh-recovery-followups-gst1465.test.ts` (new, PGLite and Postgres through `test/e2e/worktree-refresh-postgres.test.ts`): a sliced pass's partial import refuses `--abandon` and the fast-forward then `--resume` finishes with every page at HEAD; a pass paused after its level read refuses `--abandon` `sync_drain_lease_held`; a fenced and a merged orphan past the target finish on one `--resume` and `--abandon` names it; diverged members refuse naming both commits and the named merge then `--resume` finishes; an unplaceable member commit refuses with the fetch at the start commit and at the target, and once fetched the fast-forward finishes; writer status off the owner host names the owner host; the revert route completes and the next sync removes the reverted page.
+
## [0.60.620.0] - 2026-11-09
**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. The publish child scans, under its publish lock and for the exact commits it pushes, what they add: commit messages, added lines (including a value a later commit removed) and merge-commit conflict resolutions. A value that looks like a secret, added text too large to scan, or a commit that changes `.gbrain-scan-allow` or a `.gitattributes` refuses the new `publish_secret_found` naming the file, line, rule and commit, never the value, with nothing pushed; commits the scan cannot read in full refuse `publish_scan_unreadable` instead. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off.
diff --git a/docs/architecture/key-files/core-persistence-git.md b/docs/architecture/key-files/core-persistence-git.md
index f7ab6480b9..ef00bdd9ed 100644
--- a/docs/architecture/key-files/core-persistence-git.md
+++ b/docs/architecture/key-files/core-persistence-git.md
@@ -4,7 +4,7 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
The managed Git writer (`gbrain sources refresh`), git-canonical memory (the git gap census, declared database-only classes, the door) and the checkout reads beside them.
-- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified (#8617: a `refresh_source_changed` for a moved HEAD or work that arrived after the drain check is retried once in the same run from a fresh precheck; a second refusal returns the first with the retry's cause appended), dirt rechecked, `git merge --ff-only`, HEAD verified again (a HEAD that descends from the target after a successful merge, with no member synced off it, counts as merged: a plain-git commit landed in between; a refused fast-forward whose HEAD only gained commits on the start commit aborts `refresh_source_changed`, GST-1674), then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member in one budget (`sources.refresh_sync_budget_ms`; past it a member is `deferred`) (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target or descends from it, or with `outcome.sync_blocked` / `sync_deferred` when a member blocks or is deferred. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies` on every consumer topology scan) touches interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; so does a fenced row whose merge started (`outcome.merge_started_at`, epoch ms) and whose HEAD descends from the old HEAD without the target, when the reflogs of HEAD and its branch show no move to the target since then (git refused the fast-forward, GST-1674; no readable reflog stays `recovery_required`); HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. #7679: each row records its holder (`outcome.holder`: host id, hostname, pid, process start; `previous_holder` after a recovery adopts it). A row whose lock is free is orphaned: `resumeWorktreeRefreshes` also completes an orphaned `syncing` row once every member's `last_commit` reached the target or a descendant, and a plain `gbrain sources refresh` on the owner host finishes any orphaned non-`recovery_required` row through the `--resume` path (`adoptOrphanedRefresh` + `resumeHeld`) before its own refresh, reporting it as `recovered`. A holder recorded on another host is never adopted. `refreshHolderReport` (writer status `worktree_refreshes`, sync status `worktree_refresh`) names the holder, `liveness` (`live` / `orphaned` / `unknown` off the lock's host) and a fix naming `--resume`. While the worktree's newest refresh is `aborted`, every run (tick, `--resume`, `--abandon`, even one its precheck refuses) ends by running the managed `--no-pull` sync of each member behind the checkout HEAD (`syncAfterUnfinishedRefresh`, listed in `synced`), so a write held for an import that refresh fenced off is decided in that run, not at a later refresh. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit or on a row recovery would abort (a HEAD moved before the merge, or a refused merge, GST-1674), and never on a `recovery_required` row once a member's `last_commit` is past it (not it or an ancestor; GST-1457: the next sync would soft-delete what it synced), and `--resume` finishes a `recovery_required` row only at a HEAD that contains every member commit on that refresh's line. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command). Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts` (#7685: `--json` prints a refusal's structured `fix` when it has one; `refresh_in_progress` carries the writer-status read); while a resident PGLite owner (`gbrain serve`, stdio MCP) holds the database, `src/commands/sources-refresh-delegate.ts` runs the refresh inside it through the `writer_refresh` administration operation (trusted CLI registration only) and prints the same result or refusal. The consumer's idle probe applies `refreshFenceClear` to effects like the claims, so a fenced worktree's queued effects do not wake it. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge, and after a refused merge), `test/worktree-refresh-orphan-7679.test.ts` (SIGKILL mid-syncing, live-holder no-steal), `test/oversize-hold-rescreen-8072.test.ts` (budget), `test/refresh-barrier-held-after-abort.test.ts` (the sync after an aborted refresh), Postgres via `test/e2e/worktree-refresh-*postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.
+- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified (#8617: a `refresh_source_changed` for a moved HEAD or work that arrived after the drain check is retried once in the same run from a fresh precheck; a second refusal returns the first with the retry's cause appended), dirt rechecked, `git merge --ff-only`, HEAD verified again (a HEAD that descends from the target after a successful merge, with no member synced off it, counts as merged: a plain-git commit landed in between; a refused fast-forward whose HEAD only gained commits on the start commit aborts `refresh_source_changed`, GST-1674), then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member in one budget (`sources.refresh_sync_budget_ms`; past it a member is `deferred`) (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target or descends from it, or with `outcome.sync_blocked` / `sync_deferred` when a member blocks or is deferred. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies` on every consumer topology scan) touches interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; so does a fenced row whose merge started (`outcome.merge_started_at`, epoch ms) and whose HEAD descends from the old HEAD without the target, when the reflogs of HEAD and its branch show no move to the target since then (git refused the fast-forward, GST-1674; no readable reflog stays `recovery_required`); HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. #7679: each row records its holder (`outcome.holder`: host id, hostname, pid, process start; `previous_holder` after a recovery adopts it). A row whose lock is free is orphaned: `resumeWorktreeRefreshes` also completes an orphaned `syncing` row once every member's `last_commit` reached the target or a descendant, and a plain `gbrain sources refresh` on the owner host finishes any orphaned non-`recovery_required` row through the `--resume` path (`adoptOrphanedRefresh` + `resumeHeld`) before its own refresh, reporting it as `recovered`. A holder recorded on another host is never adopted. `refreshHolderReport` (writer status `worktree_refreshes`, sync status `worktree_refresh`) names the holder, `liveness` (`live` / `orphaned` / `unknown` off the lock's host) and a fix naming `--resume`. While the worktree's newest refresh is `aborted`, every run (tick, `--resume`, `--abandon`, even one its precheck refuses) ends by running the managed `--no-pull` sync of each member behind the checkout HEAD (`syncAfterUnfinishedRefresh`, listed in `synced`), so a write held for an import that refresh fenced off is decided in that run, not at a later refresh. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit or on a row recovery would abort (a HEAD moved before the merge, or a refused merge, GST-1674), and never on a `recovery_required` row once a member is past it (`membersPastStart`: a `last_commit` that is not it or an ancestor, GST-1457: the next sync would soft-delete what it synced; or a managed-sync import or delete admitted after the row's `barrier_sequence`, GST-1465: a pass stopped before its stamp), checking and aborting under every member's drain lease (`underMemberLeases`, so a pass in flight refuses `sync_drain_lease_held`), and `--resume` finishes a `recovery_required` row only at a HEAD that contains every member commit on that refresh's line (`adoptsHead`, which `--abandon` also reads to name `--resume` instead of a reset). `keepPagesWayOut` names the way out (GST-1472): a fast-forward to the newest member commit on the target's line, a merge of member commits on diverged lines (ask the user), or a fetch when git cannot place a member commit (`ancestry` tells exit 1 from a failure); the refusals also name the revert route for a deliberate rollback (GST-1477), and off the owner host writer status names no step. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command). Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts` (#7685: `--json` prints a refusal's structured `fix` when it has one; `refresh_in_progress` carries the writer-status read); while a resident PGLite owner (`gbrain serve`, stdio MCP) holds the database, `src/commands/sources-refresh-delegate.ts` runs the refresh inside it through the `writer_refresh` administration operation (trusted CLI registration only) and prints the same result or refusal. The consumer's idle probe applies `refreshFenceClear` to effects like the claims, so a fenced worktree's queued effects do not wake it. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge, and after a refused merge), `test/worktree-refresh-orphan-7679.test.ts` (SIGKILL mid-syncing, live-holder no-steal), `test/oversize-hold-rescreen-8072.test.ts` (budget), `test/refresh-barrier-held-after-abort.test.ts` (the sync after an aborted refresh), Postgres via `test/e2e/worktree-refresh-*postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.
- `src/core/persistence/refresh-barrier.ts` (+ deferred admission and claim in `journal.ts`, migration v292 `src/core/schema-migrations/v292-refresh-write-barrier.ts`) — the refresh write barrier (`docs/designs/REFRESH_WRITE_BARRIER.md`, `docs/guides/write-refusals.md#deferred-writes`). Off by default (`persistence.refresh_barrier`). With it on, a single page or memory write that reaches a worktree during a refresh is journaled in state `deferred` (tied to `deferred_refresh_id`) and answered pending instead of refused `worktree_refreshing`. Only a claim that declares the barrier moves a deferred row, and only after its refresh is released. `deferredReplayRefusal` re-checks the write's authority and reads the refresh's `old_head..target_head` diff with git, so a file the refresh changed ends `revision_conflict` with nothing applied. A write still waiting past `persistence.refresh_barrier_max_wait_ms` (15 minutes) ends `refresh_barrier_expired`. A write during a refresh in `recovery_required` defers too, and since GST-1582 there is no per-refresh cap (`persistence.refresh_barrier_max_deferred` is no longer read). A write whose page file holds a committed change sync has not imported yet is held with `deferred_import_from` (migration v294) instead of refused `pending_import`, and ends `pending_import_expired` past the wait limit (or four wait limits, at least four hours, after admission when it is held again and again). GST-1623: either kind of deferred write ends `revision_conflict` when a later write to its page committed first, and a refresh-deferred write is checked against its refresh before an import hold, which then clears `deferred_refresh_id`. `refresh-retry-hint.ts` derives `worktree_refreshing`'s `retry_after_ms` from the worktree's refresh history. `gbrain upgrade --check-downgrade` exits 3 `downgrade_blocked_deferred_writes` while any deferred write is unfinished. Tests: `test/refresh-write-barrier.test.ts`, `test/refresh-barrier-state-audit.test.ts`.
- `src/core/persistence/git-gap.ts` + `src/commands/sources-git-gap.ts` + `src/commands/doctor/checks/db-ahead-of-git.ts` — git-canonical memory, wave G1 (`docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census`), read-only. `declaredDatabaseOnly` is the one predicate for pages that may not have a tracked file, tested in order: a read-only mirror source, a private page (`isPrivatePage`), an alias-private page (`isDerivationPrivate`), lineage-private (computed in SQL from `privatePagesFilterFragment`), `database_only_reason`, a `storage.db_only` prefix (`isSourceDbOnlySlug`, refusing an invalid gbrain.yml), a never-filed derive-phase page (page-prepare.ts `isNeverFiledDerivedPage`: no `source_path`/`source_uri` under `DERIVE_PHASE_DB_ONLY_DEFAULTS`), a path the checkout's Git ignores (`ignoredPaths`: filter-free `check-ignore -z --stdin`, tracked files never reported, exit 1 = none, null when Git cannot answer). The equality contract compares a committed blob with the page's export view (`readExportPage`, withdrawals overlaid; the census reads a batch's views with `readExportPages`, the same snapshots in two statements, #7617): an inline blob parsed as reconcile parses a canonical file, aligned with the stored type, subtype and #6429 stamp and compared by `reconcileCanonical` digest; a segmented page by the Git blob id of its streamed export. HEAD is read with hardened plumbing only (`readHeadTree`: one `ls-tree -r -l -z --full-tree` under the source's directory; `readBlobs`: `cat-file --batch` in calls of at most 64 MiB) and the working tree by hashing raw bytes (`worktreeBlobOid`), never `git status`/`git diff`, so no repository filter, textconv or fsmonitor runs. `gbrain sources git-gap <id> [--sample n] [--json]` (trusted local CLI, not an MCP op) puts every live page in one state (`equal`, `database_ahead`, `git_ahead` when the sync import record's `blob_oid`/`disk_blob_oid` differs from HEAD, else folded into `database_ahead` and counted in `database_ahead_without_import_record`, split by content evidence in `direction_evidence`, `declared_database_only` per class, `undeclared_database_only`, `worktree_only`, `unparseable`, `unsafe_path`), reports the working tree separately, and counts rows with no Git home (unfenced active facts, fenced facts on a missing page or a page without a committed file, links whose `link_source` is not in `DERIVED_LINK_SOURCES`, timeline rows on pages without a file), open `sync-hold` records by code and parked effect targets by kind and code. Each 256-page batch reads in its own read-only transaction. Doctor `db_ahead_of_git` runs the census per non-archived source whose directory is a Git checkout (others are only counted) under `GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS` (default 10 s) and the entry deadline; it is always `ok` (informational) and lists totals only with each source's `live_pages` (counted in SQL before the scan), a source the budget stopped or never reached as partial (`PARTIAL, <read> of <live> live page(s) read`). Tests: `test/git-gap-census.test.ts` (PGLite and Postgres).
- `src/core/persistence/git-declared.ts` + `src/core/persistence/git-canonical-schema.ts` (migration `git_canonical_declared`) — git-canonical memory, wave G7a: the declared database-only classes of a strict source (`sources.config.canonical = "git"`, default off). `strictPageClass` judges a page by its slug and prior file (`declaredPathClass`: `db_only_prefix` for a `storage.db_only` dir, `derive_folder` for a never-filed derive-phase page; G3's indexer reads the same function) and then its rendered content (`privacyClass`: `private`, `alias_private`, or `lineage_private` from the same SQL remote reads use, `privatePagesFilterFragment`, over the page's own values). `page-prepare.ts` `prepareFileTarget` asks it before it builds a strict file target: a declared page gets no target (no file, no door commit, no Git effect), an untracked ignored target is `git_ignored`, a page turning private gets the removal of the file it still has in the worktree or at HEAD, and a path whose `filter` attribute is `lfs` passes `assertLfsTarget` only with `storage.git_lfs` and a checkout that configures the LFS filter (`git_lfs_not_enabled`). `preparePrivateTransition` (page-prepare.ts) is that removal for other writers (GBRA-60, connector imports #7971). In `publishMutation` and `publishGroup`, `assertNoPrivateCommit` refuses a file target carrying a private page's bytes before anything is written (`git_private_commit_refused`; a group rolls back whole), and `declareStrictPublication` (after apply, before the door commit) refuses a declared page's file or an undeclared file-less page (`git_home_required`), stamps `pages.database_only_reason` and, for a privacy class, clears `source_path`/`source_uri` in the transaction of the door commit that removed the file. A managed import builds its own file target, so it meets only these publication checks. `assertStrictGitHome` is the refusal for writers with no file form yet (G4, G5). The managed writer guard (`writer-guard-schema.ts`) refuses rows of a strict source unless the writer declares `gbrain.git_protocol` (`withCoordinatedWrite` does), behind the `git_canonical_brain.strict_sources` counter kept by `sources` triggers (`git_protocol_required`, mapped in `publication-failure.ts`). The guard reads its state as the writing role and fails closed: a hidden or missing `persistence_brain` or `git_canonical_brain` row, or a source or page row hidden by row-level security, raises `writer_coordinator_required` (`managed_writer_guard:unreadable_state`), and the counter refuses a recount under RLS on `sources` (`test/writer-fence-fail-closed-7636.test.ts`). The census (`git-gap.ts`) adds `database_only_source` (a source with no checkout) and maps the stamped reasons to their own classes. Tests: `test/git-canonical-declared-g7a.test.ts` (both engines).
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index cc48ea8298..858cb55f7a 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -572,7 +572,7 @@ this anchor (`--json` puts them in one object on stdout); the command exits 1.
| <a id="refresh_lock_timeout"></a>`refresh_lock_timeout` | `refresh_lock_timeout` | The refresh fence locks the brain, worktree, source and refresh rows with a 5 s lock timeout, and another database transaction held one of them longer. `why` lists the five oldest open transactions in this database holding locks on those tables (pid, application, state, how long the transaction has been open). They are candidates: the blocker may not be among them, because Postgres does not show which row each one holds. It never repeats their SQL, and says so when that lookup failed or took longer than 3 s. HEAD did not move: no fence was set, or the draining refresh was aborted. When the same holder also blocked that abort, the refusal says the row stays `draining`, and the next `gbrain sources refresh <source>` resumes it. | Retry `gbrain sources refresh <source>`. If it repeats, a transaction holding one of those rows is stuck: `why` lists the oldest candidates, so confirm the blocker on the brain host before ending any transaction. |
| <a id="refresh_sync_timeout"></a>`refresh_sync_timeout` | `refresh_sync_timeout` | Reported per source in a refresh's `sync_blocked`, not as a refusal: the source's managed sync committed nothing within its share of the refresh sync budget (each member gets an equal share of what is left; `sources.refresh_sync_budget_ms`, `GBRAIN_REFRESH_SYNC_BUDGET_MS`, default 5 min), for example because no consumer claimed its write. The message names that write and its state. The checkout is at the upstream commit, the refresh completed and released its lock, and the source is behind until its next sync. A sync stopped by the drain's own rules is reported with that stop's code instead (`drain_stalled` and the others). | Run the `resume` command (`gbrain sync --source <source> --no-pull`). If it stalls the same way, check the write it names with `gbrain sources writer status <source> --json`. |
| <a id="refresh_source_changed"></a>`refresh_source_changed` | `refresh_source_changed` | HEAD moved (an outside commit or checkout, or gbrain's own commits the upstream does not hold yet), the upstream branch changed while the refresh waited, or the checkout's ownership or set of sources changed, between the precheck and the merge. Nothing was merged and the fence was lifted. When HEAD moved or work reached the checkout after the drain check, the run already retried once from a fresh precheck, and the message names why that retry was refused too. | Retry `gbrain sources refresh <source>`. |
-| <a id="refresh_recovery_required"></a>`refresh_recovery_required` | `refresh_recovery_required` | Publication or source recovery is pending on the checkout, or a refresh was interrupted and HEAD is neither the commit it started from nor the verified upstream commit. (A commit that lands on the upstream commit right after the refresh's own merge is not this case: the refresh records the merge and syncs it. Nor is one that lands on the start commit right before the merge: git refuses the fast-forward and the refresh ends `refresh_source_changed`; if its process dies before that, recovery aborts the refresh the same way when the checkout's reflog shows HEAD never reached the upstream commit.) Writes to the checkout stay refused until it is resolved; gbrain never adopts a HEAD it cannot verify. | `gbrain sources writer status <source>`, then `gbrain sources refresh <source> --resume`. When HEAD is unverified the fix names both ways out: reset to the start commit and run `--abandon`, or reset to the upstream commit and run `--resume`. Resetting is destructive, so ask the user first. Writer status reads HEAD and names the one step left when HEAD already sits at one of those commits: `--resume` at the upstream commit, `--abandon` at the start commit when no member source has synced past it. When one has (its `last_commit` is set and is neither the start commit nor an ancestor of it; a commit git cannot find counts too), `--abandon` refuses with this code and changes nothing, because the next sync would roll that member's pages back; `--resume` refuses too, and both name the one way out that keeps those pages: the fix (`next: ask_user`) previews with `git -C <checkout> status --short`, fast-forwards the checkout with `git merge --ff-only` to the commit the members synced (the upstream commit, or a later one a member already synced; it keeps uncommitted edits and refuses if one overlaps an incoming file), then runs `--resume`. When git refuses, the fix names a hard reset to that commit instead (destructive: it discards local commits and uncommitted edits not in that commit). `--resume` finishes a `recovery_required` refresh whose HEAD is the upstream commit or descends from it, unless a member synced a commit on this refresh's line (or one git cannot place) that HEAD does not contain; then it refuses with the same fast-forward fix. |
+| <a id="refresh_recovery_required"></a>`refresh_recovery_required` | `refresh_recovery_required` | Publication or source recovery is pending on the checkout, or a refresh was interrupted and HEAD is neither the commit it started from nor the verified upstream commit. (A commit that lands on the upstream commit right after the refresh's own merge is not this case: the refresh records the merge and syncs it. Nor is one that lands on the start commit right before the merge: git refuses the fast-forward and the refresh ends `refresh_source_changed`; if its process dies before that, recovery aborts the refresh the same way when the checkout's reflog shows HEAD never reached the upstream commit.) Writes to the checkout stay refused until it is resolved; gbrain never adopts a HEAD it cannot verify. | `gbrain sources writer status <source>`, then `gbrain sources refresh <source> --resume`. When HEAD is unverified the fix names both ways out: reset to the start commit and run `--abandon`, or reset to the upstream commit and run `--resume`. Resetting is destructive, so ask the user first. Writer status reads HEAD and names the one step left when HEAD already sits at one of those commits: `--resume` at the upstream commit, `--abandon` at the start commit when no member source has synced past it. When one has (its `last_commit` is set and is neither the start commit nor an ancestor of it; a commit git cannot find counts too), `--abandon` refuses with this code and changes nothing, because the next sync would roll that member's pages back; `--resume` refuses too, and both name the one way out that keeps those pages: the fix (`next: ask_user`) previews with `git -C <checkout> status --short`, fast-forwards the checkout with `git merge --ff-only` to the commit the members synced (the upstream commit, or a later one a member already synced; it keeps uncommitted edits and refuses if one overlaps an incoming file), then runs `--resume`. When git refuses, the fix names a hard reset to that commit instead (destructive: it discards local commits and uncommitted edits not in that commit). `--resume` finishes a `recovery_required` refresh whose HEAD is the upstream commit or descends from it, unless a member synced a commit on this refresh's line (or one git cannot place) that HEAD does not contain; then it refuses with the same fast-forward fix. A member also counts as synced past the start commit when a managed sync imported or deleted a page for it after the refresh began, even though its `last_commit` is still the start commit (a pass stopped by its budget before its stamp), so the database is never left ahead of the checkout. `--abandon` of a `recovery_required` refresh checks the members and lifts the fence holding every member's drain lease: while a sync pass still holds one it refuses [`sync_drain_lease_held`](#sync_drain_lease_held) and changes nothing; retry once that pass ends. At a HEAD that is the upstream commit or descends from it (and holds every member's commit), `--abandon` refuses `refresh_in_progress` naming `--resume`, which finishes the refresh in one run. When the members' commits do not form one line (two members synced different commits past the upstream commit), no fast-forward keeps every member's pages: the refusal and writer status name each commit, and the fix (`next: ask_user`) is `git -C <checkout> merge --no-edit <commits>`, which joins them in one commit (on a conflict git stops with the conflicts in the checkout), then `--resume`. When git cannot place a member's commit (a missing object, an unreadable checkout, a git timeout), the refusal names that commit instead and its fix fetches (`git -C <checkout> fetch --all --no-tags`), then `--resume` names the way out; if no remote holds the commit any more, ask the user. **Rolled back on purpose:** an operator who reset the checkout to the start commit to reject an upstream change keeps git the parent by moving forward instead: fast-forward as the fix names, commit `git -C <checkout> revert --no-edit <the unwanted commits>` on top, then `--resume`; the refresh completes and the next sync removes those pages through history. There is no flag that abandons past a synced member. Writer status read on a host that is not the owner names no step for such a refresh (`actor: host_admin`): whether `--abandon` is safe depends on the owner's checkout, so run writer status on the owner host. |
| <a id="worktree_refreshing"></a>`worktree_refreshing` | `worktree_refreshing` | A write, or a managed sync started by a cycle or another command, reached a checkout while a refresh is draining or merging it. It was not saved. `detail` is `retry_after_ms=<n>`, estimated from the refresh itself: the median duration of the worktree's last completed refreshes minus how long this one has run, never below 15 s while it syncs or 2 s in its other phases (so a refresh of several minutes is never answered with a 1 s retry). The message names the phase, how long the refresh has run and typically takes, and the CLI's human output ends with one line, `Nothing was saved; retry the same command in about <n> s (retry_after_ms=<n>).`, which survives `| tail -1`. Writes to database-only memory are not affected. An interactive write (CLI, MCP) waits out the fence for up to 10 s, or its explicit `wait_ms` if lower, before this refusal; a background write is refused at once. The refusal is `retryable`, its `fix.next` is `wait`, and the CLI exits 1; the memory verbs keep their frozen `unavailable` code with `canonical: worktree_refreshing`. With `persistence.refresh_barrier` on, a single page or memory write waits behind the refresh instead ([deferred writes](#deferred-writes)). | Retry the same request ID after `retry_after_ms`; nothing was recorded, so the retry cannot write twice. `gbrain sources writer status --source <source> --json` shows the refresh. A cycle's sync is retried by the next cycle. |
A refresh is recorded in `persistence_worktree_refreshes` and survives a crash.
@@ -680,7 +680,7 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run
| <a id="drain-connection-lost"></a>`connection_lost` | `connection_lost` | `blocked` | The database connection dropped three times in a row (`write ECONNABORTED`, `ECONNRESET`, `ETIMEDOUT`, `EPIPE`: a pooler closing the socket mid-statement) with no page committed between the drops (#6340). Each drop was reconnected and retried after 5, 15 and 45 s; a drop that then moves data is not reported at all. Nothing is recorded against the source: the cursor and its frozen manifest stand, and `drain.connection` carries the count and the last error text (never a URL). Exit 1. | Check the database and pooler (`gbrain doctor --json`), then rerun `next.command` (`safe_to_loop` is true, `retry_after_ms` 60 s): it resumes at the stored cursor without re-freezing the manifest. Runbook: [sync unblock](sync-unblock-runbook.md#connection). |
| <a id="drain-capacity-paused"></a>`capacity_paused` | `capacity_paused` | `resumable` | The run passed its capacity preflight, then a cumulative write cap refused its next admission (`write_quota_exhausted`) or, for a background sync, the pause line did (`write_capacity_backpressure`): another writer used the room the preflight counted on. Nothing failed; the cursor and every accepted write stand, and `drain.capacity_pause` names the refusal and its config raise. | Run the `gbrain config set` the report names on the brain host (request ids never free; receipt bytes also free as receipts compact), then rerun the same `gbrain sync`. Verify with `gbrain doctor --only persistence_capacity --json`. |
| <a id="head-blocked"></a>`drain_stalled` with `cause: head_blocked` | `drain_stalled` | `blocked` | The queued write at the head of the source cannot be claimed by any consumer, and its blocker needs an operator (#6543). `drain.stall.blocked_by` names the predicate, its ids, state and owner: `refresh_fence` (a refresh left the checkout `fenced`, `merged` or `recovery_required` and no refresh process holds its lock), `zombie_publication` (a running request ahead of the head is held by a process that reports `restart_required`), or `effect_recovery` with state `unexpected_file_bytes` (a fact-withdrawal mirror's page file was edited while the mirror was publishing, so its forward-only recovery refuses to overwrite it), or `request_recovery` with state `unexpected_file_bytes` (a page write's file, or a file of a shared-skill bundle, was edited while it was publishing, #6650; this also covers a head that is itself that recovering write). For both, `blocked_by.file` names the page and path (an effect's also names its withdrawal request). `effect_recovery` or `request_recovery` with state [`recovery_version_unsupported`](#recovery_version_unsupported) is a record a newer gbrain wrote, which no recovery here finishes. A recovery stuck on `unexpected_staging_bytes` is not classified yet and still waits out the window. The drain stops after one governor tick of confirmation instead of the no-progress window. Live blockers (`root_hold`, a foreground publication; `lease`, a lapsed claim the next consumer reclaims; `withdrawal_mirror`, an `effect_recovery` or `request_recovery` that can still finish, `worktree_owner`) never stop it: the stall line names them as `blocked_by=` beside `consumer=` and the drain keeps waiting. `claimable here` is read for the head itself and prints `unknown` when the probe could not read it. | Run `next.fix`: `refresh_fence` resumes the refresh (`gbrain sources refresh <source> --resume`, which lifts the fence or names why it cannot); `zombie_publication` tells the host admin to restart the named process; `effect_recovery` runs the [`gbrain repair stuck-recovery --source <source> --request-id <request>`](repair.md#stuck-recovery) preview, whose only choice (`--keep withdrawn`, the user's to apply) backs the edit up and writes the withdrawn version; or the user restores the committed version, never deletes the file, and redoes the edit without the forgotten fact; `request_recovery` runs the [`gbrain repair stuck-recovery --source <source>`](repair.md#stuck-recovery) preview, and the user either keeps one version through it or undoes the edit. Then rerun the sync. `gbrain sources writer status --source <source> --json` names the same blocker for every queued head and, only when the caller may cancel the blocking request, `gbrain cancel-write-request <request_id>`; `recovery_version_unsupported` tells the user to run `gbrain upgrade` on the owner host. |
-| <a id="sync_drain_lease_held"></a>`drain_lease_held` | `sync_drain_lease_held` | `resumable` | Another process holds the source's drain lease (#6712): one managed drainer per source, and that holder (a serve, a `sync` job, the dream cycle, another terminal) is still committing pages. `gbrain sync` follows it within its own `--timeout` and run deadline, printing the holder (kind, pid, host, gbrain version) and the pages it commits (every 10 s on a terminal, 60 s otherwise), and takes the lease when the holder releases it. This code means the budget ended first, or the lease moved to another process mid-pass (`lost`); nothing this run admitted is lost and the cursor is intact. `--no-delegate` never skips the lease. `drain.lease_held.holder` reuses the drain's owner fields: `kind`, `id`, `host`, `pid`, `started_at`, `last_heartbeat_at`, `version` and `progress` (`committed`, `last_committed_at`, `last_progress_at`); `next.retry_after_ms` is 60 s and `next.safe_to_loop` is true. Exit 0. A cron that runs `gbrain sync` every few minutes beside a serve exits 0 here on each tick while the serve works. | Rerun `next.command` after `next.retry_after_ms`, or let the holder finish. Ctrl-C while following stops only this run; the holder keeps going. A holder that commits nothing for 5 minutes is not reported here: the run stops [`drain_stalled`](#drain-lease-stalled) instead. |
+| <a id="sync_drain_lease_held"></a>`drain_lease_held` | `sync_drain_lease_held` | `resumable` | Another process holds the source's drain lease (#6712): one managed drainer per source, and that holder (a serve, a `sync` job, the dream cycle, another terminal) is still committing pages. `gbrain sync` follows it within its own `--timeout` and run deadline, printing the holder (kind, pid, host, gbrain version) and the pages it commits (every 10 s on a terminal, 60 s otherwise), and takes the lease when the holder releases it. This code means the budget ended first, or the lease moved to another process mid-pass (`lost`); nothing this run admitted is lost and the cursor is intact. `--no-delegate` never skips the lease. `drain.lease_held.holder` reuses the drain's owner fields: `kind`, `id`, `host`, `pid`, `started_at`, `last_heartbeat_at`, `version` and `progress` (`committed`, `last_committed_at`, `last_progress_at`); `next.retry_after_ms` is 60 s and `next.safe_to_loop` is true. Exit 0. A cron that runs `gbrain sync` every few minutes beside a serve exits 0 here on each tick while the serve works. | Rerun `next.command` after `next.retry_after_ms`, or let the holder finish. `gbrain sources refresh <source> --abandon` refuses with this code too while a member's sync pass holds its lease (nothing changed); retry it once the pass ends. Ctrl-C while following stops only this run; the holder keeps going. A holder that commits nothing for 5 minutes is not reported here: the run stops [`drain_stalled`](#drain-lease-stalled) instead. |
| <a id="drain-lease-stalled"></a>`drain_stalled` with `cause: no_progress` and `stall.lease_holder` | `drain_stalled` | `blocked` | The process holding the source's drain lease committed no page and saved no cursor for 5 minutes, so following it would exit 0 forever (#6712). `drain.stall.lease_holder` names it with the fields above; the lease itself is renewed by a live process, so a wedged holder keeps it. A holder that died lets its lease lapse within 2 minutes and the next run takes over without this stop. Exit 1, `next.safe_to_loop` false. | `gbrain sources writer status --source <source> --json` (read-only) shows what the holder is waiting on. Stop or restart the named process; when it is gone but its lock row remains, `gbrain sync --source <source> --no-pull --break-lock` releases a lock whose pid is dead (`--force-break-lock` skips the liveness check: only when you know the holder is gone). Then rerun the same sync. |
| <a id="drain-not-converged"></a>`not_converged` | `not_converged` | `resumable` | The live pass (#6712 PR 4b) used its rounds without the level settling: another writer kept changing the checkout or the database while it ran. Everything it admitted stands and nothing is held for it; the pass row counts consecutive such passes (`not_converged_streak`). | Rerun the same `gbrain sync` (`next.safe_to_loop` is true). After three consecutive `not_converged` passes `next` turns to `report` (`safe_to_loop` false): run `gbrain sync status --source <id> --json` and `gbrain doctor --json` and report what keeps changing. Exit 0. |
| <a id="drain-admission-paused"></a>`admission_paused` | `admission_paused` | `resumable` | `sync.admission` is `imports_only` or `classify_only`, so the pass admitted only what it allows (or nothing) and stopped; a destructive write paused at publication is completed `cancelled` with `admission_paused`. Nothing failed. | Restoring admission is the owner's decision: `gbrain config set sync.admission normal` (`next.fix` is `tell_user_to_run`; never run automatically). The next sync continues. Exit 0. |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 91c4fa72d0..fc6ec3e2d5 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -38,6 +38,7 @@ src/commands/hook.ts 1996 ratchet cathedral-5 heartbeat extraction offsets part
src/core/chunkers/code.ts 1602 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); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
src/core/config.ts 2021 ratchet +1 GBRA-154 #7175: search.keyword_phrase KNOWN_CONFIG_KEYS row; +1 search.saved_facts_supersede KNOWN_CONFIG_KEYS row (read in search/saved-facts-match.ts; re-summed at the #7703 merge: 2014 + 1); +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +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); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-205: search.evidence_titles / query_budget_unit / query_facts_block / fact_source_pages KNOWN_CONFIG_KEYS rows (read in search/evidence-date.ts, evidence-packing.ts, facts-arm.ts); +1 GBRA-156: search.remote_page_cap KNOWN_CONFIG_KEYS row (read in search/remote-page-cap.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (2021 measured)
src/core/persistence/sync-run.ts 1697 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts); +1 #7886: the import of persistence/sync-receipt-wait.ts, where the managed sync receipt waits and their test seam live; +3 #7931: the freeze drift screen also accepts a file that holds the page as prepareFileTarget reads it (fileMatchesSnapshot import, comment, the split condition line); +5 GBRA-218: performManagedSync wraps every managed pass (sync, drain, sources refresh, git conversion, owner slice) in withCommittedPolicy (logic in access/policy-git.ts) and keeps the lease path in performLeasedPass; re-summed at the memory train #8481 merge with v0.60.576.0 (1696 measured); +1 convergence nightly fix: the sync:passed_over fault point after the pass-over cursor save (a kill seam sits where its cursor commits, so it cannot move)
+src/core/persistence/worktree-refresh.ts 1554 ratchet new row: crossed the 1500 unlisted cap in GST-1465/GST-1472/GST-1477 (refresh-recovery ways out: membersPastStart reads partial imports, keepPagesWayOut names a fast-forward, a merge of diverged members or a fetch, underMemberLeases holds every member drain lease for --abandon, adoptsHead shared by recovery and --abandon); these helpers share the module-private withGit, ancestry and refusal seams of the recovery state machine, so they stay beside it
src/core/bootstrap/harness.ts 2630 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); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments); +13 brain-first block lane: --no-instructions flag field + parse, opencodeAgentsPath dep (field + default) and the step-10b / remove call sites (logic lives in harness-brain-first.ts); +7 GBRA-243 per-turn rule hook: consent-block interface field, step-10c call site, turn_hooks JSON field, exit code and the remove arm (writer, host list and consent text live in harness-brain-first.ts); +2 #8428: the harness lane Claude Code and Codex SessionEnd hooks start gbrain through the hook launcher; +16 GBRA-194 skills index lane: --skill-loading flag field + parse, step-10b and remove call sites, skills_index JSON field and exit-code wiring (logic lives in harness-skills-index.ts and setup/skills-block.ts)
src/core/oauth-provider.ts 1237 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option; +1 GST-1113 transactional token mint
src/core/ops/pages.ts 739 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts); +1 GST-687: get_page include_timeline_entries quotes rows for remote readers (import only; logic in ops/timeline-quote.ts); +2 #8384: the quoted_unverified_origin notice call in get_page and fetch (logic lives in get-page-projection.ts); +1 GBRA-218: put_page checks a remote readable_by before admission (logic in persistence/page-visibility.ts assertSubmittedReaders) (re-summed at the train M merge of master v0.60.539.0: 732 measured); re-summed at the memory train #8481 merge with v0.60.576.0 (739 measured)
@@ -47,4 +48,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)
src/commands/config.ts 1526 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)
src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)
-src/core/behavior-change-notice.ts 1687 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row
+src/core/behavior-change-notice.ts 1688 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-1465 refresh_abandon_members_gst1465 row (since TBD until the merge slot; rows are data and cannot move)
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 2e82668a4c..bc75e84c79 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1489,6 +1489,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.618.0', id: 'refresh_replan_own_commits_8828', text: 'A `gbrain sources refresh` whose checkout HEAD moved while it waited for writes admitted before its fence no longer refuses `refresh_source_changed` when every commit since its start is one of gbrain\'s own (in the commit ledger) and the upstream branch holds them: it takes HEAD as its start and fast-forwards to the upstream. A HEAD move that includes a commit gbrain did not make, or gbrain\'s commits the upstream does not hold yet, still refuses as before.' },
{ since: '0.60.619.0', id: 'managed_commit_push_unpublished_gst1923', text: 'On a managed checkout, `gbrain git commit-push -m <msg> -- <paths>` now reports how many commits the upstream lacks as last fetched (`unpublished` in `--json`, `null` when there is no upstream) and says nothing was pushed, instead of answering `nothing to commit; <remote>/<branch> at -` and logging `[push] ok-already-on-remote` for a commit that already existed. It writes no push-log line on a managed checkout. It still never pushes there; `gbrain git commit-push --push-only --keep-checkout --path <checkout>` publishes.' },
{ since: '0.60.620.0', id: 'refresh_publish_diverged_default_gbra386', text: 'A diverged managed checkout now publishes its local commits on `gbrain sources refresh` by default when the worktree\'s Git durability is on: `sources.refresh_publish_diverged` unset now means on there (it used to mean off), merged with the upstream in memory, never rebased or forced. The refresh publish first scans what the local commits add (messages, added lines, merge resolutions) and refuses the new `publish_secret_found` naming the file, line and rule, never the value, when one looks like a secret; `gbrain git commit-push --push-only --scan-secrets` runs the same gate. Unset with durability not on still refuses, naming `gbrain sources writer git-durability <source> --enable`; `false` turns it off.' },
+ { since: 'TBD', id: 'refresh_abandon_members_gst1465', text: '`gbrain sources refresh --abandon` of a `recovery_required` refresh now also refuses when a member\'s managed sync imported or deleted pages after the refresh began, even with its `last_commit` still at the start commit (a pass its budget stopped), and refuses `sync_drain_lease_held` while a member\'s sync pass still holds its drain lease, so the database is never left ahead of the checkout. At a HEAD past the upstream commit it names `--resume` instead of a reset. Members synced to diverged lines, or to a commit git cannot place, now get their own refusal (merge those lines, or fetch the commit) instead of a fast-forward that `--resume` would refuse again, and the refusals name the revert route for a deliberate rollback. Writer status read off the owner host names no step for such a refresh.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.ts
index 460e4be72c..2af51de469 100644
--- a/src/core/persistence/worktree-refresh.ts
+++ b/src/core/persistence/worktree-refresh.ts
@@ -56,6 +56,8 @@ export interface WorktreeRefreshRow {
id: string; worktree_id: string; source_ids: string[]; principal_id: string; owner_epoch: string | number;
topology_generation: string | number; state: WorktreeRefreshState; old_head: string; target_head: string; upstream_ref: string;
preserved_uncommitted: string[]; outcome: Record<string, unknown>; created_at: string | Date; updated_at: string | Date; completed_at: string | Date | null;
+ /** The newest write request sequence when the row was inserted: a managed-sync request past it was admitted after the refresh began. */
+ barrier_sequence?: string | number | null;
}
export type RefreshBoundary = 'drained' | 'fenced' | 'merged' | 'syncing' | 'synced';
export interface RefreshHooks { boundary?: (point: RefreshBoundary, row: WorktreeRefreshRow) => Promise<void> | void }
@@ -107,34 +109,58 @@ function refusal(name: CatalogueName, cause: string, fix: string, refreshId?: st
const RETRY_IN_TICK = Symbol('retry_in_tick');
const retryInTick = (error: OperationError) => Object.assign(error, { [RETRY_IN_TICK]: true });
/**
- * GST-1457: members whose last_commit is past the refresh's start commit: set (null means never synced) and not old_head or an ancestor
- * of it. With HEAD back at old_head, lifting the fence would let their next sync diff that commit back to old_head and soft-delete what it
- * added, so --abandon refuses them. A commit git cannot place (missing object, unreadable checkout) counts as past.
+ * GST-1457: members whose database is past the refresh's start commit: a last_commit that is set (null means never synced) and neither
+ * old_head nor an ancestor of it, or (GST-1465) a managed-sync import or delete admitted after the refresh began, which a sliced pass leaves
+ * behind with last_commit still at old_head. With HEAD back at old_head, lifting the fence would leave those pages ahead of git or let the
+ * member's next sync soft-delete what it added, so --abandon refuses them. A commit git cannot place (GST-1472: any answer but exit 0 or 1
+ * of merge-base --is-ancestor) counts as past.
*/
-async function membersPastStart(engine: BrainEngine, row: Pick<WorktreeRefreshRow, 'source_ids' | 'old_head'>, root: string | null | undefined): Promise<string[]> {
- const moved = (await engine.executeRaw<{ id: string; last_commit: string | null }>('SELECT id,last_commit FROM sources WHERE id = ANY($1::text[]) ORDER BY id', [row.source_ids]))
- .filter((member): member is { id: string; last_commit: string } => member.last_commit !== null && member.last_commit !== row.old_head);
- if (!moved.length || !root) return moved.map(member => member.id);
+async function membersPastStart(engine: BrainEngine, row: Pick<WorktreeRefreshRow, 'source_ids' | 'old_head' | 'barrier_sequence'>, root: string): Promise<string[]> {
+ const members = await engine.executeRaw<{ id: string; last_commit: string | null; imported: boolean }>(`SELECT s.id,s.last_commit,
+ EXISTS (SELECT 1 FROM persistence_requests r WHERE r.source_id=s.id AND r.sequence > COALESCE($2::bigint,0)
+ AND r.intent->>'kind' IN ('managed_sync_import','managed_sync_delete') AND r.state NOT IN ('failed','conflict','cancelled')) AS imported
+ FROM sources s WHERE s.id = ANY($1::text[]) ORDER BY s.id`, [row.source_ids, row.barrier_sequence == null ? null : String(row.barrier_sequence)]);
+ const moved = members.filter(member => member.imported || (member.last_commit !== null && member.last_commit !== row.old_head));
return withGit(async git => {
const past: string[] = [];
- for (const member of moved) if (!await isAncestor(git, root, member.last_commit, row.old_head)) past.push(member.id);
+ for (const member of moved) if (member.imported || await ancestry(git, root, member.last_commit!, row.old_head) !== true) past.push(member.id);
return past;
}).catch(() => moved.map(member => member.id));
}
/**
- * GST-1457: where the way out moves HEAD. The refresh target, or the newest member last_commit on the target's line when every other
- * member's commit is an ancestor of it (a cycle sync carried a member past the target while syncing, #6712), so --resume never completes
- * with a member ahead of HEAD, whose next sync would roll it back.
+ * GST-1457, GST-1472: where the way out moves HEAD so no member's next sync rolls it back. `forward`: the refresh target, or the newest
+ * member commit on the target's line (a cycle sync carried a member past it while syncing, #6712). `diverged`: member commits on this
+ * refresh's line that do not form one line, each tip listed; no single commit keeps every member's pages. `unplaced`: a member commit git
+ * cannot place (a missing object, an unreadable checkout, a git timeout), so no commit can be named until git reads it. A member already off
+ * old_head's line before the refresh (rewritten history) is the state an uninterrupted refresh completes on, so it names nothing.
*/
-async function keepPagesHead(engine: BrainEngine, row: Pick<WorktreeRefreshRow, 'source_ids' | 'target_head'>, root: string): Promise<string> {
- const commits = [...new Set((await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id = ANY($1::text[])', [row.source_ids]))
- .map(member => member.last_commit).filter((commit): commit is string => !!commit))];
+type WayOut = { kind: 'forward'; head: string } | { kind: 'diverged'; tips: string[] } | { kind: 'unplaced'; members: Array<{ source_id: string; commit: string }> };
+async function keepPagesWayOut(engine: BrainEngine, row: Pick<WorktreeRefreshRow, 'source_ids' | 'old_head' | 'target_head'>, root: string): Promise<WayOut> {
+ const members = (await engine.executeRaw<{ id: string; last_commit: string | null }>('SELECT id,last_commit FROM sources WHERE id = ANY($1::text[]) ORDER BY id', [row.source_ids]))
+ .filter((member): member is { id: string; last_commit: string } => !!member.last_commit);
+ const unplaced = (commits: string[]): WayOut => ({ kind: 'unplaced', members: members.filter(member => commits.includes(member.last_commit)).map(member => ({ source_id: member.id, commit: member.last_commit })) });
return withGit(async git => {
- let head = row.target_head;
- for (const commit of commits) if (commit !== head && await isAncestor(git, root, head, commit)) head = commit;
- for (const commit of commits) if (!await isAncestor(git, root, commit, head)) return row.target_head;
- return head;
- }).catch(() => row.target_head);
+ const line = [row.target_head], lost: string[] = [];
+ for (const { last_commit: commit } of members) {
+ if (line.includes(commit)) continue;
+ const contained = await ancestry(git, root, commit, row.target_head);
+ const onLine = contained === false ? await ancestry(git, root, row.old_head, commit) : contained === null ? null : false;
+ if (onLine === null) lost.push(commit); else if (onLine) line.push(commit);
+ }
+ if (lost.length) return unplaced(lost);
+ const tips: string[] = [];
+ for (const commit of line) {
+ let covered = false;
+ for (const other of line) {
+ if (other === commit || covered) continue;
+ const ancestor = await ancestry(git, root, commit, other);
+ if (ancestor === null) return unplaced([commit, other]);
+ covered = ancestor;
+ }
+ if (!covered) tips.push(commit);
+ }
+ return tips.length === 1 ? { kind: 'forward', head: tips[0]! } as const : { kind: 'diverged', tips } as const;
+ }).catch(() => unplaced(members.map(member => member.last_commit)));
}
/** `git merge-base --is-ancestor`: true or false, or null when git cannot tell (a missing object, an unreadable checkout). */
async function ancestry(git: Git, root: string, ancestor: string, descendant: string): Promise<boolean | null> {
@@ -154,6 +180,15 @@ async function memberOutsideHead(engine: BrainEngine, git: Git, root: string, ro
}
return false;
}
+/**
+ * Whether recovery records the merge at `head`: HEAD is the refresh target or descends from it, and holds every member commit synced on this
+ * refresh's line. A fenced or merged row at exactly the target skips the member check (no member synced while it held the fence). GST-1472:
+ * --abandon at such a HEAD names --resume instead of a reset.
+ */
+async function adoptsHead(engine: BrainEngine, git: Git, root: string, row: WorktreeRefreshRow, head: string | null): Promise<boolean> {
+ return head !== null && (head === row.target_head || await isAncestor(git, root, row.target_head, head)) && await isAncestor(git, root, row.old_head, row.target_head)
+ && ((row.state !== 'recovery_required' && head === row.target_head) || !await memberOutsideHead(engine, git, root, row, head));
+}
/**
* GBEV-44: true when gbrain's commit ledger names every commit in from..to (writes admitted before the fence that landed while the refresh drained).
* Only the wording of a refusal depends on it, so a ledger that cannot be read proves nothing and the commits read as not gbrain's own.
@@ -265,20 +300,43 @@ async function refusedBeforeAbort(engine: BrainEngine, git: Git, root: string, r
&& await ancestry(git, root, row.old_head, head) === true && await ancestry(git, root, row.target_head, head) === false
&& !await memberOutsideHead(engine, git, root, row, head) && await reachedTargetSince(git, root, row, head, startedAt) === false;
}
+/** GST-1477: the way out for an operator who reset to the start commit on purpose to reject an upstream change; git stays the parent. */
+const revertRoute = (root: string, sourceId: string) =>
+ `If the user reset the checkout on purpose to reject an upstream change, keep git the parent instead: after that move, commit git -C ${q(root)} revert --no-edit <the unwanted commits> on top, then gbrain sources refresh ${sourceId} --resume; the next sync removes those pages through history.`;
const keepSyncedWayOut = (row: Pick<WorktreeRefreshRow, 'source_ids'>, root: string, head: string) =>
- `Ask the user first: git -C ${q(root)} merge --ff-only ${head} moves the checkout to the commit its members already synced (it keeps uncommitted edits git can carry; git -C ${q(root)} status --short lists them), then gbrain sources refresh ${row.source_ids[0]} --resume finishes the refresh and keeps the pages its members synced. If git refuses (an uncommitted edit overlaps an incoming file, or HEAD is not an ancestor of ${head}), ask the user before git -C ${q(root)} reset --hard ${head}, which discards local commits and uncommitted edits not in it, then --resume.`;
-/** GST-1457: the refusal when a member synced past old_head; its fix fast-forwards to the commit the members synced (ask_user, preview first), then --resume. */
-async function membersSyncedRefusal(engine: BrainEngine, row: WorktreeRefreshRow, root: string, moved: string[], cause: string): Promise<OperationError> {
+ `Ask the user first: git -C ${q(root)} merge --ff-only ${head} moves the checkout to the commit its members already synced (it keeps uncommitted edits git can carry; git -C ${q(root)} status --short lists them), then gbrain sources refresh ${row.source_ids[0]} --resume finishes the refresh and keeps the pages its members synced. If git refuses (an uncommitted edit overlaps an incoming file, or HEAD is not an ancestor of ${head}), ask the user before git -C ${q(root)} reset --hard ${head}, which discards local commits and uncommitted edits not in it, then --resume. ${revertRoute(root, row.source_ids[0])}`;
+const unplacedText = (way: Extract<WayOut, { kind: 'unplaced' }>) => way.members.map(member => `${member.commit} (${member.source_id}'s last synced commit)`).join(', ');
+/** GST-1472: why the way out names no single fast-forward, appended to the refusal's cause. */
+const wayOutCause = (way: WayOut, root: string) => way.kind === 'unplaced' ? ` Git cannot place ${unplacedText(way)} in ${root}, so recovery cannot tell which commit keeps those pages.`
+ : way.kind === 'diverged' ? ` Their commits do not form one line: ${way.tips.join(', ')}.` : '';
+function wayOutText(row: Pick<WorktreeRefreshRow, 'source_ids'>, root: string, way: WayOut): string {
+ const source = row.source_ids[0];
+ if (way.kind === 'forward') return keepSyncedWayOut(row, root, way.head);
+ if (way.kind === 'unplaced') return `Git cannot place ${unplacedText(way)} (a missing object, an unreadable checkout or a git timeout), so nothing was changed. Fetch it with git -C ${q(root)} fetch --all --no-tags (git -C ${q(root)} cat-file -e <commit>^{commit} confirms git has it), then gbrain sources refresh ${source} --resume names the commit to move the checkout to with git merge --ff-only. If no remote holds the commit any more, ask the user: gbrain never guesses which pages it held.`;
+ return `The members synced commits on lines that do not meet (${way.tips.join(', ')}), so no single commit keeps every member's pages, and which win is the user's call. Ask the user first: git -C ${q(root)} merge --no-edit ${way.tips.join(' ')} joins those lines in one commit that keeps them all (on a conflict git stops with the conflicts in the checkout: resolve and commit them, or git -C ${q(root)} merge --abort), then gbrain sources refresh ${source} --resume finishes the refresh. To drop one line's changes instead, commit git -C ${q(root)} revert --no-edit <those commits> on top of that merge before --resume; the next sync removes those pages through history.`;
+}
+function wayOutFix(row: Pick<WorktreeRefreshRow, 'id' | 'source_ids' | 'old_head'>, root: string, way: WayOut, moved: string[]): Action {
const source = row.source_ids[0];
- const head = await keepPagesHead(engine, row, root);
- const error = refusal('refresh_recovery_required', cause, keepSyncedWayOut(row, root, head), row.id);
- error.fix = { ask_user: true, argv: ['git', '-C', root, 'merge', '--ff-only', head], preview_argv: ['git', '-C', root, 'status', '--short'],
- consent: [], actor: 'agent', requires_exclusive: false,
- why: `Fast-forwards the checkout to ${head}, the commit ${moved.join(', ')} already synced toward; git keeps uncommitted edits it can carry and refuses, changing nothing, when one overlaps an incoming file. Then --resume finishes refresh ${row.id} without rolling a member back.`,
- user_message: `Refresh ${row.id} of ${row.source_ids.join(', ')} stopped with the checkout ${root} back at ${row.old_head}, after ${moved.join(', ')} had already synced past it. Abandoning it would let the next sync delete the pages those sources synced. To keep them, fast-forward the checkout to ${head} (git merge --ff-only keeps uncommitted edits and refuses if one overlaps an incoming file; git status --short lists them) and then run gbrain sources refresh ${source} --resume. Go ahead?`,
- verify: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', source, '--json'] },
- then: { argv: ['gbrain', 'sources', 'refresh', source, '--resume'], consent: [], actor: 'agent', requires_exclusive: false,
- why: `With HEAD at ${head}, which contains the refresh target, records the merge and runs the member syncs, so refresh ${row.id} completes.` } };
+ const verify = { argv: ['gbrain', 'sources', 'writer', 'status', '--source', source, '--json'] };
+ const resume = (why: string): Action => ({ argv: ['gbrain', 'sources', 'refresh', source, '--resume'], consent: [], actor: 'agent', requires_exclusive: false, why });
+ if (way.kind === 'unplaced') return { argv: ['git', '-C', root, 'fetch', '--all', '--no-tags', '--quiet'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: `Git cannot place ${unplacedText(way)} in ${root}, so recovery cannot name the commit that keeps those pages. A fetch moves only remote-tracking refs and brings back a commit a remote still holds; then --resume names the way out. If no remote holds it, ask the user.`,
+ verify: { argv: ['git', '-C', root, 'cat-file', '-e', `${way.members[0]!.commit}^{commit}`] },
+ then: resume(`With git able to place every member commit, names the way out that keeps their pages, or finishes refresh ${row.id}.`) };
+ const head = way.kind === 'forward' ? way.head : null;
+ return { ask_user: true, argv: head ? ['git', '-C', root, 'merge', '--ff-only', head] : ['git', '-C', root, 'merge', '--no-edit', ...(way as { tips: string[] }).tips],
+ preview_argv: ['git', '-C', root, 'status', '--short'], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: head ? `Fast-forwards the checkout to ${head}, the commit ${moved.join(', ')} already synced toward; git keeps uncommitted edits it can carry and refuses, changing nothing, when one overlaps an incoming file. Then --resume finishes refresh ${row.id} without rolling a member back.`
+ : `Merges the lines ${moved.join(', ')} synced (${(way as { tips: string[] }).tips.join(', ')}) into one commit that holds them all; git stops on a conflict. Then --resume finishes refresh ${row.id} without rolling a member back.`,
+ user_message: head ? `Refresh ${row.id} of ${row.source_ids.join(', ')} stopped with the checkout ${root} away from ${head}, after ${moved.join(', ')} had already synced past the pre-refresh commit ${row.old_head}. Abandoning it would let the next sync delete the pages those sources synced. To keep them, fast-forward the checkout to ${head} (git merge --ff-only keeps uncommitted edits and refuses if one overlaps an incoming file; git status --short lists them) and then run gbrain sources refresh ${source} --resume. If you reset the checkout on purpose to reject an upstream change, say so: then fast-forward, commit a git revert of that change on top, and run --resume, so the next sync removes those pages through history. Go ahead with the fast-forward?`
+ : `Refresh ${row.id} of ${row.source_ids.join(', ')} stopped after ${moved.join(', ')} synced commits on lines that do not meet: ${(way as { tips: string[] }).tips.join(', ')}. No single commit keeps every source's pages, so which win is your call. To keep them all, merge those lines in ${root} (git merge --no-edit; on a conflict git stops so it can be resolved) and then run gbrain sources refresh ${source} --resume. To drop one line's changes, merge and then commit a git revert of them on top before --resume. Merge them all?`,
+ then: resume(`With HEAD holding every member's commit, which contains the refresh target, records the merge and runs the member syncs, so refresh ${row.id} completes.`) };
+}
+/** GST-1457: the refusal when a member is past old_head; its fix moves HEAD to the commit that keeps every member's pages (ask_user, preview first), then --resume. */
+async function membersSyncedRefusal(engine: BrainEngine, row: WorktreeRefreshRow, root: string, moved: string[], cause: string): Promise<OperationError> {
+ const way = await keepPagesWayOut(engine, row, root);
+ const error = refusal('refresh_recovery_required', `${cause}${wayOutCause(way, root)}`, wayOutText(row, root, way), row.id);
+ error.fix = wayOutFix(row, root, way, moved);
return error;
}
/**
@@ -405,7 +463,7 @@ async function markRecoveryRequired(engine: BrainEngine, row: WorktreeRefreshRow
const moved = await membersPastStart(engine, row, root);
const error = refusal('refresh_recovery_required',
`The checkout HEAD (${head ?? 'unreadable'}) is not the verified upstream commit ${row.target_head}${moved.length ? `, and ${moved.join(', ')} already synced past the pre-refresh commit ${row.old_head}` : ` nor the pre-refresh commit ${row.old_head}`}; writes to this worktree stay fenced.`,
- moved.length ? `Inspect with gbrain sources writer status ${source}. ${keepSyncedWayOut(row, root, await keepPagesHead(engine, row, root))}`
+ moved.length ? `Inspect with gbrain sources writer status ${source}. ${wayOutText(row, root, await keepPagesWayOut(engine, row, root))}`
: `Inspect with gbrain sources writer status ${source}. Ask the user before resetting the checkout (destructive): git -C ${q(root)} reset --hard ${row.old_head} then gbrain sources refresh ${source} --abandon, or git -C ${q(root)} reset --hard ${row.target_head} then gbrain sources refresh ${source} --resume.`,
row.id);
await engine.transaction(tx => transition(tx, row, ['draining', 'fenced', 'merged', 'syncing', 'recovery_required'], 'recovery_required',
@@ -1138,8 +1196,7 @@ async function recoverOne(engine: BrainEngine, git: Git, row: WorktreeRefreshRow
const by = await ownCommits(git, root, row.old_head, head!) ? OWN_COMMITS : 'a commit gbrain did not make';
const cause = `The refreshing process stopped at its merge: HEAD moved from ${row.old_head} to ${head} (${by}) right before it, so git refused the fast-forward (or never ran it), and nothing was merged.`;
await engine.transaction(tx => transition(tx, row, ['fenced'], 'aborted', { refusal: { code: 'refresh_interrupted', cause }, observed_head: head }));
- } else if (['fenced', 'merged', 'recovery_required'].includes(row.state) && head !== null && (head === row.target_head || await isAncestor(git, root, row.target_head, head))
- && await isAncestor(git, root, row.old_head, row.target_head) && ((row.state !== 'recovery_required' && head === row.target_head) || !await memberOutsideHead(engine, git, root, row, head))) {
+ } else if (['fenced', 'merged', 'recovery_required'].includes(row.state) && await adoptsHead(engine, git, root, row, head)) {
await bookkeeping(engine, row);
} else if (row.state === 'syncing' && head !== null && (head === row.target_head || await isAncestor(git, root, row.target_head, head))) {
// stays syncing; the member syncs run from --resume or any later cycle sync.
@@ -1247,6 +1304,37 @@ async function membersAtTarget(engine: BrainEngine, git: Git, row: WorktreeRefre
return synced;
}
+/**
+ * GST-1465: runs `work` holding every member's drain lease, so no sync pass is in flight while --abandon checks the members and lifts the
+ * fence; a pass that pinned the target while the row was syncing would otherwise import or stamp it after the fence lifts. A lease a live
+ * pass holds refuses sync_drain_lease_held and changes nothing; an expired one is taken over, which fences its holder's later writes out.
+ */
+async function underMemberLeases<T>(engine: BrainEngine, row: WorktreeRefreshRow, work: () => Promise<T>, members: string[] = row.source_ids): Promise<T> {
+ const [member, ...rest] = members;
+ if (!member) return work();
+ const [{ withDrainLease, readDrainHolder }, { LockUnavailableError, syncLockId }] = await Promise.all([import('./sync-lease.ts'), import('../db-lock.ts')]);
+ const held = async (how: string) => {
+ const holder = await readDrainHolder(engine, member).catch(() => null);
+ const error = refusal('sync_drain_lease_held', `Refresh ${row.id} was not abandoned: ${how} (${holder ? `${holder.kind} pid ${holder.pid ?? 'unknown'} on ${holder.host ?? 'an unknown host'}` : 'holder unknown'}), and a pass in flight may still import or stamp the commit it pinned, so lifting the fence now could leave the database ahead of git. Nothing was changed.`,
+ `Wait for that sync pass to finish (gbrain sources writer status --source ${member} --json shows its drain lease holder), then retry gbrain sources refresh ${row.source_ids[0]} --abandon.`, row.id);
+ error.fix = writerStatusFix(`Shows who holds ${member}'s drain lease, read-only; once that pass ends, gbrain sources refresh ${row.source_ids[0]} --abandon checks the members again.`, member);
+ return error;
+ };
+ const box: { done: boolean; value?: T } = { done: false };
+ try {
+ await withDrainLease(engine, member, { holder: { kind: 'refresh', id: row.id }, remote: false }, async () => {
+ box.value = await underMemberLeases(engine, row, work, rest);
+ box.done = true;
+ return { status: 'up_to_date' } as SyncResult;
+ });
+ } catch (error) {
+ if (!(error instanceof LockUnavailableError) || error.lockId !== syncLockId(member)) throw error;
+ throw await held(`a sync pass of ${member} holds its drain lease`);
+ }
+ if (!box.done) throw await held(`${member}'s drain lease moved to another process while the members were checked`);
+ return box.value as T;
+}
+
async function resumeOrAbandon(engine: BrainEngine, sourceId: string, opts: RefreshOptions, syncBudgetMs: number): Promise<WorktreeRefreshResult> {
const binding = await getWorktreeBinding(engine, sourceId, existingHostIdFor(engine));
if (!await managedPersistenceEnabled(engine) || !binding) throw refusal('refresh_not_managed',
@@ -1267,16 +1355,22 @@ async function resumeOrAbandon(engine: BrainEngine, sourceId: string, opts: Refr
if (row.state === 'syncing') throw refusal('refresh_in_progress', 'The checkout already holds the upstream commit; abandoning now would leave files ahead of the database.',
`gbrain sources refresh ${sourceId} --resume`, row.id);
if (row.state !== 'draining' && head !== row.old_head && !await movedBeforeMerge(engine, git, root, row, head) && !await refusedBeforeAbort(engine, git, root, row, head)) {
- if (head === row.target_head) throw refusal('refresh_in_progress', `The checkout is at the refresh target ${row.target_head}; finish it instead of abandoning.`,
- `gbrain sources refresh ${sourceId} --resume`, row.id);
- throw await markRecoveryRequired(engine, row, head, root);
+ if (await adoptsHead(engine, git, root, row, head)) throw refusal('refresh_in_progress', head === row.target_head ? `The checkout is at the refresh target ${row.target_head}; finish it instead of abandoning.`
+ : `The checkout HEAD ${head} descends from the refresh target ${row.target_head}, so --resume records the merge and finishes the refresh; finish it instead of abandoning.`,
+ `gbrain sources refresh ${sourceId} --resume`, row.id);
+ if (head !== row.target_head) throw await markRecoveryRequired(engine, row, head, root);
+ throw await membersSyncedRefusal(engine, row, root, await membersPastStart(engine, row, root), `Refresh ${row.id} was not abandoned: the checkout is at the refresh target ${row.target_head}, but a member synced a commit it does not hold, so --resume cannot finish it there either. Nothing was changed.`);
}
- const moved = row.state === 'recovery_required' ? await membersPastStart(engine, row, root) : [];
- if (moved.length) throw await membersSyncedRefusal(engine, row, root, moved, `Refresh ${row.id} was not abandoned: the checkout is back at the pre-refresh commit ${row.old_head}, but ${moved.join(', ')} already synced past it, so lifting the fence would let the next sync soft-delete the pages that sync added. Nothing was changed.`);
- await engine.transaction(tx => transition(tx, row, ['draining', 'fenced', 'merged', 'recovery_required'], 'aborted',
- { refusal: { code: 'refresh_abandoned', cause: `The operator abandoned the refresh with HEAD at ${head}.` } }));
- return { ...empty, status: 'abandoned', refresh_id: row.id, source_ids: row.source_ids, old_head: row.old_head, target_head: row.target_head,
- upstream_ref: row.upstream_ref, preserved_uncommitted: row.preserved_uncommitted, next: `gbrain sources refresh ${sourceId}` };
+ const abandon = async (): Promise<WorktreeRefreshResult> => {
+ const moved = row.state === 'recovery_required' ? await membersPastStart(engine, row, root) : [];
+ if (moved.length) throw await membersSyncedRefusal(engine, row, root, moved, `Refresh ${row.id} was not abandoned: the checkout is back at the pre-refresh commit ${row.old_head}, but ${moved.join(', ')} already synced past it, so lifting the fence would leave those pages ahead of git or let the next sync soft-delete what that sync added. Nothing was changed.`);
+ await engine.transaction(tx => transition(tx, row, ['draining', 'fenced', 'merged', 'recovery_required'], 'aborted',
+ { refusal: { code: 'refresh_abandoned', cause: `The operator abandoned the refresh with HEAD at ${head}.` } }));
+ return { ...empty, status: 'abandoned', refresh_id: row.id, source_ids: row.source_ids, old_head: row.old_head, target_head: row.target_head,
+ upstream_ref: row.upstream_ref, preserved_uncommitted: row.preserved_uncommitted, next: `gbrain sources refresh ${sourceId}` };
+ };
+ // GST-1465: a syncing row's members may have a pass in flight; the check and the abort hold every member's drain lease.
+ return row.state === 'recovery_required' ? withTopologyLocks(engine, sourceId, () => underMemberLeases(engine, row, abandon), undefined, 30_000) : abandon();
}
return resumeHeld(engine, git, sourceId, active.id, root, head, empty, syncBudgetMs);
});
@@ -1291,10 +1385,12 @@ async function resumeHeld(engine: BrainEngine, git: Git, sourceId: string, refre
await engine.executeRaw(`UPDATE persistence_worktree_refreshes SET outcome=outcome||jsonb_build_object('holder',$2::text::jsonb,'previous_holder',COALESCE(outcome->'previous_holder',outcome->'holder'))
WHERE id=$1::uuid AND state IN ${ACTIVE_REFRESH_STATES_SQL}`, [refreshId, JSON.stringify(refreshHolder(engine))]);
let row = await withTopologyLocks(engine, sourceId, async () => recoverOne(engine, git, await readRefresh(engine, refreshId), root, unattended), undefined, 30_000);
- if (row.state === 'recovery_required' && head === row.old_head) {
+ if (row.state === 'recovery_required' && head !== null) {
const moved = await membersPastStart(engine, row, root);
- if (moved.length) throw await membersSyncedRefusal(engine, row, root, moved, `The checkout is back at the pre-refresh commit ${row.old_head}, but ${moved.join(', ')} already synced past it, so --resume cannot finish refresh ${row.id} from here and --abandon would let the next sync soft-delete the pages that sync added.`);
- throw refusal('refresh_recovery_required',
+ if (moved.length) throw await membersSyncedRefusal(engine, row, root, moved, head === row.old_head
+ ? `The checkout is back at the pre-refresh commit ${row.old_head}, but ${moved.join(', ')} already synced past it, so --resume cannot finish refresh ${row.id} from here and --abandon would let the next sync soft-delete the pages that sync added.`
+ : `The checkout HEAD ${head} does not hold every commit ${moved.join(', ')} synced past the pre-refresh commit ${row.old_head}, so --resume cannot finish refresh ${row.id} there.`);
+ if (head === row.old_head) throw refusal('refresh_recovery_required',
`The checkout is back at the pre-refresh commit ${row.old_head}; nothing remains to resume.`, `gbrain sources refresh ${sourceId} --abandon`, row.id);
}
if (row.state === 'recovery_required') {
@@ -1395,10 +1491,17 @@ export async function refreshHolderReport(engine: BrainEngine, row: Pick<Worktre
// #7712, #7731: what the next step does depends on the checkout HEAD, read on the host that holds the checkout.
const head = binding?.local_path ? await withGit(git => headOf(git, binding.local_path!)).catch(() => null) : undefined;
if (row.state === 'recovery_required') {
- const keep = binding?.local_path ? await keepPagesHead(engine, row, binding.local_path) : row.target_head;
+ // GST-1477: HEAD and the members' ancestry are read in the owner's checkout; without it nothing here can say which step is safe.
+ if (!binding?.local_path) return { ...base, auto_recovery: 'none', fix: { argv: verify.argv, consent: [], actor: 'host_admin', requires_exclusive: false, verify,
+ why: `Refresh ${row.id} stopped without verifying the checkout HEAD, and its checkout is on host ${holderHost ?? 'unknown'}, not this one. Whether --abandon is safe depends on that checkout's HEAD and on whether each member's last synced commit is an ancestor of the start commit ${row.old_head}, which only the owner host can check, so this host names no step. Run this on the owner host: it names --resume, --abandon or the way out that keeps the members' pages.` } };
+ const root = binding.local_path;
+ const way = await keepPagesWayOut(engine, row, root);
+ const keep = way.kind === 'forward' ? way.head : null;
if (head === row.target_head && keep === row.target_head) return { ...base, auto_recovery: 'none', fix: { argv: resume, consent: [], actor: 'agent', requires_exclusive: false, verify,
why: `Refresh ${row.id} stopped without verifying the checkout HEAD, which is now the refresh target ${row.target_head}, so --resume records the merge and finishes the refresh; nothing needs resetting.` } };
- const moved = await membersPastStart(engine, row, binding?.local_path);
+ const moved = await membersPastStart(engine, row, root);
+ if (way.kind !== 'forward') return { ...base, auto_recovery: 'none', fix: { ...wayOutFix(row, root, way, moved),
+ why: `Refresh ${row.id} stopped without verifying the checkout HEAD, and ${moved.join(', ')} already synced past the start commit ${row.old_head}, so --abandon refuses.${wayOutCause(way, root)} ${wayOutText(row, root, way)}` } };
if (head === row.old_head && !moved.length) return { ...base, auto_recovery: 'none', fix: { argv: ['gbrain', 'sources', 'refresh', source, '--abandon'], consent: [], actor: 'agent', requires_exclusive: false, verify,
why: `Refresh ${row.id} stopped without verifying the checkout HEAD, which is back at the pre-refresh commit ${row.old_head}, so --abandon lifts the fence and nothing moved; then gbrain sources refresh ${source} starts again.` } };
if (head === row.old_head) return { ...base, auto_recovery: 'none', fix: { argv: resume, consent: [], actor: 'agent', requires_exclusive: false, verify,
diff --git a/test/e2e/worktree-refresh-postgres.test.ts b/test/e2e/worktree-refresh-postgres.test.ts
index d8bf713f56..c37ab8b18b 100644
--- a/test/e2e/worktree-refresh-postgres.test.ts
+++ b/test/e2e/worktree-refresh-postgres.test.ts
@@ -8,4 +8,5 @@ await registerPostgresTests(
() => import('../worktree-refresh-orphan-7679.test.ts'),
() => import('../refresh-publish-diverged-7686.test.ts'),
() => import('../refresh-source-changed-retry-8617.test.ts'),
+ () => import('../refresh-recovery-followups-gst1465.test.ts'),
);
diff --git a/test/refresh-recovery-followups-gst1465.test.ts b/test/refresh-recovery-followups-gst1465.test.ts
new file mode 100644
index 0000000000..be22ba5c89
--- /dev/null
+++ b/test/refresh-recovery-followups-gst1465.test.ts
@@ -0,0 +1,286 @@
+/**
+ * GST-1465, GST-1472, GST-1477: the refresh-recovery follow-ups from the GST-1457 reviews (#8661).
+ *
+ * Protects: "git is the parent" on every manual way out of an interrupted `gbrain sources refresh`. `--abandon` never lifts the fence
+ * while a member's database is past the start commit, whether its `last_commit` moved or a sliced pass imported part of the target
+ * (GST-1465 #1), or while a sync pass that pinned the target still holds a member's drain lease (GST-1465 #2). Every way out a refusal
+ * or writer status names actually finishes the refresh, or the refusal names its own distinct reason: a HEAD past the target (GST-1472
+ * #1), members synced to diverged lines (#2), a member commit git cannot place (#3), writer status read off the owner host (GST-1477 #1),
+ * and an operator who reset the checkout on purpose to reject an upstream change (GST-1477 #2: revert on top of the target, then --resume).
+ * Seams: the refresh's `hooks.boundary` crash, the real managed sync (a slice for #1, a fault hook pausing a pass after its level read for
+ * #2), HEAD moved by hand; member commits set with the coordinated write only where a test says so.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { tryAcquireNativeLock } from '../src/core/persistence/native-lock.ts';
+import { refreshLockPath, refreshWorktree } from '../src/core/persistence/worktree-refresh.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { commitFile, git, page, withRefreshFixture, type RefreshFixture } from './helpers/worktree-refresh-fixture.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ installFaultHook(undefined);
+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }
+ await closePostgres?.();
+});
+
+type Refusal = { code?: string; message?: string; suggestion?: string; fix?: Record<string, any> };
+const each = async (fn: (f: RefreshFixture) => Promise<void>) => { for (const engine of engines) await withRefreshFixture(engine, fn); };
+const settle = <T>(promise: Promise<T>) => promise.then(value => ({ value, error: null as Refusal | null }), error => ({ value: null as T | null, error: error as Refusal }));
+const refused = async (promise: Promise<unknown>, code: string): Promise<Refusal> => {
+ const { error } = await settle(promise);
+ expect(error, `expected refusal ${code}`).not.toBeNull();
+ expect(error!.code).toBe(code);
+ return error!;
+};
+const sync = (f: RefreshFixture, sourceId: string) => performManagedSync(f.engine, { sourceId, noPull: true, noEmbed: true });
+const livePages = async (f: RefreshFixture, sourceId: string) => (await f.engine.executeRaw<{ slug: string }>(
+ 'SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [sourceId])).map(row => row.slug);
+const states = async (f: RefreshFixture) => (await f.refreshRows()).map(row => row.state);
+const setLastCommit = (f: RefreshFixture, member: string, sha: string) => f.engine.transaction(tx => withCoordinatedWrite(tx, [member],
+ () => tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [member, sha]), TEST_WRITE_ATTRIBUTION));
+const writerStatusRow = async (f: RefreshFixture) => (await runPersistenceAdministration(f.engine, 'writer_status', { source_id: f.alpha }) as
+ { worktree_refreshes: Array<Record<string, any>> }).worktree_refreshes[0];
+/** A refresh killed at `point`, its row left in `state` with the consumer stopped, so only the manual path recovers it. */
+async function orphanAt(f: RefreshFixture, point: 'fenced' | 'merged' | 'syncing', state: string) {
+ await expect(refreshWorktree(f.engine, f.alpha, { hooks: { boundary: at => { if (at === point) throw new Error(`simulated crash at ${at}`); } } }))
+ .rejects.toThrow('simulated crash');
+ await disposePersistenceConsumer(f.engine);
+ const [orphan] = await f.refreshRows();
+ await f.engine.executeRaw('UPDATE persistence_worktree_refreshes SET state=$2,completed_at=NULL WHERE id=$1::uuid', [orphan.id, state]);
+ return orphan;
+}
+
+test('GST-1465 #1: a member a sliced sync carried partly into the target, still at the start commit, keeps --abandon from lifting the fence', () => each(async f => {
+ // Value: protects=the database never ends ahead of git after --abandon: a member whose pass imported pages of the target but stopped before
+ // its stamp (last_commit still old_head) counts as past the start commit, so --resume names the fast-forward, --abandon refuses, and that
+ // way out completes with every page at HEAD; fails_when=the member check reads last_commit alone, so --abandon lifts the fence and the
+ // imported pages stay live with no file at HEAD; why_new=GBRA-323's probe; 7r-7t move last_commit; seam=performManagedSync's slice (one page);
+ // no_claim=a slice that deleted pages (the same request check).
+ f.push('alpha/two.md', page('Alpha two', 'Upstream two.'));
+ f.push('alpha/three.md', page('Alpha three', 'Upstream three.'));
+ const target = f.push('alpha/four.md', page('Alpha four', 'Upstream four.'));
+ const old = f.head();
+ const before = await livePages(f, f.alpha);
+ const orphan = await orphanAt(f, 'syncing', 'syncing');
+ const sliced = await performManagedSync(f.engine, { sourceId: f.alpha, noPull: true, noEmbed: true }, { maxPages: 1, maxMs: 60_000 });
+ expect(sliced.status).toBe('partial');
+ expect(await f.lastCommit(f.alpha)).toBe(old);
+ const partial = await livePages(f, f.alpha);
+ expect(partial.length).toBe(before.length + 1);
+ git(f.root, 'reset', '-q', '--hard', old);
+ const resume = await refused(refreshWorktree(f.engine, f.alpha, { resume: true }), 'refresh_recovery_required');
+ expect(resume.suggestion).not.toContain('--abandon');
+ expect(resume.fix).toMatchObject({ ask_user: true, argv: ['git', '-C', f.root, 'merge', '--ff-only', target] });
+ expect((await writerStatusRow(f)).fix.argv).not.toContain('--abandon');
+ const abandon = await refused(refreshWorktree(f.engine, f.alpha, { abandon: true }), 'refresh_recovery_required');
+ expect(abandon.message).toContain(f.alpha);
+ await refused(sync(f, f.alpha), 'refresh_recovery_required');
+ expect(await livePages(f, f.alpha)).toEqual(partial);
+ expect(await states(f)).toEqual(['recovery_required']);
+ git(f.root, 'merge', '-q', '--ff-only', target);
+ expect(await refreshWorktree(f.engine, f.alpha, { resume: true })).toMatchObject({ refresh_id: orphan.id, status: 'completed' });
+ expect(await f.lastCommit(f.alpha)).toBe(target);
+ expect(await livePages(f, f.alpha)).toEqual(['four', 'one', 'three', 'two']);
+}), 180_000);
+
+test('GST-1465 #2: --abandon refuses while a pass that pinned the target holds a member\'s drain lease, so it never publishes after the fence lifts', () => each(async f => {
+ // Value: protects=the member check and the abort run under every member's drain lease: a cycle pass that read HEAD at the target while the
+ // row was syncing, still in flight when HEAD is reset and --resume/--abandon run, makes --abandon refuse sync_drain_lease_held instead of
+ // lifting the fence under it; once it finishes, the check sees what it published and names the fast-forward; fails_when=--abandon reads
+ // last_commit and aborts without the leases, so the pass stamps last_commit=target over HEAD=old_head; why_new=GST-1465 #2 was theoretical;
+ // seam=a fault hook pausing the real pass after its level read; no_claim=a holder that stopped renewing (the lease takeover fences it).
+ const target = f.push('alpha/two.md', page('Alpha two', 'Upstream two.'));
+ const old = f.head();
+ const before = await livePages(f, f.alpha);
+ const orphan = await orphanAt(f, 'syncing', 'syncing');
+ let reached!: () => void, release!: () => void;
+ const paused = new Promise<void>(resolve => { reached = resolve; });
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ installFaultHook(async (point, detail) => {
+ if (point !== 'sync:level_read' || detail.sourceId !== f.alpha) return;
+ installFaultHook(undefined);
+ reached();
+ await gate;
+ });
+ let pass: Promise<unknown> | undefined;
+ try {
+ pass = settle(sync(f, f.alpha));
+ await paused;
+ git(f.root, 'reset', '-q', '--hard', old);
+ await refused(refreshWorktree(f.engine, f.alpha, { resume: true }), 'refresh_recovery_required');
+ const held = await refused(refreshWorktree(f.engine, f.alpha, { abandon: true }), 'sync_drain_lease_held');
+ expect(held.message).toContain(f.alpha);
+ expect(held.suggestion).toContain(`gbrain sources refresh ${f.alpha} --abandon`);
+ expect(await states(f)).toEqual(['recovery_required']);
+ } finally { installFaultHook(undefined); release(); await pass; }
+ const after = await settle(refreshWorktree(f.engine, f.alpha, { abandon: true }));
+ if (after.error) {
+ expect(after.error.code).toBe('refresh_recovery_required');
+ git(f.root, 'merge', '-q', '--ff-only', target);
+ expect(await refreshWorktree(f.engine, f.alpha, { resume: true })).toMatchObject({ refresh_id: orphan.id, status: 'completed' });
+ expect(await livePages(f, f.alpha)).toEqual(['one', 'two']);
+ } else {
+ expect(after.value).toMatchObject({ status: 'abandoned' });
+ expect(await f.lastCommit(f.alpha)).toBe(old);
+ expect(await livePages(f, f.alpha)).toEqual(before);
+ }
+}), 180_000);
+
+for (const state of ['fenced', 'merged'] as const) {
+ test(`GST-1472 #1: a ${state} orphan whose HEAD descends from the target finishes on the first --resume, and --abandon names --resume`, () => each(async f => {
+ // Value: protects=a HEAD past the target is accepted for fenced and merged rows (after the member check), so one --resume completes and
+ // --abandon refuses refresh_in_progress naming --resume without moving the row to recovery_required or naming a reset; fails_when=either
+ // path marks the row recovery_required first, so the first --resume (or --abandon) names a fast-forward and a hard-reset fallback the
+ // operator does not need; why_new=7v covers recovery_required rows only; seam=a crash at merged, a local commit on top of the target;
+ // no_claim=a member synced off HEAD's line (7w, 7x).
+ const target = f.push('alpha/two.md', page('Alpha two', 'Upstream two.'));
+ const orphan = await orphanAt(f, 'merged', state);
+ expect(f.head()).toBe(target);
+ const past = commitFile(f.root, 'alpha/three.md', page('Alpha three', 'A local commit on top of the target.'));
+ const abandon = await refused(refreshWorktree(f.engine, f.alpha, { abandon: true }), 'refresh_in_progress');
+ expect(abandon.suggestion).toContain(`gbrain sources refresh ${f.alpha} --resume`);
+ expect(abandon.suggestion).not.toContain('reset --hard');
+ expect(await states(f)).toEqual([state]);
+ expect(await refreshWorktree(f.engine, f.alpha, { resume: true })).toMatchObject({ refresh_id: orphan.id, status: 'completed' });
+ expect(f.head()).toBe(past);
+ expect(await f.lastCommit(f.alpha)).toBe(past);
+ }), 180_000);
+}
+
+test('GST-1472 #2: members synced to diverged lines refuse with the divergence named, and the named merge then --resume finishes', () => each(async f => {
+ // Value: protects=when member commits do not form one line, the refusal and writer status name each diverged commit and ask the user to
+ // merge them (git merge keeps both members' pages), never the target-only fast-forward --resume would refuse again; that merge then
+ // --resume completes with every synced page live; fails_when=keepPagesHead falls back to target_head, so every named way out loops back to
+ // the fenced row; why_new=7x has one member on a sibling line of the HEAD it tries, not two diverged members; seam=two local commits on top of
+ // the target, each synced by the real managed sync while the test holds the refresh lock (so the owner scan leaves the row syncing);
+ // no_claim=a merge that conflicts (git stops with the conflicts in the checkout), or the owner scan completing such a row (rewritten history).
+ const target = f.push('alpha/two.md', page('Alpha two', 'Upstream two.'));
+ const old = f.head();
+ const orphan = await orphanAt(f, 'syncing', 'syncing');
+ const betaLine = commitFile(f.root, 'beta/two.md', page('Beta two', 'Synced on one line past the target.'));
+ await sync(f, f.beta);
+ git(f.root, 'reset', '-q', '--hard', target);
+ const alphaLine = commitFile(f.root, 'alpha/three.md', page('Alpha three', 'Synced on another line past the target.'));
+ const lock = (await tryAcquireNativeLock(refreshLockPath(f.worktreeId)))!;
+ try { await sync(f, f.alpha); await disposePersistenceConsumer(f.engine); } finally { await lock.release(); }
+ expect(await states(f)).toEqual(['syncing']);
+ expect([await f.lastCommit(f.alpha), await f.lastCommit(f.beta)]).toEqual([alphaLine, betaLine]);
+ const pages = [await livePages(f, f.alpha), await livePages(f, f.beta)];
+ git(f.root, 'reset', '-q', '--hard', old);
+ const resume = await refused(refreshWorktree(f.engine, f.alpha, { resume: true }), 'refresh_recovery_required');
+ for (const text of [resume.message!, resume.suggestion!]) { expect(text).toContain(alphaLine); expect(text).toContain(betaLine); }
+ expect(resume.fix).toMatchObject({ ask_user: true, then: { argv: ['gbrain', 'sources', 'refresh', f.alpha, '--resume'] } });
+ expect(resume.fix!.argv).not.toEqual(['git', '-C', f.root, 'merge', '--ff-only', target]);
+ expect(resume.fix!.user_message).toContain(alphaLine);
+ const status = await writerStatusRow(f);
+ expect(status.fix.why).toContain(betaLine);
+ expect(status.fix.why).not.toContain(`fast-forward the checkout to ${target}`);
+ await refused(refreshWorktree(f.engine, f.alpha, { abandon: true }), 'refresh_recovery_required');
+ git(f.root, ...resume.fix!.argv.slice(3));
+ expect(await refreshWorktree(f.engine, f.alpha, { resume: true })).toMatchObject({ refresh_id: orphan.id, status: 'completed' });
+ for (const member of [f.alpha, f.beta]) await sync(f, member);
+ expect([await livePages(f, f.alpha), await livePages(f, f.beta)]).toEqual(pages);
+}), 180_000);
+
+test('GST-1472 #3: a member commit git cannot place refuses with that reason, never a fast-forward --resume would refuse again; fetching it unblocks the way out', () => each(async f => {
+ // Value: protects=membersPastStart, keepPagesHead and the resume guard read git's answer the same way (exit 1 is "not an ancestor", any
+ // other failure is "cannot place"), so a member commit missing from the checkout gets its own refusal naming the commit and a fetch, and
+ // once git has it the usual fast-forward way out completes; fails_when=keepPagesHead treats the failure as "not ahead" and names the
+ // target, so the fast-forward then --resume loops on the same row; why_new=7t checks only that --abandon refuses it; seam=a member
+ // last_commit on a commit the managed checkout never fetched (pushed to another upstream branch); no_claim=a pruned object gone for good.
+ const target = f.push('alpha/two.md', page('Alpha two', 'Upstream two.'));
+ const old = f.head();
+ const orphan = await orphanAt(f, 'syncing', 'syncing');
+ await sync(f, f.alpha);
+ const elsewhere = commitFile(f.upstream, 'beta/two.md', page('Beta two', 'Synced from a commit this checkout never fetched.'));
+ git(f.upstream, 'push', '-q', 'origin', `${elsewhere}:refs/heads/side`);
+ git(f.upstream, 'reset', '-q', '--hard', target);
+ await setLastCommit(f, f.beta, elsewhere);
+ git(f.root, 'reset', '-q', '--hard', old);
+ for (const step of ['--resume at the start commit', '--resume at the target']) {
+ if (step.endsWith('target')) git(f.root, 'merge', '-q', '--ff-only', target);
+ const unplaced = await refused(refreshWorktree(f.engine, f.alpha, { resume: true }), 'refresh_recovery_required');
+ expect(unplaced.message, step).toContain(elsewhere);
+ expect(unplaced.message, step).toContain('cannot place');
+ expect(unplaced.fix, step).toMatchObject({ argv: ['git', '-C', f.root, 'fetch', '--all', '--no-tags', '--quiet'], then: { argv: ['gbrain', 'sources', 'refresh', f.alpha, '--resume'] } });
+ expect((await writerStatusRow(f)).fix.why, step).toContain(elsewhere);
+ expect((await writerStatusRow(f)).fix.why, step).not.toContain('finishes it once HEAD is');
+ }
+ git(f.root, ...['fetch', '--all', '--no-tags', '--quiet']);
+ const named = await refused(refreshWorktree(f.engine, f.alpha, { resume: true }), 'refresh_recovery_required');
+ expect(named.fix).toMatchObject({ argv: ['git', '-C', f.root, 'merge', '--ff-only', elsewhere] });
+ git(f.root, 'merge', '-q', '--ff-only', elsewhere);
+ expect(await refreshWorktree(f.engine, f.alpha, { resume: true })).toMatchObject({ refresh_id: orphan.id, status: 'completed' });
+}), 180_000);
+
+test('GST-1477 #1: writer status read off the owner host says the member check needs the owner host instead of reporting members as past', () => each(async f => {
+ // Value: protects=without the owner's checkout, refreshHolderReport does not guess member ancestry (a member merely behind the start commit
+ // read as past), so its fix sends the operator to writer status on the owner host, which names --abandon there; fails_when=membersPastStart
+ // counts every member whose last_commit is not old_head as past when it has no checkout; why_new=7t reads status on the owner host; seam=the
+ // recorded holder host set to another host id; no_claim=a real second host.
+ f.push('alpha/two.md', page('Alpha two', 'Upstream two.'));
+ const old = f.head();
+ const orphan = await orphanAt(f, 'merged', 'recovery_required');
+ await setLastCommit(f, f.alpha, git(f.root, 'rev-parse', `${old}~1`));
+ git(f.root, 'reset', '-q', '--hard', old);
+ const elsewhere = randomUUID();
+ await f.engine.executeRaw(`UPDATE persistence_worktree_refreshes SET outcome=jsonb_set(outcome,'{holder,host_id}',to_jsonb($2::text)) WHERE id=$1::uuid`, [orphan.id, elsewhere]);
+ const remote = await writerStatusRow(f);
+ expect(remote).toMatchObject({ liveness: 'unknown', auto_recovery: 'none', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', f.alpha, '--json'], actor: 'host_admin' } });
+ expect(remote.fix.why).toContain('owner host');
+ expect(remote.fix.why).toContain(elsewhere);
+ expect(remote.fix.why).not.toContain('already synced past');
+ await f.engine.executeRaw(`UPDATE persistence_worktree_refreshes SET outcome=jsonb_set(outcome,'{holder,host_id}','null'::jsonb) WHERE id=$1::uuid`, [orphan.id]);
+ expect(await writerStatusRow(f)).toMatchObject({ fix: { argv: ['gbrain', 'sources', 'refresh', f.alpha, '--abandon'] } });
+ expect((await refreshWorktree(f.engine, f.alpha, { abandon: true })).status).toBe('abandoned');
+}), 180_000);
+
+test('GST-1477 #2: an operator who reset to the start commit on purpose is named the revert route, and revert on top of the target then --resume removes those pages through history', () => each(async f => {
+ // Value: protects=the members-synced refusal names the deliberate-rollback route (fast-forward, git revert the unwanted commits, --resume)
+ // beside the fast-forward, with no consent-free override, and that route keeps git the parent: the refresh completes and the next sync
+ // soft-deletes the reverted page because history removed it; fails_when=the only route named is the fast-forward the operator rejected;
+ // why_new=7r follows the fast-forward only; seam=the member synced by the real managed sync, HEAD reset by hand; no_claim=a revert that conflicts.
+ const target = f.push('alpha/two.md', page('Alpha two', 'An upstream change the operator rejects.'));
+ const old = f.head();
+ const orphan = await orphanAt(f, 'syncing', 'syncing');
+ await sync(f, f.alpha);
+ expect(await livePages(f, f.alpha)).toEqual(['one', 'two']);
+ git(f.root, 'reset', '-q', '--hard', old);
+ const resume = await refused(refreshWorktree(f.engine, f.alpha, { resume: true }), 'refresh_recovery_required');
+ const abandon = await refused(refreshWorktree(f.engine, f.alpha, { abandon: true }), 'refresh_recovery_required');
+ for (const refusal of [resume, abandon]) {
+ expect(refusal.suggestion).toContain(`git -C ${f.root} revert`);
+ expect(refusal.fix!.user_message).toContain('git revert');
+ expect(refusal.fix!.argv).toEqual(['git', '-C', f.root, 'merge', '--ff-only', target]);
+ }
+ git(f.root, 'merge', '-q', '--ff-only', target);
+ git(f.root, 'revert', '--no-edit', target);
+ const reverted = f.head();
+ expect(await refreshWorktree(f.engine, f.alpha, { resume: true })).toMatchObject({ refresh_id: orphan.id, status: 'completed' });
+ await sync(f, f.alpha);
+ expect(await f.lastCommit(f.alpha)).toBe(reverted);
+ expect(await livePages(f, f.alpha)).toEqual(['one']);
+}), 180_000);