Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(refresh): opt-in sources.refresh_publish_diverged publishes a diverged managed checkout (keep-checkout publish) before fast-forwarding (#7686)

garrytan7d6ba39bd0ee
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2634aeb65c..dd44b0df4f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,41 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**A managed checkout that gets local commits while a sibling checkout pushes the same branch can now stay current without a person in the loop. Turn on `sources.refresh_publish_diverged` and a diverged `gbrain sources refresh` publishes the local commits merged with the upstream, then fast-forwards.**
+
+Before, such a refresh always refused `refresh_diverged`, and the database lagged the upstream until someone ran the keep-checkout publish by hand or a scheduled publish caught up. That repeated every interval. The setting is the user's standing consent to push those local commits. It defaults to off, so nothing changes for existing brains.
+
+### How to get it
+
+```bash
+gbrain config set sources.refresh_publish_diverged true
+```
+
+### What changed
+
+| Situation | Before | Now |
+|---|---|---|
+| Diverged checkout, setting on | refused `refresh_diverged` | pushes HEAD merged with the upstream in memory (the `gbrain git commit-push --push-only --keep-checkout` publish), fast-forwards to the merge and reports `published` (sha, local commits, upstream commits merged) |
+| Diverged checkout, setting off (the default) | refused `refresh_diverged` | unchanged; the refusal now also names the setting |
+| A file both sides changed, setting on | n/a | refuses `integrate_conflict` naming the file; nothing is pushed, fenced or moved |
+| `--dry-run` | refused `refresh_diverged` | unchanged: a dry run never publishes |
+| `gbrain config set sources.refresh_fetch_timeout_ms` / `sources.refresh_drain_wait_ms` | refused as an unknown key, although the refresh reads both | accepted |
+
+### Things to watch after you upgrade
+
+- The publish needs a Git identity in the checkout for the merge commit, the same as the manual keep-checkout publish.
+- It never uses a `--pull` that moves the checkout: the merge is built in memory and pushed, and the checkout moves only through the refresh's usual fast-forward.
+
+### Itemized changes
+
+- `src/core/persistence/worktree-refresh.ts`: when `sources.refresh_publish_diverged` is on and the run is not a dry run, the precheck runs `commitAndPush` (`pushOnly`, `keepCheckout`) for a diverged checkout, re-fetches and continues; the result carries `published`. The `refresh_diverged` suggestion names the setting.
+- `src/commands/sources-refresh.ts`: a text line for the publish.
+- `src/core/config-runtime-keys.ts`: registers `sources.refresh_publish_diverged`, `sources.refresh_fetch_timeout_ms` and `sources.refresh_drain_wait_ms`.
+- Docs: `docs/guides/live-sync.md`, `docs/guides/write-refusals.md`, `docs/architecture/canonical-writers.md` and its census.
+- Tests: `test/refresh-publish-diverged-7686.test.ts` (setting on, off, a conflict and a dry run, on PGLite and on Postgres through `test/e2e/worktree-refresh-postgres.test.ts`).
+
## [0.60.472.0] - 2026-10-27
**A `gbrain sources refresh` whose process dies mid-refresh no longer wedges the managed checkout. The next refresh finishes it, and status tells you who holds a refresh and whether it is still running.**
diff --git a/docs/architecture/canonical-writers.md b/docs/architecture/canonical-writers.md
index c8401fbd84..4e139e25d3 100644
--- a/docs/architecture/canonical-writers.md
+++ b/docs/architecture/canonical-writers.md
@@ -78,7 +78,10 @@ worktree native lock while claims stop (`fenced`), verifies HEAD and runs
ordinary managed `--no-pull` sync that follows, so every imported page is a
journaled request. A durable `persistence_worktree_refreshes` row lets a
restarted owner converge an interrupted refresh without adopting an unverified
-HEAD. Remote sync retains the
+HEAD. With `sources.refresh_publish_diverged` on (the user's standing consent,
+default off), a diverged refresh first runs the keep-checkout publish, which
+pushes HEAD merged with the upstream in memory and never moves the checkout or
+writes the database, then fast-forwards as above. Remote sync retains the
original `submit_job` principal, admin/source/operation ceiling and normalized
payload; runtime options cannot expand that grant and current revocation is
checked before publication.
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 4d0b9c608f..fb958a3589 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -251,7 +251,7 @@ src/core/repair/frontmatter.ts 2 coordinator `gbrain repair frontmatter --apply`
src/commands/sources-mirror.ts 1 engine_guard `gbrain sources mirror-readonly|mirror-writable` (#5409) updates only sources.config.mirror_read_only, exactly as `sources federate` updates sources.config.federated; the sources managed_writer_guard trigger governs the row and no page, fact or file is written.
src/core/sync-upstream.ts 1 engine_guard `recordUpstreamObservation` (#5255/#5176) updates only sources.upstream_checked_at, upstream_commit and upstream_behind, observations of the checkout's Git upstream outside managed_writer_guard's protected topology and checkpoint tuples; no page, fact or file is written, and a failure never fails the sync.
src/core/persistence/mirror-read-only.ts 1 coordinator classifyMirrorPage stamps pages.database_only_reason=mirror_read_only only inside the coordinator publication transaction of a page write that published no file into a read-only mirror source (#5409), as classifyUnboundPage does for unbound sources.
-src/core/persistence/worktree-refresh.ts 1 coordinator `gbrain sources refresh` (F0) is the one sanctioned managed Git writer: it fast-forwards the checkout only under the worktree native lock after admission refused and claims stopped every checkout write (`fenced`), then updates only sources.upstream_checked_at/upstream_commit/upstream_behind in the merged bookkeeping transaction; pages and the checkpoint advance through the ordinary managed --no-pull sync.
+src/core/persistence/worktree-refresh.ts 1 coordinator `gbrain sources refresh` (F0) is the one sanctioned managed Git writer: it fast-forwards the checkout only under the worktree native lock after admission refused and claims stopped every checkout write (`fenced`), then updates only sources.upstream_checked_at/upstream_commit/upstream_behind in the merged bookkeeping transaction; pages and the checkpoint advance through the ordinary managed --no-pull sync. #7686: with sources.refresh_publish_diverged on (standing consent, default off) it first runs the keep-checkout publish (commitAndPush pushOnly+keepCheckout), which pushes HEAD merged with the upstream in memory and never moves the checkout or the database.
src/core/facts/unfenced-facts.ts 3 coordinator The extract_facts cycle phase and the v0.32.2 migration fence row_num-NULL facts onto their entity pages. On a managed brain the fence publishes through a coordinated maintenance request; an unmanaged brain writes the page file under the source filesystem and page locks, then mirrors the body and stamps row numbers in one maintenanceTransaction.
src/core/repair/take-supersession.ts 1 coordinator gbrain repair take-supersession reprojects superseded_by for a page whose fence is already right: inside withCoordinatedWrite under the page key on a managed brain (revision-checked), maintenanceTransaction on an unmanaged one. Fence edits go through a revision-bound put_page request.
src/core/repair/timeline-comments.ts 2 coordinator `gbrain repair timeline-comments` (#6184) deletes or rewrites timeline rows carrying HTML comment markup under the page lock: `withCoordinatedWrite` with maintenance attribution on managed brains, `maintenanceTransaction` otherwise; the page body changes go through a revision-bound put_page first.
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index f532f585b0..719fcdb28c 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -668,6 +668,15 @@ vars — incident-time escape hatches, not everyday knobs.
means something commits into the checkout outside gbrain: fix that writer
instead of forcing the checkout
([scripts and the managed checkout](shared-checkout-git.md#scripts-and-the-managed-checkout)).
+ When local commits there are expected (automations committing alongside a
+ sibling checkout that pushes the same branch), the user can give standing
+ consent with `gbrain config set sources.refresh_publish_diverged true`
+ (default off): a diverged refresh then pushes the local commits merged with
+ the upstream in memory, the same publish as
+ `gbrain git commit-push --push-only --keep-checkout`, and fast-forwards to
+ the merge. It never moves the checkout to merge, a conflicting file refuses
+ `integrate_conflict` naming it with nothing pushed, and `--dry-run` never
+ publishes.
**Say to your agent:** *"Bring my notes source up to date with its remote."*
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 2b4be8749c..34abc11157 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -516,7 +516,7 @@ this anchor (`--json` puts them in one object on stdout); the command exits 1.
| <a id="refresh_no_upstream"></a>`refresh_no_upstream` | `refresh_no_upstream` | The checkout's branch tracks no upstream, HEAD is detached, or the checkout is not a Git checkout at all (gbrain never initializes Git on its own), 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 checkout that is not Git has nothing to refresh; making it a clone with an upstream is the user's call. |
| <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_git_unavailable"></a>`git_unavailable` | `git_unavailable` | A git command that reads the checkout's branch or remote (`symbolic-ref`, `remote`, `config --get branch.<branch>.remote` or `.merge`) failed or did not finish, so the checkout's state is unknown. The message names the command and git's first error line. A detached HEAD or an unset key is not this refusal. Nothing changed and no refresh record was written. | Run `git -C <checkout> status` to see why git cannot read the checkout, repair what it reports, then retry `gbrain sources refresh <source>`. |
-| <a id="refresh_diverged"></a>`refresh_diverged` | `refresh_diverged` | The checkout has commits its upstream lacks, so a fast-forward is impossible. Nothing changed. | Ask the user, then publish the local commits merged with the upstream: `gbrain git commit-push --push-only --keep-checkout --path <checkout>` merges in memory, pushes the merge, refuses on a conflicting file and never moves the checkout (the refusal's fix fills in the real path and counts the local commits). Then retry `gbrain sources refresh <source>`, which fast-forwards to the merge. `gbrain sources reclone <source>` replaces the checkout instead and drops the local commits. |
+| <a id="refresh_diverged"></a>`refresh_diverged` | `refresh_diverged` | The checkout has commits its upstream lacks, so a fast-forward is impossible. Nothing changed. | Ask the user, then publish the local commits merged with the upstream: `gbrain git commit-push --push-only --keep-checkout --path <checkout>` merges in memory, pushes the merge, refuses on a conflicting file and never moves the checkout (the refusal's fix fills in the real path and counts the local commits). Then retry `gbrain sources refresh <source>`, which fast-forwards to the merge. `gbrain sources reclone <source>` replaces the checkout instead and drops the local commits. With `sources.refresh_publish_diverged` set to `true` (the user's standing consent, default off), the refresh runs that publish itself and then fast-forwards; a conflicting file then refuses `integrate_conflict` with nothing pushed. |
| <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. `gbrain repair frontmatter --apply` refuses the same way while an unfinished cursor still names a selected file. | Run the printed `gbrain sync --source <source> --no-pull ...` resume command (it keeps the cursor's options), then retry (for a repair, preview again and approve the new hash). |
| <a id="refresh_in_progress"></a>`refresh_in_progress` | `refresh_in_progress` | Another refresh of the same checkout is active and its process is still running (the message names its holder's pid and host when the active refresh row is already readable), or a command that changes which sources share the checkout (`sources add`, `remove`, `archive`, `restore`, `reclone`) ran while one was active. A refresh whose process died is not a reason to refuse: the next refresh on the owner host finishes it first (`--dry-run` does not, so it still refuses while the orphan stands, and neither does a refresh that cannot read the checkout's HEAD: it leaves the orphan as it is and refuses until git can read HEAD again). A refresh whose holder is recorded on another host is never taken over either: writer status shows its `liveness` as `unknown`, and `gbrain sources refresh <source> --resume` on the owner host finishes it once that host's refresh is known to have stopped. Pending publication or topology recovery on the checkout refuses `refresh_recovery_required` first. An interrupted refresh that needs a reset decision refuses `refresh_recovery_required` instead. | Wait for the running refresh, or check it with `gbrain sources writer status <source>` (`liveness`, `holder`). `gbrain sources refresh <source> --resume` finishes an orphaned one now; then retry the source command with the same request ID. |
diff --git a/llms-full.txt b/llms-full.txt
index 76575d3143..7b2354fc15 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -7711,6 +7711,15 @@ vars — incident-time escape hatches, not everyday knobs.
means something commits into the checkout outside gbrain: fix that writer
instead of forcing the checkout
([scripts and the managed checkout](shared-checkout-git.md#scripts-and-the-managed-checkout)).
+ When local commits there are expected (automations committing alongside a
+ sibling checkout that pushes the same branch), the user can give standing
+ consent with `gbrain config set sources.refresh_publish_diverged true`
+ (default off): a diverged refresh then pushes the local commits merged with
+ the upstream in memory, the same publish as
+ `gbrain git commit-push --push-only --keep-checkout`, and fast-forwards to
+ the merge. It never moves the checkout to merge, a conflicting file refuses
+ `integrate_conflict` naming it with nothing pushed, and `--dry-run` never
+ publishes.
**Say to your agent:** *"Bring my notes source up to date with its remote."*
diff --git a/src/commands/sources-refresh.ts b/src/commands/sources-refresh.ts
index d5288e3a46..6a3186c312 100644
--- a/src/commands/sources-refresh.ts
+++ b/src/commands/sources-refresh.ts
@@ -54,6 +54,7 @@ function describe(result: WorktreeRefreshResult): string {
const head = (value: string | null) => value ? value.slice(0, 12) : '-';
const lines = [`Refresh ${result.status}: sources ${result.source_ids.join(', ')}; ${head(result.old_head)} -> ${head(result.target_head)}${result.upstream_ref ? ` (${result.upstream_ref})` : ''}.`];
if (result.recovered) lines.push(`Recovered orphaned refresh ${result.recovered.refresh_id} (${result.recovered.status}; previous holder: ${result.recovered.previous_holder ? `pid ${result.recovered.previous_holder.pid} on ${result.recovered.previous_holder.hostname}` : 'not recorded'}).`);
+ if (result.published) lines.push(`Published ${result.published.local_commits} local commit(s) merged with ${result.published.integrated} upstream commit(s) as ${head(result.published.sha)} before the fast-forward (sources.refresh_publish_diverged).`);
if (result.incoming_files !== undefined) lines.push(`Incoming files: ${result.incoming_files}.`);
for (const member of result.synced) lines.push(` ${member.source_id}: sync ${member.status}, last_commit ${head(member.last_commit)}`);
if (result.preserved_uncommitted.length) lines.push(`Preserved uncommitted paths (outside the incoming diff): ${result.preserved_uncommitted.slice(0, 20).join(', ')}${result.preserved_uncommitted.length > 20 ? ' ...' : ''}`);
diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.ts
index 8d5f12ffd2..79f9d1b565 100644
--- a/src/core/config-runtime-keys.ts
+++ b/src/core/config-runtime-keys.ts
@@ -19,5 +19,7 @@ export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = [
'writer.lint_on_put_page', // output/post-write.ts lint after put_page, default off
'context.hot_memory.session_only', // facts/meta-hook.ts, read by the turn_context and context_pack IPC handlers: hot memory never falls back to other sessions' facts, default off
'serve.cli_socket', // config.ts loadConfigWithEngine (snapshot only) → serve.ts: a Postgres serve answers CLI reads over a private Unix socket, default off
+ 'sources.refresh_fetch_timeout_ms', 'sources.refresh_drain_wait_ms', // persistence/worktree-refresh.ts: refresh fetch bound (default 120 s) and drain wait (default 60 s), in ms
+ 'sources.refresh_publish_diverged', // persistence/worktree-refresh.ts (#7686): refresh publishes a diverged checkout's local commits merged with the upstream before fast-forwarding, default off
'serve.vector_prewarm', // config.ts loadConfigWithEngine (snapshot only) → serve.ts: a Postgres serve prewarms the HNSW indexes into shared_buffers at start when they fit, default off
];
diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.ts
index 0a8a2c838d..fdee6d8ba6 100644
--- a/src/core/persistence/worktree-refresh.ts
+++ b/src/core/persistence/worktree-refresh.ts
@@ -42,6 +42,8 @@ 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';
import { gitChildEnv } from '../git-env.ts';
+import { commitAndPush } from '../git/commit-push.ts';
+import { isTruthy } from '../connectors/config-keys.ts';
import { classifyOriginUniqueViolation } from './origin-guard.ts';
export interface WorktreeRefreshRow {
@@ -68,6 +70,8 @@ export interface WorktreeRefreshResult {
synced: RefreshMemberSync[]; sync_blocked?: RefreshSyncBlocked[]; next?: string;
/** #7679: an orphaned refresh this run finished (or rolled back) through the `--resume` path before its own refresh. */
recovered?: { refresh_id: string; state: WorktreeRefreshState; status: WorktreeRefreshResult['status']; previous_holder: RefreshHolder | null };
+ /** #7686: the diverged checkout's local commits this run published, merged with the upstream, before fast-forwarding (`sources.refresh_publish_diverged`). */
+ published?: { sha: string; local_commits: number; integrated: number };
}
/** #7679: the process that holds a refresh's lock, recorded on the row so status can name it. */
export interface RefreshHolder { host_id: string | null; hostname: string; pid: number; started_at: string }
@@ -216,11 +220,14 @@ async function markRecoveryRequired(engine: BrainEngine, row: WorktreeRefreshRow
interface Plan {
binding: WorktreeBinding; root: string; members: string[]; upstreamRef: string; oldHead: string; targetHead: string;
- overlap: string[]; preserved: string[]; incoming: number;
+ overlap: string[]; preserved: string[]; incoming: number; published?: WorktreeRefreshResult['published'];
}
+/** #7686: standing consent, default off, to publish a diverged checkout's local commits before the fast-forward. */
+export const REFRESH_PUBLISH_DIVERGED_KEY = 'sources.refresh_publish_diverged';
+
/** 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> {
+async function precheck(engine: BrainEngine, git: Git, sourceId: string, fetchTimeoutMs: number, publishDiverged = false): 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, existingLocalHostId());
@@ -274,7 +281,13 @@ async function precheck(engine: BrainEngine, git: Git, sourceId: string, fetchTi
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 await divergedRefusal(git, root, sourceId, upstreamRef, oldHead, targetHead);
+ if (oldHead !== targetHead && !await isAncestor(git, root, oldHead, targetHead)) {
+ if (!publishDiverged) throw await divergedRefusal(git, root, sourceId, upstreamRef, oldHead, targetHead);
+ const localCommits = Number((await read(['rev-list', '--count', `${targetHead}..${oldHead}`])).stdout.trim()) || 0;
+ const pushed = commitAndPush({ repo: root, pushOnly: true, keepCheckout: true });
+ const plan = await precheck(engine, git, sourceId, fetchTimeoutMs);
+ return { ...plan, published: { sha: pushed.sha ?? plan.targetHead, local_commits: localCommits, integrated: pushed.integrated } };
+ }
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 };
@@ -290,7 +303,7 @@ async function divergedRefusal(git: Git, root: string, sourceId: string, upstrea
const argv = ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', root, '--json'];
const error = refusal('refresh_diverged',
`The checkout HEAD ${oldHead} is not an ancestor of ${upstreamRef} (${targetHead}); a fast-forward is impossible and nothing changed.`,
- `Publish ${local} merged with ${upstreamRef}: ${argv.map(q).join(' ')} (it merges in memory, refuses on a conflict and never moves the checkout), then retry gbrain sources refresh ${sourceId}. Ask the user first, because it pushes those commits (git -C ${q(root)} log --stat ${upstreamRef}..HEAD lists them). gbrain sources reclone ${sourceId} replaces the checkout instead and drops them.`);
+ `Publish ${local} merged with ${upstreamRef}: ${argv.map(q).join(' ')} (it merges in memory, refuses on a conflict and never moves the checkout), then retry gbrain sources refresh ${sourceId}. Ask the user first, because it pushes those commits (git -C ${q(root)} log --stat ${upstreamRef}..HEAD lists them). gbrain sources reclone ${sourceId} replaces the checkout instead and drops them. To let every refresh publish a diverged checkout this way on its own, the user can run gbrain config set ${REFRESH_PUBLISH_DIVERGED_KEY} true.`);
error.fix = { argv, consent: [], actor: 'user', ask_user: true, requires_exclusive: false,
why: `HEAD has ${local} that ${upstreamRef} lacks while ${upstreamRef} moved on; pushing HEAD merged with it makes HEAD an ancestor of the upstream, so the refresh can fast-forward.`,
user_message: `The checkout of source ${sourceId} has ${local} that were never pushed while its remote moved on. Push them, merged with the remote, so gbrain can bring the checkout up to date? Conflicting files stop the push and change nothing.`,
@@ -438,9 +451,11 @@ export async function refreshWorktree(engine: BrainEngine, sourceId: string, opt
async function refreshOnce(engine: BrainEngine, sourceId: string, opts: RefreshOptions, fetchTimeoutMs: number, waitDrainMs: number): Promise<WorktreeRefreshResult> {
return withGit(async git => {
- const plan = await precheck(engine, git, sourceId, fetchTimeoutMs);
+ const publishDiverged = !opts.dryRun && isTruthy(await engine.getConfig(REFRESH_PUBLISH_DIVERGED_KEY));
+ const plan = await precheck(engine, git, sourceId, fetchTimeoutMs, publishDiverged);
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 };
+ target_head: plan.targetHead, upstream_ref: plan.upstreamRef, preserved_uncommitted: plan.preserved, incoming_files: plan.incoming,
+ ...(plan.published ? { published: plan.published } : {}) };
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) {
@@ -483,7 +498,8 @@ async function refreshOnce(engine: BrainEngine, sourceId: string, opts: RefreshO
const merged = await fenceAndMerge(engine, git, sourceId, plan, row, opts.hooks);
await opts.hooks?.boundary?.('syncing', merged);
const sync = await syncMembers(engine, git, merged, plan.root);
- return finished(await readRefresh(engine, row.id), sync, plan.preserved);
+ const result = finished(await readRefresh(engine, row.id), sync, plan.preserved);
+ return plan.published ? { ...result, published: plan.published } : result;
} finally { await refreshLock.release(); }
});
}
diff --git a/test/e2e/worktree-refresh-postgres.test.ts b/test/e2e/worktree-refresh-postgres.test.ts
index 4d70b235bc..10927dda53 100644
--- a/test/e2e/worktree-refresh-postgres.test.ts
+++ b/test/e2e/worktree-refresh-postgres.test.ts
@@ -6,4 +6,5 @@ await registerPostgresTests(
() => import('../persistence-worktree-refresh.test.ts'),
() => import('../persistence-worktree-refresh-restart.test.ts'),
() => import('../worktree-refresh-orphan-7679.test.ts'),
+ () => import('../refresh-publish-diverged-7686.test.ts'),
);
diff --git a/test/refresh-publish-diverged-7686.test.ts b/test/refresh-publish-diverged-7686.test.ts
new file mode 100644
index 0000000000..41b5f4c171
--- /dev/null
+++ b/test/refresh-publish-diverged-7686.test.ts
@@ -0,0 +1,142 @@
+/**
+ * #7686: an opt-in refresh publishes a diverged managed checkout before it
+ * fast-forwards.
+ *
+ * Protects: with `sources.refresh_publish_diverged` on (standing consent, default
+ * off) a refresh of a checkout that has local commits while its upstream moved
+ * on pushes HEAD merged with the upstream in memory (the keep-checkout publish,
+ * which never moves the checkout), then fast-forwards, keeping the local commits;
+ * with the setting off it refuses `refresh_diverged` as before; a conflicting path
+ * refuses `integrate_conflict` naming the path and changes nothing; a dry run never
+ * publishes.
+ * Regression it catches: a refresh that pushes local commits without the
+ * setting, one that moves the checkout or drops the local commits while
+ * publishing, and one that pushes or fences anything when the merge conflicts.
+ * Seams: none; a real bare remote, a pushing clone and the managed checkout.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';
+import { runSourcesRefresh } from '../src/commands/sources-refresh.ts';
+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';
+import { REFRESH_PUBLISH_DIVERGED_KEY, refreshWorktree } from '../src/core/persistence/worktree-refresh.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { git, page, withRefreshFixture, type RefreshFixture } from './helpers/worktree-refresh-fixture.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) if (engine.kind === 'pglite') await engine.disconnect();
+ await closePostgres?.();
+});
+
+const each = async (fn: (f: RefreshFixture) => Promise<void>) => {
+ for (const engine of engines) {
+ await withRefreshFixture(engine, async f => {
+ try { await fn(f); } finally { await engine.unsetConfig(REFRESH_PUBLISH_DIVERGED_KEY); }
+ });
+ }
+};
+const refusedWith = async (promise: Promise<unknown>, code: string) => {
+ const error = await promise.then(() => null, e => e as { code?: string; message?: string; suggestion?: string; detail?: string });
+ expect(error, `expected refusal ${code}`).not.toBeNull();
+ expect(error!.code).toBe(code);
+ return error!;
+};
+const remoteHead = (f: RefreshFixture) => git(f.root, 'ls-remote', 'origin', 'refs/heads/main').split('\t')[0];
+/** The upstream moves on while the managed checkout gains a local commit: a diverged checkout. */
+function diverge(f: RefreshFixture, local = { path: 'beta/local.md', content: page('Local', 'A local commit nobody pushed.') }): string {
+ f.push('alpha/two.md', page('Alpha two', 'Upstream side.'));
+ git(f.root, 'config', 'user.name', 'Example'); git(f.root, 'config', 'user.email', '[email protected]');
+ writeFileSync(join(f.root, local.path), local.content);
+ git(f.root, 'add', local.path); git(f.root, 'commit', '-qm', 'local only');
+ return f.head();
+}
+
+test('the setting is a registered knob, default off', () => {
+ expect(REFRESH_PUBLISH_DIVERGED_KEY).toBe('sources.refresh_publish_diverged');
+ expect(KNOWN_CONFIG_KEYS).toContain(REFRESH_PUBLISH_DIVERGED_KEY);
+ expect(KNOWN_CONFIG_KEYS).toEqual(expect.arrayContaining(['sources.refresh_fetch_timeout_ms', 'sources.refresh_drain_wait_ms']));
+});
+
+test('setting on: a diverged refresh publishes the local commits merged with the upstream, then fast-forwards and keeps them', () => each(async f => {
+ const local = diverge(f);
+ await f.engine.setConfig(REFRESH_PUBLISH_DIVERGED_KEY, 'true');
+ const done = await refreshWorktree(f.engine, f.alpha);
+ expect(done).toMatchObject({ status: 'completed', old_head: local, published: { local_commits: 1, integrated: 1 } });
+ expect(done.published!.sha).toBe(remoteHead(f));
+ expect(done.target_head).toBe(done.published!.sha);
+ expect(f.head()).toBe(done.published!.sha);
+ git(f.root, 'merge-base', '--is-ancestor', local, 'HEAD');
+ expect(readFileSync(join(f.root, 'alpha/two.md'), 'utf8')).toContain('Upstream side.');
+ expect(readFileSync(join(f.root, 'beta/local.md'), 'utf8')).toContain('A local commit nobody pushed.');
+ expect(await f.lastCommit(f.alpha)).toBe(done.published!.sha);
+ expect(await f.lastCommit(f.beta)).toBe(done.published!.sha);
+}), 120_000);
+
+test('setting on: the text result names the publish', () => each(async f => {
+ diverge(f);
+ await f.engine.setConfig(REFRESH_PUBLISH_DIVERGED_KEY, 'on');
+ const out: string[] = [];
+ const log = console.log;
+ _resetCliExitVerdictForTests();
+ console.log = (line: string) => { out.push(line); };
+ try { await runSourcesRefresh(f.engine, [f.alpha]); } finally { console.log = log; _resetCliExitVerdictForTests(); process.exitCode = 0; }
+ expect(out.join('\n')).toContain('Published 1 local commit(s) merged with 1 upstream commit(s) as ');
+ expect(out.join('\n')).toContain('Refresh completed');
+}), 120_000);
+
+test('setting off (unset or false): the refresh refuses refresh_diverged, pushes nothing and names the setting', () => each(async f => {
+ const local = diverge(f);
+ const remote = remoteHead(f);
+ for (const value of [null, 'false']) {
+ if (value !== null) await f.engine.setConfig(REFRESH_PUBLISH_DIVERGED_KEY, value);
+ const error = await refusedWith(refreshWorktree(f.engine, f.alpha), 'refresh_diverged');
+ expect(error.suggestion).toContain('gbrain config set sources.refresh_publish_diverged true');
+ expect(remoteHead(f)).toBe(remote);
+ expect(f.head()).toBe(local);
+ expect(await f.refreshRows()).toEqual([]);
+ }
+}), 120_000);
+
+test('setting on: a conflicting path refuses integrate_conflict naming it, and nothing is pushed, fenced or moved', () => each(async f => {
+ const local = diverge(f, { path: 'alpha/two.md', content: page('Alpha two', 'Local side.') });
+ const remote = remoteHead(f);
+ const lastAlpha = await f.lastCommit(f.alpha);
+ await f.engine.setConfig(REFRESH_PUBLISH_DIVERGED_KEY, 'true');
+ const error = await refusedWith(refreshWorktree(f.engine, f.alpha), 'integrate_conflict') as { detail?: string; suggestion?: string };
+ expect(JSON.parse(error.detail!).paths).toEqual(['alpha/two.md']);
+ expect(error.suggestion).toContain('--keep-checkout');
+ expect(error.suggestion).toContain('--resolve alpha/two.md=ours|theirs');
+ expect(remoteHead(f)).toBe(remote);
+ expect(f.head()).toBe(local);
+ expect(readFileSync(join(f.root, 'alpha/two.md'), 'utf8')).toContain('Local side.');
+ expect(git(f.root, 'status', '--porcelain', '--untracked-files=no')).toBe('');
+ expect(await f.refreshRows()).toEqual([]);
+ expect(await f.lastCommit(f.alpha)).toBe(lastAlpha);
+}), 120_000);
+
+test('setting on: a dry run publishes nothing and still refuses refresh_diverged', () => each(async f => {
+ const local = diverge(f);
+ const remote = remoteHead(f);
+ await f.engine.setConfig(REFRESH_PUBLISH_DIVERGED_KEY, 'true');
+ await refusedWith(refreshWorktree(f.engine, f.alpha, { dryRun: true }), 'refresh_diverged');
+ expect(remoteHead(f)).toBe(remote);
+ expect(f.head()).toBe(local);
+}), 120_000);