Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence): worktree-wide coordinated ff-only refresh (F0 state machine, admission fence, claim predicates, restart recovery)

garrytand4d112f22df0
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 5185f14ba3..a903ebb203 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -65,7 +65,7 @@ of making a duplicate.
| unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. |
| <a id="colon_slug_windows_write_through"></a>`colon_slug_windows_write_through` | `colon_slug_windows_write_through` | A page slug such as `calendar:abc` is valid, but its canonical file name would contain `:`, which Windows cannot store (it names an alternate data stream). On Windows, a write that would publish that file is refused before admission, and `gbrain sync` skips each such file with this reason instead of failing the run. Database-only writes of the same slug (no repo configured, `sync.write_through` off, an unbound source, or a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) source and pages created while it was one) still succeed, and macOS and Linux are unchanged. | Use a slug without `:` (the suggestion names one), or write the page from a macOS or Linux host that owns the source. For a skipped sync file, rename it without `:` on a macOS or Linux checkout, commit, then run `gbrain sync --source <source> --no-pull` on the Windows host. |
| <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. |
-| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | For a source whose remote is authoritative (it never receives brain writes you need as files), make it a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) once, then advance it and sync without pulling: `gbrain sources mirror-readonly <source> && git -C <checkout> pull --ff-only && gbrain sync --source <source> --no-pull`. The printed `fix` fills in the real source and checkout. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. A coordinated in-gbrain fast-forward refresh is planned; until then this is the supported sequence. |
+| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | `gbrain sources refresh <source>` (the printed `fix` fills in the source). It drains writes to the source's checkout, fast-forwards it to its upstream and runs the managed sync for every source bound to that checkout; see [worktree refresh refusals](#worktree-refresh-refusals) for what it can refuse. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. |
| <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). |
| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |
@@ -109,6 +109,42 @@ when lifetime request IDs or receipt bytes reach 80% of a limit, with the
`gbrain config set` value to use; outstanding-request, queued-byte and
recovery-byte limits can refuse writes without that warning.
+## Worktree refresh refusals
+
+`gbrain sources refresh <source>` is the one supported way to move a managed
+checkout to new upstream commits. It runs on the source's registered owner
+host, fetches, then refuses new writes to every source that shares the
+checkout while queued writes finish, fast-forwards with `git merge --ff-only`
+and syncs each of those sources with `--no-pull`. Each refusal below prints
+`code`, a one-line `cause`, a literal `fix` with the real source filled in and
+this anchor (`--json` puts them in one object on stdout); the command exits 1.
+
+**Say to your agent:** *"Pull the latest commits into my notes source."* or
+*"The refresh was refused. What do I need to do?"*
+
+| Reason | Error code | What it means | Recovery |
+| --- | --- | --- | --- |
+| <a id="refresh_not_managed"></a>`refresh_not_managed` | `refresh_not_managed` | The brain is not managed, or the source has no claimed checkout. Plain sync already pulls such a source, so there is nothing to coordinate. | `gbrain sync --source <source>`. |
+| <a id="refresh_not_owner"></a>`refresh_not_owner` | `refresh_not_owner` | This host is not the source's registered owner, and only the owner may move its checkout. | Run `gbrain sources refresh <source>` on the owner host; `gbrain sources writer status <source>` names it. |
+| <a id="refresh_no_upstream"></a>`refresh_no_upstream` | `refresh_no_upstream` | The checkout's branch tracks no upstream (or HEAD is detached), so there is nothing to fast-forward to. | `git -C <checkout> branch --set-upstream-to <remote>/<branch>` (the fix fills in the real values), then retry. |
+| <a id="fetch_failed"></a>`fetch_failed` | `fetch_failed` | `git fetch` failed or did not finish within `sources.refresh_fetch_timeout_ms` (default 120000; `GBRAIN_REFRESH_FETCH_TIMEOUT_MS`; `--fetch-timeout-ms` wins over both). Nothing changed and no refresh record was written. | Retry. For a slow remote, raise the bound with `--fetch-timeout-ms <ms>` or `gbrain config set sources.refresh_fetch_timeout_ms <ms>`. Credentials are the user's: ask them to fix authentication rather than changing the remote. |
+| <a id="refresh_diverged"></a>`refresh_diverged` | `refresh_diverged` | The checkout has commits its upstream lacks, so a fast-forward is impossible. Nothing changed. | Reconcile the histories and push from a clone that is not managed, then retry. `gbrain sources reclone <source>` replaces the checkout; ask the user first, because local commits are dropped. |
+| <a id="refresh_dirty"></a>`refresh_dirty` | `refresh_dirty` | Uncommitted or untracked files overlap the incoming upstream changes (the first 20 are named), or `git merge --ff-only` refused for the same reason. HEAD did not move. Uncommitted files outside the incoming changes do not refuse; they are kept and listed as `preserved_uncommitted`. | Commit or discard the named paths, then retry. Check `gbrain sources writer status <source> --json` first: a pending Git effect may be about to commit a gbrain-published file. |
+| <a id="sync_in_progress"></a>`sync_in_progress` | `sync_in_progress` | A managed sync of one of the checkout's sources has an unfinished cursor. Moving the checkout now would strand it, and the refresh never waits on a sync. | Run the printed `gbrain sync --source <source> --no-pull ...` resume command (it keeps the cursor's options), then retry. |
+| <a id="refresh_in_progress"></a>`refresh_in_progress` | `refresh_in_progress` | Another refresh of the same checkout is active, or a command that changes which sources share the checkout (`sources add`, `remove`, `archive`, `restore`, `reclone`) ran while one was active. | `gbrain sources refresh <source> --resume`, then retry the source command with the same request ID. |
+| <a id="refresh_drain_timeout"></a>`refresh_drain_timeout` | `refresh_drain_timeout` | Queued writes or Git effects on the checkout did not finish within `--wait-drain` (default 60 s; `sources.refresh_drain_wait_ms`; `GBRAIN_REFRESH_DRAIN_WAIT_MS`). The counts are in the message. The fence was lifted and HEAD did not move. | Retry, or wait longer with `--wait-drain <seconds>`. Inspect what is queued 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. |
+| <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. | Retry the same request ID after about a second. `gbrain sources writer status <source>` 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.
+When the owner restarts it finishes the deterministic steps on its own: an
+interrupted drain or a fence with HEAD unchanged is abandoned, and a merge
+that already reached the verified upstream commit moves on to syncing.
+`gbrain sources refresh <source> --resume` runs the remaining syncs. Doctor
+reports `worktree_refresh_stuck` for a refresh active longer than 15 minutes,
+with the resume command.
+
## Unbound sources on Postgres
A source with a checkout path (`local_path`, or `sync.repo_path` for the
diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.ts
index 1792302381..1bbde5ae97 100644
--- a/src/core/error-catalogue.ts
+++ b/src/core/error-catalogue.ts
@@ -42,6 +42,19 @@ export const ERROR_CATALOGUE = {
source_checkout_missing: { code: 'recovery_required', docs: 'docs/guides/write-refusals.md#source_checkout_missing' },
managed_pull_skipped: { code: 'managed_pull_skipped', docs: 'docs/guides/write-refusals.md#managed_pull_skipped' },
no_pricing: { code: 'no_pricing', docs: 'docs/guides/write-refusals.md#no_pricing' },
+ // F0 `gbrain sources refresh` (worktree-wide coordinated ff-only refresh).
+ refresh_not_managed: { code: 'refresh_not_managed', docs: 'docs/guides/write-refusals.md#refresh_not_managed' },
+ refresh_not_owner: { code: 'refresh_not_owner', docs: 'docs/guides/write-refusals.md#refresh_not_owner' },
+ refresh_no_upstream: { code: 'refresh_no_upstream', docs: 'docs/guides/write-refusals.md#refresh_no_upstream' },
+ fetch_failed: { code: 'fetch_failed', docs: 'docs/guides/write-refusals.md#fetch_failed' },
+ refresh_diverged: { code: 'refresh_diverged', docs: 'docs/guides/write-refusals.md#refresh_diverged' },
+ refresh_dirty: { code: 'refresh_dirty', docs: 'docs/guides/write-refusals.md#refresh_dirty' },
+ sync_in_progress: { code: 'sync_in_progress', docs: 'docs/guides/write-refusals.md#sync_in_progress' },
+ refresh_in_progress: { code: 'refresh_in_progress', docs: 'docs/guides/write-refusals.md#refresh_in_progress' },
+ refresh_drain_timeout: { code: 'refresh_drain_timeout', docs: 'docs/guides/write-refusals.md#refresh_drain_timeout' },
+ refresh_source_changed: { code: 'refresh_source_changed', docs: 'docs/guides/write-refusals.md#refresh_source_changed' },
+ refresh_recovery_required: { code: 'refresh_recovery_required', docs: 'docs/guides/write-refusals.md#refresh_recovery_required' },
+ worktree_refreshing: { code: 'worktree_refreshing', docs: 'docs/guides/write-refusals.md#worktree_refreshing' },
} as const satisfies Record<string, CatalogueEntry>;
export type CatalogueName = keyof typeof ERROR_CATALOGUE;
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index f8417fc415..ff26878199 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -10,6 +10,7 @@ import type { SqlEngine } from './model.ts';
import { isFactsExtractionEnabled } from '../facts/extract.ts';
import { resolveDefaultVisibility } from '../facts/visibility.ts';
import { declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
+import { refreshFenceClear } from './worktree-refresh-schema.ts';
/** `snapshot` is the publication's final read of the page, including deleted rows, in this transaction. */
export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequest, snapshot: PageSnapshot | null,
@@ -40,14 +41,14 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
}
}
-/** Claims release their database connection before waiting for a filesystem lock/provider. */
+/** Claims release their database connection before waiting for a filesystem lock/provider. Nothing on a refresh-fenced worktree is claimed. */
export async function claimPersistenceEffect(engine: BrainEngine, hostId: string): Promise<PersistenceEffect | null> {
return engine.transactionDirect(async tx => {
await declarePersistenceProtocol(tx);
const [candidate] = await tx.executeRaw<PersistenceEffect>(`SELECT e.* FROM persistence_effects e
LEFT JOIN persistence_worktrees w ON w.id=e.worktree_id
WHERE (e.state='queued' OR e.state='running' AND e.claim_expires_at<now()) AND e.next_attempt_at<=now()
- AND (e.worktree_id IS NULL OR w.owner_host_id=$1::uuid)
+ AND (e.worktree_id IS NULL OR w.owner_host_id=$1::uuid) AND (e.worktree_id IS NULL OR ${refreshFenceClear('e')})
AND e.recovery IS NULL AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked
WHERE blocked.worktree_id=e.worktree_id AND blocked.recovery IS NOT NULL)
AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked
@@ -82,6 +83,7 @@ export async function claimCoalescedGitEffects(engine: BrainEngine, hostId: stri
WHERE e.worktree_id=$2::uuid AND e.kind='git' AND e.data ? 'relative_path'
AND NOT (e.data ? 'targets') AND NOT (e.data ? 'source_scan') AND NOT (e.data ? 'version')
AND (e.state='queued' OR e.state='running' AND e.claim_expires_at<now()) AND e.next_attempt_at<=now()
+ AND ${refreshFenceClear('e')}
AND e.recovery IS NULL AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked
WHERE blocked.worktree_id=e.worktree_id AND blocked.recovery IS NOT NULL)
AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 456d98a88f..c004a5d153 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -8,6 +8,8 @@ import { journalLimitKey, oneYearCapacity, readJournalLimits, readReceiptRetenti
import { retryWriteAdmission } from './admission-retry.ts';
import { writeHealth, type WriteHealthFacts } from './health.ts';
import { writerStamp } from './writer-versions.ts';
+import { catalogueError } from '../error-catalogue.ts';
+import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh-schema.ts';
import { assertMutationProtocol, assertSharedSkillPersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import {
isTerminal, principalKey, requestPrincipal, recoveryFiles,
@@ -130,6 +132,7 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over
assertMutationProtocol({ target_kind: input.targetKind, protocol_version: input.protocolVersion });
if (input.worktreeId) {
await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [input.worktreeId]);
+ await assertWorktreeNotRefreshing(tx, input);
const binding = await tx.executeRaw(`SELECT source_id FROM persistence_source_bindings WHERE source_id=$1
AND source_incarnation=$2::uuid AND worktree_id=$3::uuid AND topology_generation=$4`,
[input.sourceId, input.sourceIncarnation, input.worktreeId, input.topologyGeneration]);
@@ -182,14 +185,46 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over
} };
}
+/**
+ * F0: a write to a worktree under an active `gbrain sources refresh` is refused
+ * before it is journaled. The fence insert holds the worktree row FOR UPDATE
+ * and admission holds it FOR SHARE, so an admission either commits before the
+ * fence (and is drained) or sees it. During `syncing` only the managed sync's
+ * own writes are admitted; a `syncing` refresh whose members all reached the
+ * target is completed here, so a later cycle sync converges a crashed refresh.
+ */
+async function assertWorktreeNotRefreshing(tx: BrainEngine, input: WriteAdmission): Promise<void> {
+ const [refresh] = await tx.executeRaw<{ id: string; state: string; source_ids: string[] }>(`SELECT id,state,source_ids FROM persistence_worktree_refreshes
+ WHERE worktree_id=$1::uuid AND state IN ${ACTIVE_REFRESH_STATES_SQL}`, [input.worktreeId]);
+ if (!refresh) return;
+ const managedSync = input.operation === 'submit_job' && String(input.intent.kind ?? '').startsWith('managed_sync_');
+ if (refresh.state === 'syncing' && managedSync) return;
+ if (refresh.state === 'syncing') {
+ const completed = await tx.executeRaw(`UPDATE persistence_worktree_refreshes f SET state='completed',completed_at=now(),updated_at=now()
+ WHERE f.id=$1::uuid AND f.state='syncing' AND NOT EXISTS (SELECT 1 FROM sources s WHERE s.id=ANY(f.source_ids)
+ AND s.last_commit IS DISTINCT FROM f.target_head) RETURNING f.id`, [refresh.id]);
+ if (completed.length) return;
+ }
+ if (refresh.state === 'recovery_required') throw catalogueError('refresh_recovery_required',
+ `Refresh ${refresh.id} could not verify the checkout HEAD of source ${input.sourceId}; writes to its worktree stay fenced.`,
+ `gbrain sources writer status ${input.sourceId}, then gbrain sources refresh ${input.sourceId} --resume. Retry the same request_id afterwards.`);
+ const error = catalogueError('worktree_refreshing',
+ `Source ${input.sourceId}'s checkout is being fast-forwarded by refresh ${refresh.id} (${refresh.state}); this write was not journaled.`,
+ `Retry the same request_id after retry_after_ms: 1000. Check progress with gbrain sources writer status ${input.sourceId}.`);
+ error.detail = 'retry_after_ms=1000';
+ throw error;
+}
+
/**
* The rows `claimNextWrite` may claim, over `persistence_requests r LEFT JOIN
* persistence_worktrees w`, with $1 = host id and $2 = excluded root keys. An
- * unresolved head blocks its entire root. A file write also waits for an
+ * unresolved head blocks its entire root. A worktree under a refresh fence
+ * (`fenced`, `merged`, `recovery_required`) claims nothing. A file write also waits for an
* unfinished withdrawal mirror of its page (of every page, for an untargeted
* mirror), so the mirror never rewrites a file under an accepted request.
*/
export const CLAIMABLE_WRITE_SQL = `r.state='queued' AND (r.worktree_id IS NULL OR (w.owner_host_id=$1::uuid AND w.state='active'))
+ AND (r.worktree_id IS NULL OR ${refreshFenceClear('r')})
AND NOT (COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)=ANY($2::text[]))
AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)
AND NOT EXISTS (SELECT 1 FROM persistence_effects mirror WHERE mirror.worktree_id=r.worktree_id
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 2533d32eb0..dc35b3294b 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -25,6 +25,7 @@ import { extractManagedStaleLinks } from './links-maintenance.ts';
import { CHECKPOINT_VALIDATION_TIMEOUT, checkpointTimeoutHint } from './checkpoint-validation.ts';
import { isTerminalWriteState, publicWriteReceipt, type WriteReceipt } from './types.ts';
import type { WriteRequest } from './model.ts';
+import { assertManagedSyncAllowed } from './worktree-refresh.ts';
export interface ManagedSyncWriteDiagnostic {
source_id: string;
@@ -257,6 +258,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
assertPersistenceAccepting(engine);
validateManagedSyncOptions(opts);
const context = await resolveManagedSyncContext(engine, opts);
+ if (!opts.dryRun) await assertManagedSyncAllowed(engine, context.binding.worktree_id, context.sourceId);
const authority = await managedSyncAuthority(engine, context.sourceId, context.incarnation, opts.repoPath ?? context.root);
const company = currentCompanyBrainSync(context.sourceId);
const processingOptions = syncProcessingOptions(opts);
@@ -512,7 +514,8 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
}
if (!opts.dryRun) {
const code = error instanceof OperationError ? error.code : 'storage_error';
- if (code !== 'permission_denied') {
+ // A refresh fence is transient admission back-pressure, not a sync failure to record.
+ if (!['permission_denied', 'worktree_refreshing', 'refresh_recovery_required'].includes(code)) {
const [stored] = cursor ? [] : await engine.executeRaw<{ completed_keys: [CursorHeader] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [OP, key]);
const failedCursor = cursor ?? stored?.completed_keys?.[0];
const { failure } = await recordManagedSyncFailure(engine, { source_id: context.sourceId, source_incarnation: context.incarnation, path: cursor?.entries[cursor.index]?.path ?? failedCursor?.pending?.intent.path ?? `<${phase}>`, code,
diff --git a/src/core/persistence/topology-locks.ts b/src/core/persistence/topology-locks.ts
index b748174dd4..d4cafcb9b0 100644
--- a/src/core/persistence/topology-locks.ts
+++ b/src/core/persistence/topology-locks.ts
@@ -8,6 +8,8 @@ import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from '
import { containsPath, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
import { completeWrite, lockCounters } from './journal.ts';
import { principalKey, requestPrincipal, type WriteRequest } from './model.ts';
+import { catalogueError } from '../error-catalogue.ts';
+import { ACTIVE_REFRESH_STATES_SQL } from './worktree-refresh-schema.ts';
export type TopologyBinding=WorktreeBinding & { unbound?:boolean };
@@ -55,8 +57,12 @@ export async function withTopologyLocks<T>(engine: BrainEngine, sourceId: string
} finally { for (const handle of handles.reverse()) await handle.release(); }
}
-/** Keep the complete affected membership locked, including absent target keys. */
-export async function lockTopologyRows(tx: BrainEngine, sourceId: string, bindings: TopologyBinding[]): Promise<string[]> {
+/**
+ * Keep the complete affected membership locked, including absent target keys.
+ * An active `gbrain sources refresh` on an affected worktree refuses with
+ * `refresh_in_progress`, except for the refresh named by `refreshId` itself.
+ */
+export async function lockTopologyRows(tx: BrainEngine, sourceId: string, bindings: TopologyBinding[], refreshId?: string): Promise<string[]> {
await tx.executeRaw('SELECT singleton FROM persistence_brain WHERE singleton=1 FOR UPDATE');
const ids = bindings.map(b => b.worktree_id).sort();
const owners = await tx.executeRaw<{ id: string; owner_host_id: string; state: string; owner_epoch:string;topology_generation:string }>(
@@ -64,6 +70,11 @@ export async function lockTopologyRows(tx: BrainEngine, sourceId: string, bindin
if (owners.length !== ids.length || owners.some(row => row.owner_host_id !== localHostId() || row.state !== 'active')) {
throw new OperationError('recovery_required', 'The affected worktree is draining, recovering, or changed ownership.');
}
+ const [refresh] = await tx.executeRaw<{ id: string; state: string; source_ids: string[] }>(`SELECT id,state,source_ids FROM persistence_worktree_refreshes
+ WHERE worktree_id=ANY($1::uuid[]) AND state IN ${ACTIVE_REFRESH_STATES_SQL} AND ($2::uuid IS NULL OR id<>$2::uuid) LIMIT 1`, [ids, refreshId ?? null]);
+ if (refresh) throw catalogueError('refresh_in_progress',
+ `Refresh ${refresh.id} of the worktree holding source ${refresh.source_ids[0]} is ${refresh.state}; source topology cannot change until it finishes.`,
+ `gbrain sources refresh ${refresh.source_ids[0]} --resume, then retry this source command with the same request_id.`);
const members = await tx.executeRaw<{ source_id: string }>('SELECT source_id FROM persistence_source_bindings WHERE worktree_id=ANY($1::uuid[]) ORDER BY source_id', [ids]);
const sources = [...new Set([sourceId,...members.map(row => row.source_id)])].sort();
await tx.executeRaw('SELECT id FROM sources WHERE id=ANY($1::text[]) ORDER BY id FOR UPDATE', [sources]);
diff --git a/src/core/persistence/topology-recovery.ts b/src/core/persistence/topology-recovery.ts
index f9a17ed68f..cc8ddebddd 100644
--- a/src/core/persistence/topology-recovery.ts
+++ b/src/core/persistence/topology-recovery.ts
@@ -16,6 +16,7 @@ import type { CloneLifecycleHooks } from './topology-clone.ts';
import { flushTopologyDirectory, topologyDirectoryIdentity } from './topology-filesystem.ts';
import { assertPhysicalRoot } from './physical-root.ts';
import { assertPhysicalRootStamp, readPhysicalRootReservation } from './physical-root-record.ts';
+import { resumeWorktreeRefreshes } from './worktree-refresh.ts';
async function readChange(engine:BrainEngine,id:string):Promise<TopologyChange>{
const [row]=await engine.executeRaw<TopologyChange>('SELECT * FROM persistence_topology_changes WHERE id=$1::uuid',[id]);
@@ -178,9 +179,14 @@ export async function finishTopologyClone(engine:BrainEngine,id:string,hooks:Clo
}
const recoveryCursors=new WeakMap<BrainEngine,string>();
-/** A bounded rotating scan keeps persistent conflicts from starving other roots. */
+/**
+ * A bounded rotating scan keeps persistent conflicts from starving other roots.
+ * It first converges interrupted worktree refreshes (F0, section 1.5) whose
+ * refreshing process has exited; a live refresh holds its lock and is skipped.
+ */
export async function recoverSourceTopologies(engine:BrainEngine,opts:{hostId?:string;limit?:number;onAttempt?:(id:string,recovered:boolean)=>void}={}):Promise<number>{
const host=opts.hostId??localHostId(),limit=Math.max(1,Math.min(16,opts.limit??2));
+ await resumeWorktreeRefreshes(engine,{hostId:host});
const scan=async(after:string|null)=>engine.executeRaw<TopologyChange>(`SELECT c.* FROM persistence_topology_changes c
JOIN persistence_worktrees w ON w.id=(c.recovery->>'worktreeId')::uuid
WHERE c.recovery IS NOT NULL AND w.owner_host_id=$1::uuid AND ($2::uuid IS NULL OR c.id>$2::uuid)
diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.ts
new file mode 100644
index 0000000000..1292bcac47
--- /dev/null
+++ b/src/core/persistence/worktree-refresh.ts
@@ -0,0 +1,566 @@
+/**
+ * F0 `gbrain sources refresh`: the one sanctioned Git writer for a managed
+ * checkout. A worktree-wide, drained, fast-forward-only refresh with a
+ * durable checkpoint (`persistence_worktree_refreshes`):
+ *
+ * precheck (no DB state) -> draining -> fenced -> merged -> syncing -> completed
+ *
+ * `draining` refuses new checkout writes for every member source at admission
+ * while queued work drains; `fenced` (worktree native lock held) stops claims
+ * and runs `git merge --ff-only`; `merged` writes the upstream observation;
+ * `syncing` runs the managed `--no-pull` sync per member and admits only those
+ * sync writes. A crash converges through `resumeWorktreeRefreshes`, which only
+ * adopts a HEAD it can verify. Git and network waits never run inside a
+ * database transaction; fetch also runs outside the native locks.
+ *
+ * A per-worktree refresh lock (`locks/refresh-<worktree>.lock`) is held by the
+ * refreshing process for its whole run, so recovery never touches the row of a
+ * live refresh: holding that native lock proves the previous process exited.
+ */
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import type { SyncResult } from '../../commands/sync.ts';
+import { execFileBounded } from '../brain-repo-durability.ts';
+import { loadConfig } from '../config.ts';
+import { catalogueError, type CatalogueName } from '../error-catalogue.ts';
+import { OperationError } from '../ops/contract.ts';
+import { recordUpstreamObservation } from '../sync-upstream.ts';
+import { checkpointRetryCommand } from './checkpoint-validation.ts';
+import { localHostId, persistenceHome } from './identity.ts';
+import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';
+import { getWorktreeBinding, managedPersistenceEnabled, type WorktreeBinding } from './ownership.ts';
+import { isPhysicalRootMetadata } from './physical-root-record.ts';
+import { startPersistenceConsumer } from './service.ts';
+import { lockTopologyPrincipal, lockTopologyRows, topologyPrincipal, withTopologyLocks } from './topology-locks.ts';
+import { ACTIVE_REFRESH_STATES_SQL, CHECKOUT_EFFECT_KINDS_SQL, type WorktreeRefreshState } from './worktree-refresh-schema.ts';
+
+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;
+}
+export type RefreshBoundary = 'drained' | 'fenced' | 'merged';
+export interface RefreshHooks { boundary?: (point: RefreshBoundary, row: WorktreeRefreshRow) => Promise<void> | void }
+export interface RefreshOptions {
+ dryRun?: boolean; resume?: boolean; abandon?: boolean;
+ /** Flag value; falls back to GBRAIN_REFRESH_DRAIN_WAIT_MS, then `sources.refresh_drain_wait_ms`, then 60 s. */
+ waitDrainMs?: number;
+ /** Flag value; falls back to GBRAIN_REFRESH_FETCH_TIMEOUT_MS, then `sources.refresh_fetch_timeout_ms`, then 120 s. */
+ fetchTimeoutMs?: number;
+ hooks?: RefreshHooks;
+}
+export interface RefreshMemberSync { source_id: string; status: string; last_commit: string | null }
+export interface RefreshSyncBlocked { source_id: string; code: string; message: string; resume: string }
+export interface WorktreeRefreshResult {
+ status: 'already_current' | 'completed' | 'sync_blocked' | 'dry_run' | 'syncing' | 'abandoned' | 'nothing_to_resume';
+ refresh_id: string | null; worktree_id: string; source_ids: string[]; old_head: string | null; target_head: string | null;
+ upstream_ref: string | null; preserved_uncommitted: string[]; incoming_files?: number;
+ synced: RefreshMemberSync[]; sync_blocked?: RefreshSyncBlocked[]; next?: string;
+}
+
+const DRAIN_POLL_MS = 250;
+const MAX_MEMBER_SYNC_PASSES = 20;
+const GIT_ENV = { GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never', LC_ALL: 'C', GIT_OPTIONAL_LOCKS: '0' };
+
+function refusal(name: CatalogueName, cause: string, fix: string, refreshId?: string): OperationError {
+ const error = catalogueError(name, cause, fix);
+ if (refreshId) error.detail = `refresh_id=${refreshId}`;
+ return error;
+}
+const q = (value: string) => /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
+
+/** Hardened git: no prompts, no user hooks, untranslated output, bounded. */
+async function withGit<T>(run: (git: (args: string[], timeoutMs?: number) => Promise<{ stdout: string; stderr: string; code: number; timedOut: boolean }>) => Promise<T>): Promise<T> {
+ const base = join(persistenceHome(), 'empty-hooks');
+ mkdirSync(base, { recursive: true, mode: 0o700 });
+ const hooks = mkdtempSync(join(base, 'refresh-'));
+ try {
+ return await run(async (args, timeoutMs = 30_000) => {
+ const { error, stdout, stderr } = await execFileBounded('git', ['-c', 'core.quotepath=false', '-c', `core.hooksPath=${hooks}`, ...args],
+ { timeout: timeoutMs, maxBuffer: 32 * 1024 ** 2, env: { ...process.env, ...GIT_ENV } });
+ const timedOut = !!error && (error.killed || typeof error.code !== 'number');
+ return { stdout, stderr, code: error ? (typeof error.code === 'number' ? error.code : -1) : 0, timedOut };
+ });
+ } finally { rmSync(hooks, { recursive: true, force: true }); }
+}
+type Git = Parameters<Parameters<typeof withGit>[0]>[0];
+
+async function revParse(git: Git, root: string, rev: string): Promise<string | null> {
+ const out = await git(['-C', root, 'rev-parse', '--verify', '-q', `${rev}^{commit}`]);
+ return out.code === 0 ? out.stdout.trim() : null;
+}
+async function isAncestor(git: Git, root: string, ancestor: string, descendant: string): Promise<boolean> {
+ return (await git(['-C', root, 'merge-base', '--is-ancestor', ancestor, descendant])).code === 0;
+}
+
+/** Uncommitted paths (ignored files excluded) split into those the incoming diff touches and the rest. */
+async function dirtyOverlap(git: Git, root: string, from: string, to: string): Promise<{ overlap: string[]; preserved: string[]; incoming: number }> {
+ const status = await git(['-C', root, 'status', '--porcelain=v1', '-z', '--untracked-files=normal']);
+ if (status.code !== 0) throw new OperationError('storage_error', `git status failed in ${root}: ${status.stderr.trim().split('\n')[0]}`);
+ const dirty: string[] = [];
+ const fields = status.stdout.split('\0');
+ for (let i = 0; i < fields.length; i++) {
+ const entry = fields[i];
+ if (entry.length < 4) continue;
+ dirty.push(entry.slice(3));
+ if (entry[0] === 'R' || entry[0] === 'C') dirty.push(fields[++i]);
+ }
+ const diff = await git(['-C', root, 'diff', '--name-only', '-z', '--no-renames', from, to]);
+ if (diff.code !== 0) throw new OperationError('storage_error', `git diff failed in ${root}: ${diff.stderr.trim().split('\n')[0]}`);
+ const incoming = diff.stdout.split('\0').filter(Boolean);
+ const touches = (path: string) => incoming.some(file => file === path || (path.endsWith('/') && file.startsWith(path)) || path.startsWith(`${file}/`));
+ const ours = (path: string) => isPhysicalRootMetadata(path.replace(/\/$/, '')) || path === '.gbrain-managed' || path.startsWith('.gbrain-managed/');
+ const unique = [...new Set(dirty)].filter(path => !ours(path)).sort();
+ return { overlap: unique.filter(touches), preserved: unique.filter(path => !touches(path)), incoming: incoming.length };
+}
+
+async function configuredMs(engine: BrainEngine, flag: number | undefined, env: string, key: string, fallback: number): Promise<number> {
+ const raw = flag ?? (process.env[env] !== undefined && process.env[env] !== '' ? Number(process.env[env]) : undefined) ?? await engine.getConfig(key).then(v => v == null ? undefined : Number(v));
+ if (raw === undefined) return fallback;
+ if (!Number.isFinite(raw) || raw < 0) throw new OperationError('invalid_params', `${key} (or ${env}) must be a whole number of milliseconds; got ${raw}.`,
+ `Run gbrain config set ${key} ${fallback} (or unset ${env}), then retry.`);
+ return Math.floor(raw);
+}
+
+function refreshLockPath(worktreeId: string): string { return join(persistenceHome(), 'locks', `refresh-${worktreeId}.lock`); }
+
+async function readActiveRefresh(engine: BrainEngine, worktreeId: string): Promise<WorktreeRefreshRow | null> {
+ const [row] = await engine.executeRaw<WorktreeRefreshRow>(`SELECT * FROM persistence_worktree_refreshes
+ WHERE worktree_id=$1::uuid AND state IN ${ACTIVE_REFRESH_STATES_SQL}`, [worktreeId]);
+ return row ?? null;
+}
+async function readRefresh(engine: BrainEngine, id: string): Promise<WorktreeRefreshRow> {
+ const [row] = await engine.executeRaw<WorktreeRefreshRow>('SELECT * FROM persistence_worktree_refreshes WHERE id=$1::uuid', [id]);
+ if (!row) throw new OperationError('not_found', 'The worktree refresh record disappeared.');
+ return row;
+}
+/** Conditional transition: returns false when another process already moved the row. */
+async function transition(tx: BrainEngine, row: WorktreeRefreshRow, from: WorktreeRefreshState[], to: WorktreeRefreshState, outcome: Record<string, unknown> = {}): Promise<boolean> {
+ const terminal = to === 'completed' || to === 'aborted';
+ const changed = await tx.executeRaw(`UPDATE persistence_worktree_refreshes SET state=$3,outcome=outcome||$4::text::jsonb,updated_at=now(),
+ completed_at=CASE WHEN $5::boolean THEN now() ELSE completed_at END WHERE id=$1::uuid AND state=ANY($2::text[]) RETURNING id`,
+ [row.id, from, to, JSON.stringify(outcome), terminal]);
+ return changed.length === 1;
+}
+function refusalOutcome(error: OperationError): Record<string, unknown> {
+ return { refusal: { code: error.code, cause: error.message, fix: error.suggestion, docs: error.docs } };
+}
+async function abort(engine: BrainEngine, row: WorktreeRefreshRow, from: WorktreeRefreshState[], error: OperationError, extra: Record<string, unknown> = {}): Promise<never> {
+ await engine.transaction(tx => transition(tx, row, from, 'aborted', { ...refusalOutcome(error), ...extra }));
+ error.detail = `refresh_id=${row.id}`;
+ throw error;
+}
+async function markRecoveryRequired(engine: BrainEngine, row: WorktreeRefreshRow, head: string | null, root: string): Promise<OperationError> {
+ const source = row.source_ids[0];
+ 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.`,
+ row.id);
+ await engine.transaction(tx => transition(tx, row, ['draining', 'fenced', 'merged', 'syncing', 'recovery_required'], 'recovery_required',
+ { ...refusalOutcome(error), observed_head: head }));
+ return error;
+}
+
+interface Plan {
+ binding: WorktreeBinding; root: string; members: string[]; upstreamRef: string; oldHead: string; targetHead: string;
+ overlap: string[]; preserved: string[]; incoming: number;
+}
+
+/** Steps 1.3/1: refusals before any database state; fetch moves only remote-tracking refs. */
+async function precheck(engine: BrainEngine, git: Git, sourceId: string, fetchTimeoutMs: number): Promise<Plan> {
+ if (!await managedPersistenceEnabled(engine)) throw refusal('refresh_not_managed',
+ 'This brain is not managed, so gbrain sync pulls the checkout itself; there is no worktree fence to coordinate.', `gbrain sync --source ${sourceId}`);
+ const binding = await getWorktreeBinding(engine, sourceId);
+ if (!binding) throw refusal('refresh_not_managed',
+ `Source ${sourceId} has no claimed canonical worktree, so gbrain sync pulls it without a refresh.`, `gbrain sync --source ${sourceId}`);
+ if (binding.owner_host_id !== localHostId() || !binding.local_path) throw refusal('refresh_not_owner',
+ `Only the registered owner host of source ${sourceId} may move its checkout; this host is not that owner.`,
+ `Run gbrain sources refresh ${sourceId} on the owner host; check which host owns it with gbrain sources writer status ${sourceId}`);
+ const root = binding.local_path;
+ const active = await readActiveRefresh(engine, binding.worktree_id);
+ if (active) throw refusal('refresh_in_progress', `Refresh ${active.id} of this worktree is ${active.state}; only one refresh per worktree runs at a time.`,
+ `gbrain sources refresh ${sourceId} --resume`, active.id);
+ if (binding.state !== 'active' || await worktreeRecoveryPending(engine, binding.worktree_id)) throw refusal('refresh_recovery_required',
+ 'Publication or topology recovery is pending on this worktree; the checkout must not move until it is recovered.',
+ `gbrain sources writer status ${sourceId}, let the owner finish recovery, then gbrain sources refresh ${sourceId}`);
+ const members = (await engine.executeRaw<{ source_id: string }>('SELECT source_id FROM persistence_source_bindings WHERE worktree_id=$1::uuid ORDER BY source_id',
+ [binding.worktree_id])).map(row => row.source_id);
+ await assertNoUnfinishedSync(engine, members);
+ const branch = (await git(['-C', root, 'symbolic-ref', '--quiet', '--short', 'HEAD'])).stdout.trim();
+ const upstream = branch ? await git(['-C', root, 'rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}']) : null;
+ if (!branch || !upstream || upstream.code !== 0) {
+ const remote = (await git(['-C', root, 'remote'])).stdout.split('\n').map(v => v.trim()).filter(Boolean)[0] ?? 'origin';
+ throw refusal('refresh_no_upstream', `The checkout ${branch ? `branch ${branch}` : '(detached HEAD)'} has no upstream branch, so there is nothing to fast-forward to.`,
+ branch ? `git -C ${q(root)} branch --set-upstream-to ${remote}/${branch}` : `git -C ${q(root)} switch <branch>, then git -C ${q(root)} branch --set-upstream-to ${remote}/<branch>`);
+ }
+ const upstreamRef = upstream.stdout.trim();
+ const remote = (await git(['-C', root, 'config', '--get', `branch.${branch}.remote`])).stdout.trim();
+ const merge = (await git(['-C', root, 'config', '--get', `branch.${branch}.merge`])).stdout.trim();
+ if (remote && remote !== '.') {
+ const fetched = await git(['-C', root, 'fetch', '--no-tags', '--quiet', remote, merge || branch], fetchTimeoutMs);
+ if (fetched.code !== 0) throw refusal('fetch_failed',
+ fetched.timedOut ? `git fetch ${remote} did not finish within ${fetchTimeoutMs} ms; nothing changed.`
+ : `git fetch ${remote} failed (${fetched.stderr.trim().split('\n')[0] || `exit ${fetched.code}`}); nothing changed.`,
+ `Retry gbrain sources refresh ${sourceId}; for a slow remote raise the bound: gbrain sources refresh ${sourceId} --fetch-timeout-ms ${Math.max(fetchTimeoutMs * 2, 120_000)} (or gbrain config set sources.refresh_fetch_timeout_ms <ms>).`);
+ }
+ const oldHead = await revParse(git, root, 'HEAD');
+ const targetHead = await revParse(git, root, '@{upstream}');
+ if (!oldHead || !targetHead) throw refusal('refresh_no_upstream', `The checkout HEAD or its upstream ${upstreamRef} does not resolve to a commit.`,
+ `git -C ${q(root)} fetch ${remote || 'origin'}, then gbrain sources refresh ${sourceId}`);
+ if (oldHead !== targetHead && !await isAncestor(git, root, oldHead, targetHead)) throw refusal('refresh_diverged',
+ `The checkout HEAD ${oldHead} is not an ancestor of ${upstreamRef} (${targetHead}); a fast-forward is impossible and nothing changed.`,
+ `Reconcile the histories and push from a non-managed clone, then retry gbrain sources refresh ${sourceId}; or replace the checkout with gbrain sources reclone ${sourceId} (ask the user first).`);
+ const dirt = await dirtyOverlap(git, root, oldHead, targetHead);
+ if (dirt.overlap.length) throw dirtyRefusal(sourceId, dirt.overlap);
+ return { binding, root, members, upstreamRef, oldHead, targetHead, ...dirt };
+}
+function dirtyRefusal(sourceId: string, overlap: string[], refreshId?: string): OperationError {
+ const named = overlap.slice(0, 20).join(', ') + (overlap.length > 20 ? ` and ${overlap.length - 20} more` : '');
+ return refusal('refresh_dirty', `Uncommitted or untracked paths overlap the incoming upstream changes: ${named}. Nothing changed.`,
+ `Commit or discard those paths (check gbrain sources writer status ${sourceId} --json for pending git effects first), then retry gbrain sources refresh ${sourceId}.`, refreshId);
+}
+async function worktreeRecoveryPending(engine: BrainEngine, worktreeId: string): Promise<boolean> {
+ const [row] = await engine.executeRaw<{ pending: boolean }>(`SELECT EXISTS (SELECT 1 FROM persistence_requests WHERE worktree_id=$1::uuid AND recovery IS NOT NULL)
+ OR EXISTS (SELECT 1 FROM persistence_effects WHERE worktree_id=$1::uuid AND recovery IS NOT NULL)
+ OR EXISTS (SELECT 1 FROM persistence_topology_changes WHERE recovery IS NOT NULL AND recovery->>'worktreeId'=$1::text) AS pending`, [worktreeId]);
+ return row?.pending === true;
+}
+/** Never wait on a sync: an unexhausted cursor names its own resume command. */
+async function assertNoUnfinishedSync(engine: BrainEngine, members: string[]): Promise<void> {
+ const [cursor] = await engine.executeRaw<{ source_id: string; header: Record<string, unknown>; failed: boolean }>(`SELECT c.completed_keys->0->>'sourceId' AS source_id,
+ c.completed_keys->0 AS header,EXISTS (SELECT 1 FROM op_checkpoints f WHERE f.op='managed-sync-failure' AND f.fingerprint=c.fingerprint) AS failed
+ FROM op_checkpoints c WHERE c.op='managed-sync' AND COALESCE(c.completed_keys->0->>'done','false')<>'true'
+ AND c.completed_keys->0->>'sourceId'=ANY($1::text[]) ORDER BY c.updated_at LIMIT 1`, [members]);
+ if (!cursor) return;
+ const header = cursor.header as { processingOptions?: Record<string, boolean>; syncOptions?: Parameters<typeof checkpointRetryCommand>[0]['syncOptions'] };
+ const resume = checkpointRetryCommand({ sourceId: cursor.source_id, processingOptions: header.processingOptions, syncOptions: header.syncOptions ?? null });
+ throw refusal('sync_in_progress', `Source ${cursor.source_id} has an unfinished managed sync cursor; moving the checkout now would strand it.`,
+ `${cursor.failed ? resume : resume.replace(' --retry-failed', '')}, then retry the refresh.`);
+}
+
+async function drainCounts(engine: BrainEngine, worktreeId: string): Promise<{ requests: number; effects: number; recovery: number }> {
+ const [row] = await engine.executeRaw<{ requests: number; effects: number; recovery: number }>(`SELECT
+ (SELECT count(*) FROM persistence_requests WHERE worktree_id=$1::uuid AND state IN ('queued','running','recovering'))::int AS requests,
+ (SELECT count(*) FROM persistence_effects WHERE worktree_id=$1::uuid AND kind IN ${CHECKOUT_EFFECT_KINDS_SQL} AND state IN ('queued','running'))::int AS effects,
+ ((SELECT count(*) FROM persistence_requests WHERE worktree_id=$1::uuid AND recovery IS NOT NULL)
+ +(SELECT count(*) FROM persistence_effects WHERE worktree_id=$1::uuid AND recovery IS NOT NULL))::int AS recovery`, [worktreeId]);
+ return { requests: Number(row.requests), effects: Number(row.effects), recovery: Number(row.recovery) };
+}
+
+async function headOf(git: Git, root: string): Promise<string | null> { return revParse(git, root, 'HEAD'); }
+
+/** Step 5: `merged` and the lane B upstream observation, then `syncing`, in one transaction. */
+async function bookkeeping(engine: BrainEngine, row: WorktreeRefreshRow): Promise<void> {
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
+ if (!await transition(tx, row, ['fenced', 'merged', 'recovery_required'], 'merged')) throw new OperationError('source_changed', 'The refresh record changed under its own lock.');
+ await tx.executeRaw(`UPDATE sources SET upstream_checked_at=now(),upstream_commit=$2,upstream_behind=0 WHERE id=ANY($1::text[])`, [row.source_ids, row.target_head]);
+ await transition(tx, row, ['merged'], 'syncing');
+ });
+}
+
+/** Steps 6-7: the managed `--no-pull` sync per member, then completion when every member is at target_head. */
+async function syncMembers(engine: BrainEngine, git: Git, row: WorktreeRefreshRow, root: string): Promise<{ synced: RefreshMemberSync[]; blocked: RefreshSyncBlocked[] }> {
+ const { performManagedSync } = await import('./sync-run.ts');
+ const synced: RefreshMemberSync[] = [], blocked: RefreshSyncBlocked[] = [];
+ for (const sourceId of row.source_ids) {
+ let status = 'up_to_date';
+ for (let pass = 0; pass < MAX_MEMBER_SYNC_PASSES; pass++) {
+ const commit = await lastCommit(engine, sourceId);
+ if (commit === row.target_head || (commit && commit !== row.old_head && await isAncestor(git, root, row.target_head, commit))) break;
+ let result: SyncResult;
+ try { result = await performManagedSync(engine, { sourceId, noPull: true }); }
+ catch (error) {
+ const failure = error instanceof OperationError ? error : new OperationError('storage_error', error instanceof Error ? error.message : String(error));
+ blocked.push({ source_id: sourceId, code: failure.code, message: failure.message, resume: `gbrain sync --source ${sourceId} --no-pull --retry-failed` });
+ status = 'blocked';
+ break;
+ }
+ status = result.status;
+ if (result.status === 'blocked_by_failures') {
+ blocked.push({ source_id: sourceId, code: result.managedWrite?.write_error ?? result.failureCodes?.[0]?.code ?? 'sync_blocked',
+ message: result.managedWrite?.message ?? 'The managed sync is blocked by a failed write.', resume: `gbrain sync --source ${sourceId} --no-pull --retry-failed` });
+ break;
+ }
+ if (result.status === 'partial') await new Promise(resolve => setTimeout(resolve, DRAIN_POLL_MS));
+ }
+ await recordUpstreamObservation(engine, sourceId);
+ synced.push({ source_id: sourceId, status, last_commit: await lastCommit(engine, sourceId) });
+ }
+ const atTarget = synced.every(member => member.last_commit === row.target_head);
+ if (atTarget || blocked.length) await engine.transaction(tx => transition(tx, row, ['syncing'], 'completed',
+ { synced, ...(blocked.length ? { sync_blocked: blocked } : {}) }));
+ return { synced, blocked };
+}
+async function lastCommit(engine: BrainEngine, sourceId: string): Promise<string | null> {
+ const [row] = await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]);
+ return row?.last_commit ?? null;
+}
+
+function finished(row: WorktreeRefreshRow, sync: { synced: RefreshMemberSync[]; blocked: RefreshSyncBlocked[] }, preserved = row.preserved_uncommitted): WorktreeRefreshResult {
+ const status = sync.blocked.length ? 'sync_blocked' : sync.synced.every(member => member.last_commit === row.target_head) ? 'completed' : 'syncing';
+ return { status, refresh_id: row.id, worktree_id: row.worktree_id, source_ids: row.source_ids, old_head: row.old_head, target_head: row.target_head,
+ upstream_ref: row.upstream_ref, preserved_uncommitted: preserved, synced: sync.synced,
+ ...(sync.blocked.length ? { sync_blocked: sync.blocked, next: sync.blocked.map(item => item.resume).join(' ; ') } : {}),
+ ...(status === 'syncing' ? { next: `gbrain sources refresh ${row.source_ids[0]} --resume` } : {}) };
+}
+
+/**
+ * `gbrain sources refresh <source>`. Trusted local CLI on the registered owner
+ * host only; refusals throw catalogue errors (`code`, cause, literal fix, docs).
+ */
+export async function refreshWorktree(engine: BrainEngine, sourceId: string, opts: RefreshOptions = {}): Promise<WorktreeRefreshResult> {
+ if (opts.resume || opts.abandon) return resumeOrAbandon(engine, sourceId, opts);
+ const fetchTimeoutMs = await configuredMs(engine, opts.fetchTimeoutMs, 'GBRAIN_REFRESH_FETCH_TIMEOUT_MS', 'sources.refresh_fetch_timeout_ms', 120_000);
+ const waitDrainMs = await configuredMs(engine, opts.waitDrainMs, 'GBRAIN_REFRESH_DRAIN_WAIT_MS', 'sources.refresh_drain_wait_ms', 60_000);
+ return withGit(async git => {
+ const plan = await precheck(engine, git, sourceId, fetchTimeoutMs);
+ const base = { refresh_id: null, worktree_id: plan.binding.worktree_id, source_ids: plan.members, old_head: plan.oldHead,
+ target_head: plan.targetHead, upstream_ref: plan.upstreamRef, preserved_uncommitted: plan.preserved, incoming_files: plan.incoming };
+ if (opts.dryRun) return { ...base, status: 'dry_run', synced: [],
+ next: plan.oldHead === plan.targetHead ? `Already at ${plan.upstreamRef}; nothing to fast-forward.` : `gbrain sources refresh ${sourceId}` };
+ if (plan.oldHead === plan.targetHead) {
+ const synced: RefreshMemberSync[] = [], blocked: RefreshSyncBlocked[] = [];
+ const { performManagedSync } = await import('./sync-run.ts');
+ for (const member of plan.members) {
+ await recordUpstreamObservation(engine, member);
+ if (await lastCommit(engine, member) === plan.oldHead) { synced.push({ source_id: member, status: 'up_to_date', last_commit: plan.oldHead }); continue; }
+ try {
+ const result = await performManagedSync(engine, { sourceId: member, noPull: true });
+ if (result.status === 'blocked_by_failures') blocked.push({ source_id: member, code: result.managedWrite?.write_error ?? 'sync_blocked',
+ message: result.managedWrite?.message ?? 'The managed sync is blocked by a failed write.', resume: `gbrain sync --source ${member} --no-pull --retry-failed` });
+ synced.push({ source_id: member, status: result.status, last_commit: await lastCommit(engine, member) });
+ } catch (error) {
+ blocked.push({ source_id: member, code: (error as OperationError).code ?? 'storage_error', message: (error as Error).message, resume: `gbrain sync --source ${member} --no-pull --retry-failed` });
+ }
+ }
+ return { ...base, status: blocked.length ? 'sync_blocked' : 'already_current', synced, ...(blocked.length ? { sync_blocked: blocked, next: blocked.map(b => b.resume).join(' ; ') } : {}) };
+ }
+ const refreshLock = await tryAcquireNativeLock(refreshLockPath(plan.binding.worktree_id));
+ if (!refreshLock) throw refusal('refresh_in_progress', 'Another process is refreshing this worktree right now.', `gbrain sources refresh ${sourceId} --resume`);
+ try {
+ const principal = await topologyPrincipal(engine);
+ const row = await fenceDraining(engine, sourceId, plan, principal);
+ const config = loadConfig() ?? { engine: engine.kind };
+ // The owner keeps claiming what is already queued; this process may be that owner.
+ startPersistenceConsumer(engine, config);
+ const deadline = performance.now() + waitDrainMs;
+ for (;;) {
+ const counts = await drainCounts(engine, row.worktree_id);
+ if (counts.requests + counts.effects + counts.recovery === 0) break;
+ if (performance.now() >= deadline) {
+ await abort(engine, row, ['draining'], refusal('refresh_drain_timeout',
+ `The worktree queue did not drain within ${waitDrainMs} ms (${counts.requests} request(s), ${counts.effects} checkout effect(s), ${counts.recovery} recovery record(s) pending); the fence was lifted and nothing moved.`,
+ `Retry gbrain sources refresh ${sourceId}, or wait longer: gbrain sources refresh ${sourceId} --wait-drain ${Math.ceil(Math.max(waitDrainMs * 2, 120_000) / 1000)}. Inspect the queue with gbrain sources writer status ${sourceId} --json.`), { counts });
+ }
+ await new Promise(resolve => setTimeout(resolve, DRAIN_POLL_MS));
+ }
+ await opts.hooks?.boundary?.('drained', row);
+ const merged = await fenceAndMerge(engine, git, sourceId, plan, row, opts.hooks);
+ const sync = await syncMembers(engine, git, merged, plan.root);
+ return finished(await readRefresh(engine, row.id), sync, plan.preserved);
+ } finally { await refreshLock.release(); }
+ });
+}
+
+/** Step 2: native topology + worktree locks, then one transaction inserting the `draining` row. */
+async function fenceDraining(engine: BrainEngine, sourceId: string, plan: Plan, principal: string): Promise<WorktreeRefreshRow> {
+ return withTopologyLocks(engine, sourceId, async bindings => engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','5s',true)");
+ await lockTopologyPrincipal(tx, principal);
+ const sources = await lockTopologyRows(tx, sourceId, bindings);
+ const current = bindings.find(binding => binding.worktree_id === plan.binding.worktree_id);
+ if (!current || String(current.owner_epoch) !== String(plan.binding.owner_epoch) || String(current.topology_generation) !== String(plan.binding.topology_generation)
+ || sources.join(',') !== plan.members.join(',')) {
+ throw refusal('refresh_source_changed', 'The worktree ownership or source membership changed after the refresh precheck; nothing moved.', `Retry gbrain sources refresh ${sourceId}`);
+ }
+ const [row] = await tx.executeRaw<WorktreeRefreshRow>(`INSERT INTO persistence_worktree_refreshes
+ (worktree_id,source_ids,principal_id,owner_epoch,topology_generation,state,old_head,target_head,upstream_ref,preserved_uncommitted)
+ VALUES($1::uuid,$2::text[],$3::uuid,$4,$5,'draining',$6,$7,$8,$9::text[]) RETURNING *`,
+ [plan.binding.worktree_id, plan.members, principal, String(current.owner_epoch), String(current.topology_generation),
+ plan.oldHead, plan.targetHead, plan.upstreamRef, plan.preserved]);
+ return row;
+ })).catch(error => {
+ if ((error as { code?: string }).code === '23505') throw refusal('refresh_in_progress', 'Another refresh of this worktree started first.', `gbrain sources refresh ${sourceId} --resume`);
+ throw error;
+ });
+}
+
+/** Steps 3-5 under the worktree native lock: recheck drained, fence, verify HEAD, ff-only merge, bookkeeping. */
+async function fenceAndMerge(engine: BrainEngine, git: Git, sourceId: string, plan: Plan, row: WorktreeRefreshRow, hooks?: RefreshHooks): Promise<WorktreeRefreshRow> {
+ let fenced: WorktreeRefreshRow;
+ try {
+ fenced = await withTopologyLocks(engine, sourceId, async bindings => {
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','5s',true)");
+ const sources = await lockTopologyRows(tx, sourceId, bindings, row.id);
+ const current = bindings.find(binding => binding.worktree_id === row.worktree_id);
+ if (!current || String(current.owner_epoch) !== String(row.owner_epoch) || String(current.topology_generation) !== String(row.topology_generation)
+ || sources.join(',') !== row.source_ids.join(',')) {
+ throw refusal('refresh_source_changed', 'The worktree ownership or source membership changed while the refresh drained; nothing moved.', `Retry gbrain sources refresh ${sourceId}`, row.id);
+ }
+ const counts = await drainCounts(tx, row.worktree_id);
+ if (counts.requests + counts.effects + counts.recovery > 0) throw refusal('refresh_source_changed',
+ `Work reached the worktree after the drain check (${counts.requests} request(s), ${counts.effects} checkout effect(s), ${counts.recovery} recovery record(s)); nothing moved.`,
+ `Retry gbrain sources refresh ${sourceId}`, row.id);
+ if (!await transition(tx, row, ['draining'], 'fenced')) throw refusal('refresh_source_changed', 'The refresh record was moved by recovery while draining.', `gbrain sources refresh ${sourceId} --resume`, row.id);
+ });
+ const current = await readRefresh(engine, row.id);
+ await hooks?.boundary?.('fenced', current);
+ const head = await headOf(git, plan.root);
+ if (head !== row.old_head) {
+ if (head === null) throw await markRecoveryRequired(engine, current, head, plan.root);
+ await abort(engine, current, ['fenced'], refusal('refresh_source_changed',
+ `The checkout HEAD moved from ${row.old_head} to ${head} after the precheck (an external commit or checkout); nothing was merged.`, `Retry gbrain sources refresh ${sourceId}`));
+ }
+ const dirt = await dirtyOverlap(git, plan.root, row.old_head, row.target_head);
+ if (dirt.overlap.length) await abort(engine, current, ['fenced'], dirtyRefusal(sourceId, dirt.overlap));
+ const merge = await git(['-C', plan.root, 'merge', '--ff-only', '--no-edit', '--quiet', row.target_head], 120_000);
+ const after = await headOf(git, plan.root);
+ if (merge.code !== 0 || after !== row.target_head) {
+ if (after === row.old_head) await abort(engine, current, ['fenced'], refusal('refresh_dirty',
+ `git merge --ff-only refused (${merge.stderr.trim().split('\n')[0] || `exit ${merge.code}`}); HEAD is unchanged at ${row.old_head}.`,
+ `Commit or discard the paths git names (check gbrain sources writer status ${sourceId} --json for pending git effects), then retry gbrain sources refresh ${sourceId}.`));
+ throw await markRecoveryRequired(engine, current, after, plan.root);
+ }
+ await hooks?.boundary?.('merged', current);
+ await bookkeeping(engine, current);
+ return readRefresh(engine, row.id);
+ }, undefined, 30_000);
+ } catch (error) {
+ const stored = await readRefresh(engine, row.id);
+ if (stored.state === 'draining' && error instanceof OperationError) {
+ await engine.transaction(tx => transition(tx, stored, ['draining'], 'aborted', refusalOutcome(error)));
+ error.detail ??= `refresh_id=${row.id}`;
+ }
+ throw error;
+ }
+ return fenced;
+}
+
+async function hostRoot(engine: BrainEngine, worktreeId: string, hostId = localHostId()): Promise<string | null> {
+ const [row] = await engine.executeRaw<{ local_path: string | null }>(
+ 'SELECT local_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid', [worktreeId, hostId]);
+ return row?.local_path ?? null;
+}
+
+/**
+ * Section 1.5: deterministic, bounded convergence of one interrupted refresh.
+ * The caller holds the refresh lock. Returns the row after the step.
+ */
+async function recoverOne(engine: BrainEngine, git: Git, row: WorktreeRefreshRow, root: string): Promise<WorktreeRefreshRow> {
+ const head = await headOf(git, root);
+ if (row.state === 'draining') {
+ await engine.transaction(tx => transition(tx, row, ['draining'], 'aborted', { refusal: { code: 'refresh_interrupted', cause: 'The refreshing process stopped while draining; no merge was started.' } }));
+ } else if (row.state === 'fenced' && head === row.old_head) {
+ await engine.transaction(tx => transition(tx, row, ['fenced'], 'aborted', { refusal: { code: 'refresh_interrupted', cause: 'The refreshing process stopped before merging; HEAD is unchanged.' } }));
+ } else if (['fenced', 'merged', 'recovery_required'].includes(row.state) && head === row.target_head && await isAncestor(git, root, row.old_head, row.target_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.
+ } else if (row.state !== 'recovery_required') {
+ await markRecoveryRequired(engine, row, head, root);
+ }
+ return readRefresh(engine, row.id);
+}
+
+/**
+ * Owner-startup recovery: every active refresh on this host's worktrees whose
+ * refreshing process has exited (its refresh lock is free) is converged one
+ * step. Member syncs are not run here; `--resume` or the next cycle sync does.
+ */
+export async function resumeWorktreeRefreshes(engine: BrainEngine, opts: { hostId?: string } = {}): Promise<number> {
+ const host = opts.hostId ?? localHostId();
+ const rows = await engine.executeRaw<WorktreeRefreshRow>(`SELECT f.* FROM persistence_worktree_refreshes f
+ JOIN persistence_worktrees w ON w.id=f.worktree_id WHERE w.owner_host_id=$1::uuid AND f.state IN ('draining','fenced','merged','syncing')
+ ORDER BY f.created_at LIMIT 16`, [host]);
+ let moved = 0;
+ for (const row of rows) {
+ const root = await hostRoot(engine, row.worktree_id, host);
+ if (!root) continue;
+ const lock = await tryAcquireNativeLock(refreshLockPath(row.worktree_id));
+ if (!lock) continue;
+ try {
+ await withGit(async git => {
+ const after = await withTopologyLocks(engine, row.source_ids[0], async () => recoverOne(engine, git, await readRefresh(engine, row.id), root), undefined, 0);
+ if (after.state !== row.state) moved++;
+ });
+ } catch (error) {
+ if (!(error instanceof OperationError && ['write_pending', 'recovery_required', 'refresh_recovery_required', 'owner_unavailable'].includes(error.code))) throw error;
+ } finally { await lock.release(); }
+ }
+ return moved;
+}
+
+async function resumeOrAbandon(engine: BrainEngine, sourceId: string, opts: RefreshOptions): Promise<WorktreeRefreshResult> {
+ const binding = await getWorktreeBinding(engine, sourceId);
+ if (!await managedPersistenceEnabled(engine) || !binding) throw refusal('refresh_not_managed',
+ `Source ${sourceId} has no claimed canonical worktree on a managed brain, so there is no refresh to resume.`, `gbrain sync --source ${sourceId}`);
+ if (binding.owner_host_id !== localHostId() || !binding.local_path) throw refusal('refresh_not_owner',
+ `Only the registered owner host of source ${sourceId} may resume its refresh.`, `Run it on the owner host; check it with gbrain sources writer status ${sourceId}`);
+ const root = binding.local_path;
+ const active = await readActiveRefresh(engine, binding.worktree_id);
+ const empty: WorktreeRefreshResult = { status: 'nothing_to_resume', refresh_id: null, worktree_id: binding.worktree_id, source_ids: [sourceId],
+ old_head: null, target_head: null, upstream_ref: null, preserved_uncommitted: [], synced: [], next: `gbrain sources refresh ${sourceId}` };
+ if (!active) return empty;
+ const lock = await acquireNativeLock(refreshLockPath(binding.worktree_id), { timeoutMs: 1000 }).catch(() => null as NativeLockHandle | null);
+ if (!lock) throw refusal('refresh_in_progress', `Refresh ${active.id} is still running in another process.`, `Wait for it, then gbrain sources refresh ${sourceId} --resume`, active.id);
+ try {
+ return await withGit(async git => {
+ const head = await headOf(git, root);
+ if (opts.abandon) {
+ const row = await readRefresh(engine, active.id);
+ 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) {
+ 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);
+ }
+ 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}` };
+ }
+ let row = await withTopologyLocks(engine, sourceId, async () => recoverOne(engine, git, await readRefresh(engine, active.id), root), 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') {
+ 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.',
+ stored.fix ?? `gbrain sources writer status ${sourceId}, then gbrain sources refresh ${sourceId} --resume`, row.id);
+ }
+ if (row.state !== 'syncing') 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, next: `The interrupted refresh was rolled back without moving HEAD; start again with gbrain sources refresh ${sourceId}` };
+ startPersistenceConsumer(engine, loadConfig() ?? { engine: engine.kind });
+ const sync = await syncMembers(engine, git, row, root);
+ row = await readRefresh(engine, row.id);
+ return finished(row, sync);
+ });
+ } finally { await lock.release(); }
+}
+
+/**
+ * A managed sync started elsewhere (cycle, autopilot, `gbrain sync`) while a
+ * refresh drains or holds the fence is refused before discovery, so it never
+ * freezes a cursor against the pre-refresh HEAD; the next cycle retries.
+ */
+export async function assertManagedSyncAllowed(engine: BrainEngine, worktreeId: string, sourceId: string): Promise<void> {
+ const [refresh] = await engine.executeRaw<{ id: string; state: string }>(`SELECT id,state FROM persistence_worktree_refreshes
+ WHERE worktree_id=$1::uuid AND state IN ('draining','fenced','merged','recovery_required')`, [worktreeId]);
+ if (!refresh) return;
+ if (refresh.state === 'recovery_required') throw refusal('refresh_recovery_required',
+ `Refresh ${refresh.id} could not verify the checkout HEAD of source ${sourceId}; sync stays fenced.`,
+ `gbrain sources writer status ${sourceId}, then gbrain sources refresh ${sourceId} --resume`, refresh.id);
+ const error = refusal('worktree_refreshing', `Source ${sourceId}'s checkout is being fast-forwarded by refresh ${refresh.id} (${refresh.state}); this sync did not start.`,
+ `Retry after retry_after_ms: 1000; the refresh runs this sync itself. Check progress with gbrain sources writer status ${sourceId}.`);
+ error.detail = 'retry_after_ms=1000';
+ throw error;
+}
+
+/** Doctor `worktree_refresh_stuck`: active refreshes older than `minutes`. */
+export async function stuckWorktreeRefreshes(engine: BrainEngine, minutes = 15): Promise<Array<Pick<WorktreeRefreshRow, 'id' | 'state' | 'source_ids' | 'updated_at'>>> {
+ return engine.executeRaw(`SELECT id,state,source_ids,updated_at FROM persistence_worktree_refreshes
+ WHERE state IN ${ACTIVE_REFRESH_STATES_SQL} AND created_at < now()-($1::double precision*interval '1 minute') ORDER BY created_at`, [minutes]);
+}