Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(refresh): --abandon refuses a recovery_required row once a member synced past the start commit (GST-1457)
garrytan199ecd99eec6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ee9137fb71..8e978ccb42 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,17 @@ identifiers and attribution are available in the pre-removal Git revision## [Unreleased]+**`gbrain sources refresh --abandon` no longer lets the next sync delete pages a member source already synced.**++A refresh interrupted after a member source synced the upstream commit, then moved to `recovery_required` with the checkout back at the commit it started from, could be abandoned: `--resume` refused and named `--abandon`, `--abandon` lifted the fence, and the next sync diffed that member back to the start commit and soft-deleted every page it had synced. `--abandon` now refuses such a row (`refresh_recovery_required`, nothing changed) once any member's `last_commit` is neither the start commit nor empty, and `--resume` no longer names `--abandon` there. Both name the one way out that keeps the pages, as an ask-the-user fix: preview with `git -C <checkout> status --short`, reset the checkout to the upstream commit, then `--resume`. A row whose members never moved is abandoned exactly as before, and sync's deletion behaviour is unchanged.++### Itemized changes++- `src/core/persistence/worktree-refresh.ts`: one member check (`membersPastStart`) feeds `--abandon`, the `--resume` refusal at the start commit, the stored `recovery_required` fix and writer status.+- Tests: `test/persistence-worktree-refresh.test.ts` 7r (the three-step chain: crash while syncing, member synced, HEAD reset; pages survive, then reset-to-target and `--resume` completes) and 7s (no member moved: `--abandon` still works), on PGLite and on Postgres through `test/e2e/worktree-refresh-postgres.test.ts`.++## [Unreleased]+**Sync and source-refresh follow-ups from wave #8123: an interrupted refresh names what holds it and how to finish it, managed-sync preparations stop waiting on table locks, code sources converge on their first full sync, and `sync.write_through=false`, impossible timeline dates, image names, dry runs and missing source directories behave as documented.****`gbrain sources refresh` says what is actually holding an interrupted refresh, and its owner recovery stops holding locks it doesn't need (#8123).**diff --git a/docs/architecture/key-files/core-persistence-git.md b/docs/architecture/key-files/core-persistence-git.mdindex ca8249db19..738bf92e60 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, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member 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; 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`. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command). 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), `test/worktree-refresh-orphan-7679.test.ts` (SIGKILL mid-syncing, live-holder no-steal), `test/oversize-hold-rescreen-8072.test.ts` (budget), Postgres via `test/e2e/worktree-refresh-*postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.+- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member 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; 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`. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit, and never on a `recovery_required` row once a member's `last_commit` moved off it (GST-1457: the next sync would soft-delete what it synced). `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), `test/worktree-refresh-orphan-7679.test.ts` (SIGKILL mid-syncing, live-holder no-steal), `test/oversize-hold-rescreen-8072.test.ts` (budget), Postgres via `test/e2e/worktree-refresh-*postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.- `src/core/persistence/git-gap.ts` + `src/commands/sources-git-gap.ts` + `src/commands/doctor/checks/db-ahead-of-git.ts` — git-canonical memory, wave G1 (`docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census`), read-only. `declaredDatabaseOnly` is the one predicate for pages that may not have a tracked file, tested in order: a read-only mirror source, a private page (`isPrivatePage`), an alias-private page (`isDerivationPrivate`), lineage-private (computed in SQL from `privatePagesFilterFragment`), `database_only_reason`, a `storage.db_only` prefix (`isSourceDbOnlySlug`, refusing an invalid gbrain.yml), a never-filed derive-phase page (page-prepare.ts `isNeverFiledDerivedPage`: no `source_path`/`source_uri` under `DERIVE_PHASE_DB_ONLY_DEFAULTS`), a path the checkout's Git ignores (`ignoredPaths`: filter-free `check-ignore -z --stdin`, tracked files never reported, exit 1 = none, null when Git cannot answer). The equality contract compares a committed blob with the page's export view (`readExportPage`, withdrawals overlaid; the census reads a batch's views with `readExportPages`, the same snapshots in two statements, #7617): an inline blob parsed as reconcile parses a canonical file, aligned with the stored type, subtype and #6429 stamp and compared by `reconcileCanonical` digest; a segmented page by the Git blob id of its streamed export. HEAD is read with hardened plumbing only (`readHeadTree`: one `ls-tree -r -l -z --full-tree` under the source's directory; `readBlobs`: `cat-file --batch` in calls of at most 64 MiB) and the working tree by hashing raw bytes (`worktreeBlobOid`), never `git status`/`git diff`, so no repository filter, textconv or fsmonitor runs. `gbrain sources git-gap <id> [--sample n] [--json]` (trusted local CLI, not an MCP op) puts every live page in one state (`equal`, `database_ahead`, `git_ahead` when the sync import record's `blob_oid`/`disk_blob_oid` differs from HEAD, else folded into `database_ahead` and counted in `database_ahead_without_import_record`, `declared_database_only` per class, `undeclared_database_only`, `worktree_only`, `unparseable`, `unsafe_path`), reports the working tree separately, and counts rows with no Git home (unfenced active facts, fenced facts on a missing page or a page without a committed file, links whose `link_source` is not in `DERIVED_LINK_SOURCES`, timeline rows on pages without a file), open `sync-hold` records by code and parked effect targets by kind and code. Each 256-page batch reads in its own read-only transaction. Doctor `db_ahead_of_git` runs the census per non-archived source whose directory is a Git checkout (others are only counted) under `GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS` (default 10 s) and the entry deadline; it is always `ok` (informational) and lists totals only, a source the budget stopped or never reached as partial. Tests: `test/git-gap-census.test.ts` (PGLite and Postgres).- `src/core/persistence/git-declared.ts` + `src/core/persistence/git-canonical-schema.ts` (migration `git_canonical_declared`) — git-canonical memory, wave G7a: the declared database-only classes of a strict source (`sources.config.canonical = "git"`, default off). `strictPageClass` judges a page by its slug and prior file (`declaredPathClass`: `db_only_prefix` for a `storage.db_only` dir, `derive_folder` for a never-filed derive-phase page; G3's indexer reads the same function) and then its rendered content (`privacyClass`: `private`, `alias_private`, or `lineage_private` from the same SQL remote reads use, `privatePagesFilterFragment`, over the page's own values). `page-prepare.ts` `prepareFileTarget` asks it before it builds a strict file target: a declared page gets no target (no file, no door commit, no Git effect), an untracked ignored target is `git_ignored`, a page turning private gets the removal of the file it still has in the worktree or at HEAD, and a path whose `filter` attribute is `lfs` passes `assertLfsTarget` only with `storage.git_lfs` and a checkout that configures the LFS filter (`git_lfs_not_enabled`). `preparePrivateTransition` (page-prepare.ts) is that removal for other writers (GBRA-60, 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).- `src/core/persistence/checkout-state.ts` (`readCheckoutState`) — Q1: a canonical checkout against its last fetched upstream, read-only and time-bounded (no fetch): ahead/behind, `diverged`, each commit the upstream lacks (sha, author, date, subject, paths; at most 20) and porcelain counts. `sources writer status` reports it as `checkouts`; doctor `git_convergence` adds the commits and counts for a managed checkout and warns at once on a diverged one.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex bf31affa61..36151f5563 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 the checkout's ownership or set of sources changed, between the precheck and the merge. Nothing was merged and the fence was lifted. | 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. 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, it asks the user first: `--resume` there names `--abandon`, which would let the next sync roll that member's pages back, and resetting to the upstream commit then `--resume` finishes the refresh instead. |+| <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. 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 neither the start commit nor empty), `--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`, `consent: ["destructive"]`) previews with `git -C <checkout> status --short`, resets the checkout to the upstream commit, then runs `--resume`. || <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 journaled. `detail` is `retry_after_ms=1000`. 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`. | 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.diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.tsindex 9079b11747..9bc74e6aa8 100644--- a/src/core/persistence/worktree-refresh.ts+++ b/src/core/persistence/worktree-refresh.ts@@ -100,6 +100,29 @@ function refusal(name: CatalogueName, cause: string, fix: string, refreshId?: stif (refreshId) error.detail = `refresh_id=${refreshId}`;return error;}+/**+ * GST-1457: members whose last_commit moved off the refresh's start commit (null means never synced). 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.+ */+async function membersPastStart(engine: BrainEngine, row: Pick<WorktreeRefreshRow, 'source_ids' | 'old_head'>): Promise<string[]> {+ return (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.last_commit !== null && member.last_commit !== row.old_head).map(member => member.id);+}+const keepSyncedWayOut = (row: Pick<WorktreeRefreshRow, 'source_ids' | 'target_head'>, root: string) =>+ `Ask the user before resetting the checkout (destructive; git -C ${q(root)} status --short lists the uncommitted changes it discards): git -C ${q(root)} reset --hard ${row.target_head} then gbrain sources refresh ${row.source_ids[0]} --resume finishes the refresh and keeps the pages its members synced.`;+/** GST-1457: the refusal when a member synced past old_head; its fix is the reset to the target (ask_user, preview first), then --resume. */+function membersSyncedRefusal(row: WorktreeRefreshRow, root: string, cause: string): OperationError {+ const source = row.source_ids[0];+ const error = refusal('refresh_recovery_required', cause, keepSyncedWayOut(row, root), row.id);+ error.fix = { ask_user: true, argv: ['git', '-C', root, 'reset', '--hard', row.target_head], preview_argv: ['git', '-C', root, 'status', '--short'],+ consent: ['destructive'], actor: 'agent', requires_exclusive: false,+ why: `Moves the checkout to the refresh target ${row.target_head}, which its members already synced, discarding any uncommitted changes the preview lists; 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 a member had already synced the upstream commit ${row.target_head}. Abandoning it would let the next sync delete the pages that member synced. To keep them, reset the checkout to ${row.target_head} (this discards the uncommitted changes git status --short lists there) and then run gbrain sources refresh ${source} --resume. Reset now?`,+ 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 the target, records the merge and runs the member syncs, so refresh ${row.id} completes.` } };+ return error;+}/*** GBRA-133: the owner check reads this process's host identity without minting one (a cron job with another HOME would* otherwise become a new host silently), and its refusal names the identity file it read and the HOME it resolved from.@@ -218,9 +241,11 @@ async function abort(engine: BrainEngine, row: WorktreeRefreshRow, from: Worktre}async function markRecoveryRequired(engine: BrainEngine, row: WorktreeRefreshRow, head: string | null, root: string): Promise<OperationError> {const source = row.source_ids[0];+ const moved = await membersPastStart(engine, row);const error = refusal('refresh_recovery_required',- `The checkout HEAD (${head ?? 'unreadable'}) is neither the pre-refresh commit ${row.old_head} nor the verified upstream commit ${row.target_head}; writes to this worktree stay fenced.`,- `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.`,+ `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)}`+ : `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',{ ...refusalOutcome(error), observed_head: head }));@@ -982,6 +1007,8 @@ async function resumeOrAbandon(engine: BrainEngine, sourceId: string, opts: Refr`gbrain sources refresh ${sourceId} --resume`, row.id);throw await markRecoveryRequired(engine, row, head, root);}+ const moved = row.state === 'recovery_required' ? await membersPastStart(engine, row) : [];+ if (moved.length) throw membersSyncedRefusal(row, root, `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,@@ -1000,8 +1027,12 @@ async function resumeHeld(engine: BrainEngine, git: Git, sourceId: string, refreawait 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) 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' && head === row.old_head) {+ const moved = await membersPastStart(engine, row);+ if (moved.length) throw membersSyncedRefusal(row, root, `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',+ `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') {const stored = (row.outcome.refusal ?? {}) as { cause?: string; fix?: string };throw refusal('refresh_recovery_required', stored.cause ?? 'The refresh could not verify the checkout HEAD.',@@ -1101,12 +1132,11 @@ export async function refreshHolderReport(engine: BrainEngine, row: Pick<Worktreif (row.state === 'recovery_required') {if (head === 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 membersAtOld = head === row.old_head && (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id = ANY($1::text[])', [row.source_ids]))- .every(member => member.last_commit === null || member.last_commit === row.old_head);+ const membersAtOld = head === row.old_head && (await membersPastStart(engine, row)).length === 0;if (membersAtOld) 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,- why: `Refresh ${row.id} stopped with the checkout back at the pre-refresh commit ${row.old_head}, but a member source already synced past it. --resume refuses here and names --abandon, which would let the next sync roll that member's pages back, so ask the user first; resetting the checkout to the refresh target ${row.target_head} and running --resume finishes the refresh instead.` } };+ why: `Refresh ${row.id} stopped with the checkout back at the pre-refresh commit ${row.old_head}, but a member source already synced past it, so --abandon refuses (the next sync would roll that member's pages back). --resume refuses too and names the one way out that keeps those pages: reset the checkout to the refresh target ${row.target_head} (destructive, so ask the user first), then --resume.` } };return { ...base, auto_recovery: 'none', fix: { argv: resume, consent: [], actor: 'agent', requires_exclusive: false, verify,why: `Refresh ${row.id} could not verify the checkout HEAD, so nothing recovers it on its own. --resume changes nothing here: it prints the two ways out (reset to the start commit and --abandon, or to the upstream commit and --resume); resetting is destructive, so ask the user first.` } };}diff --git a/test/persistence-worktree-refresh.test.ts b/test/persistence-worktree-refresh.test.tsindex 1c7d4df5a1..d0368ed954 100644--- a/test/persistence-worktree-refresh.test.ts+++ b/test/persistence-worktree-refresh.test.ts@@ -692,6 +692,75 @@ test('7q. writer status for a recovery_required refresh whose members already syexpect(status.fix.why).toContain('ask the user first');}), 180_000);+/** The live (not soft-deleted) slugs of a member source. */+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 settle = (promise: Promise<unknown>) => promise.then(value => ({ value, error: null }), error => ({ value: null, error: error as { code?: string; suggestion?: string; message?: string; fix?: Record<string, any> } }));++test('7r. GST-1457: a recovery_required refresh whose member synced to the target, with HEAD back at the start commit, never lets --abandon and the next sync soft-delete those pages', () => each(async f => {+ // Value: protects=the pages a member already synced to target_head survive the manual path out of recovery_required: --resume no longer+ // names --abandon, --abandon refuses (ask_user: reset to the target, then --resume), and the next sync stays fenced; fails_when=--abandon+ // aborts a recovery_required row whatever its members' last_commit, so the next sync diffs target_head back to old_head and soft-deletes+ // the synced pages (the chain the #8344 fix-check reproduced); why_new=7q covers writer status only; seam=a crash at the syncing boundary,+ // the member synced by the real managed sync, HEAD reset by hand; no_claim=other HEADs (test 7) and the owner scan (7i).+ const target = f.push('alpha/two.md', page('Alpha two', 'Synced to the target before recovery.'));+ const old = f.head();+ const orphan = await orphanAt(f, 'syncing', 'syncing');+ expect(f.head()).toBe(target);+ await performManagedSync(f.engine, { sourceId: f.alpha, noPull: true, noEmbed: true });+ expect(await f.lastCommit(f.alpha)).toBe(target);+ const synced = await livePages(f, f.alpha);+ expect(synced.some(slug => slug.endsWith('two'))).toBe(true);+ git(f.root, 'reset', '-q', '--hard', old);+ const resume = await settle(refreshWorktree(f.engine, f.alpha, { resume: true }));+ const abandon = await settle(refreshWorktree(f.engine, f.alpha, { abandon: true }));+ const sync = await settle(performManagedSync(f.engine, { sourceId: f.alpha, noPull: true, noEmbed: true }));+ expect(await livePages(f, f.alpha)).toEqual(synced);+ expect(await f.lastCommit(f.alpha)).toBe(target);+ expect((await f.refreshRows()).map(r => r.state)).toEqual(['recovery_required']);+ expect(resume.error?.code).toBe('refresh_recovery_required');+ expect(resume.error!.suggestion).not.toContain('--abandon');+ expect(resume.error!.suggestion).toContain(`reset --hard ${target}`);+ expect(abandon.error?.code).toBe('refresh_recovery_required');+ expect(abandon.error!.message).toContain(f.alpha);+ expect(abandon.error!.suggestion).toContain(`reset --hard ${target}`);+ expect(abandon.error!.suggestion).not.toContain(`reset --hard ${old}`);+ for (const refusal of [resume.error!, abandon.error!]) {+ expect(refusal.fix).toMatchObject({ ask_user: true, consent: ['destructive'], argv: ['git', '-C', f.root, 'reset', '--hard', target],+ preview_argv: ['git', '-C', f.root, 'status', '--short'], then: { argv: ['gbrain', 'sources', 'refresh', f.alpha, '--resume'] } });+ expect(refusal.fix!.user_message).toContain(f.alpha);+ }+ expect(sync.error?.code).toBe('refresh_recovery_required');+ // The stored fix the plain refresh and writes repeat names only the safe way out too.+ const plain = await refusedWith(refreshWorktree(f.engine, f.alpha), 'refresh_recovery_required');+ expect(plain.suggestion).not.toContain('--abandon');+ // The safe way out: reset to the target, --resume finishes the refresh, and the synced pages stay.+ git(f.root, 'reset', '-q', '--hard', target);+ expect(await refreshWorktree(f.engine, f.alpha, { resume: true })).toMatchObject({ refresh_id: orphan.id, status: 'completed' });+ await performManagedSync(f.engine, { sourceId: f.alpha, noPull: true, noEmbed: true });+ expect(await livePages(f, f.alpha)).toEqual(synced);+}), 180_000);++test('7s. GST-1457: with no member synced past the start commit, --resume still names --abandon and --abandon still lifts the fence', () => each(async f => {+ // Value: protects=the 7r refusal is scoped to rows whose members moved: a recovery_required row whose members all still sit at old_head is+ // abandoned as before, and the next sync loses nothing; fails_when=--abandon refuses every recovery_required row, or the member check reads+ // the wrong commit; why_new=7p abandons a row that was never syncing; seam=a crash at the syncing boundary before any member synced;+ // no_claim=members with no last_commit (the same branch of the check).+ f.push('alpha/two.md', page('Alpha two', 'Never synced.'));+ const old = f.head();+ await orphanAt(f, 'syncing', 'syncing');+ expect(await f.lastCommit(f.alpha)).toBe(old);+ expect(await f.lastCommit(f.beta)).toBe(old);+ const before = await livePages(f, f.alpha);+ git(f.root, 'reset', '-q', '--hard', old);+ const resume = await refusedWith(refreshWorktree(f.engine, f.alpha, { resume: true }), 'refresh_recovery_required');+ expect(resume.suggestion).toBe(`gbrain sources refresh ${f.alpha} --abandon`);+ expect((await refreshWorktree(f.engine, f.alpha, { abandon: true })).status).toBe('abandoned');+ expect((await f.refreshRows()).map(r => r.state)).toEqual(['aborted']);+ await performManagedSync(f.engine, { sourceId: f.alpha, noPull: true, noEmbed: true });+ expect(await livePages(f, f.alpha)).toEqual(before);+}), 180_000);+test('8. a queued git effect drains before fenced, and nothing on the worktree is claimed while fenced', () => each(async f => {f.push('alpha/two.md', page('Alpha two', 'Upstream.'));await f.put(f.beta, 'notes/effect', page('Effect', 'Has a git effect.'));