Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes (the rewrite guard reads the upstream before this fetch, #7686)
garrytan813f3212a107
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8d5b44c2c2..9eeb374bfe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -45,7 +45,7 @@ gbrain config set sources.refresh_publish_diverged true### 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 the keep-checkout publish (`gbrain git commit-push --push-only --keep-checkout` in a bounded child, never on the PGLite owner's event loop) for a diverged checkout (after refusing `refresh_dirty` first when an uncommitted edit touches a file the upstream changed), re-fetches and continues; it refuses `refresh_diverged` instead when the checkout holds a commit the upstream held before (its remote-tracking reflog or a completed refresh's target) but no longer contains, or when neither record exists; the result carries `published` (with any quarantined or superseded paths, which the text output names), and a refusal after the publish says the remote already holds the local commits. The `refresh_diverged` suggestion names the setting.+- `src/core/persistence/worktree-refresh.ts`: when `sources.refresh_publish_diverged` is on and the run is not a dry run, the precheck runs the keep-checkout publish (`gbrain git commit-push --push-only --keep-checkout` in a bounded child, never on the PGLite owner's event loop) for a diverged checkout (after refusing `refresh_dirty` first when an uncommitted edit touches a file the upstream changed), re-fetches and continues; it refuses `refresh_diverged` instead when the checkout holds a commit the upstream held before (the remote-tracking ref before this fetch, its reflog, or a completed refresh's target for the same upstream) but no longer contains, or when neither record exists; the result carries `published` (with any quarantined or superseded paths, which the text output names), and a refusal after the publish says the remote already holds the local commits. 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/guides/troubleshooting.md`, `docs/guides/shared-checkout-git.md`, `docs/architecture/canonical-writers.md` and its census.diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.tsindex 1588335b07..6e94402290 100644--- a/src/core/persistence/worktree-refresh.ts+++ b/src/core/persistence/worktree-refresh.ts@@ -20,7 +20,7 @@* so status can say who holds it, and a row whose lock is free is orphaned: the* next plain refresh finishes it through the `--resume` path before refreshing.*/-import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';import { hostname } from 'node:os';import { join } from 'node:path';import type { BrainEngine } from '../engine.ts';@@ -273,6 +273,17 @@ async function precheck(engine: BrainEngine, git: Git, sourceId: string, fetchTiconst upstreamRef = upstream.stdout.trim();const remote = (await read(['config', '--get', `branch.${branch}.remote`], 1)).stdout.trim();const merge = (await read(['config', '--get', `branch.${branch}.merge`], 1)).stdout.trim();+ const heldUpstream = new Set<string>();+ if (publishDiverged) {+ const upstreamFull = (await read(['rev-parse', '--symbolic-full-name', '@{upstream}'])).stdout.trim();+ let reflog = '';+ try { reflog = readFileSync((await read(['rev-parse', '--path-format=absolute', '--git-path', `logs/${upstreamFull}`])).stdout.trim(), 'utf8'); } catch { /* no reflog */ }+ const rows = await engine.executeRaw<{ target_head: string }>(`SELECT target_head FROM persistence_worktree_refreshes WHERE worktree_id=$1::uuid AND upstream_ref=$2 AND state='completed' ORDER BY created_at DESC LIMIT 100`, [binding.worktree_id, upstreamRef]);+ for (const sha of [(await read(['rev-parse', '--verify', '-q', '@{upstream}^{commit}'], 1)).stdout.trim(),+ ...reflog.split('\n').slice(-1000).flatMap(line => line.split(' ').slice(0, 2)), ...rows.map(r => r.target_head)]) {+ if (/^[0-9a-f]{40,64}$/.test(sha) && !/^0+$/.test(sha)) heldUpstream.add(sha);+ }+ }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',@@ -286,10 +297,6 @@ async function precheck(engine: BrainEngine, git: Git, sourceId: string, fetchTi`git -C ${q(root)} fetch ${remote || 'origin'}, then gbrain sources refresh ${sourceId}`);if (oldHead !== targetHead && !await isAncestor(git, root, oldHead, targetHead)) {if (!publishDiverged) throw await divergedRefusal(git, root, sourceId, upstreamRef, oldHead, targetHead);- const upstreamFull = (await read(['rev-parse', '--symbolic-full-name', '@{upstream}'])).stdout.trim();- const heldUpstream = new Set([...(await read(['log', '-g', '-n', '1000', '--format=%H', upstreamFull, '--'], 128)).stdout.split('\n'),- ...(await engine.executeRaw<{ target_head: string }>(`SELECT target_head FROM persistence_worktree_refreshes WHERE worktree_id=$1::uuid AND state='completed' ORDER BY created_at DESC LIMIT 100`, [binding.worktree_id])).map(r => r.target_head)]- .map(sha => sha.trim()).filter(Boolean));const removed = (await read(['rev-list', `${targetHead}..${oldHead}`])).stdout.split('\n').map(sha => sha.trim()).find(sha => heldUpstream.has(sha));if (!heldUpstream.size || removed) throw await divergedRefusal(git, root, sourceId, upstreamRef, oldHead, targetHead, removed? `${upstreamRef} no longer contains ${removed}, which it held before: its history was rewritten (a force-push), and publishing would merge back the commits the rewrite removed.`@@ -349,7 +356,7 @@ async function divergedRefusal(git: Git, root: string, sourceId: string, upstrea`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.${rewrite ? '' : ` 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: rewrite ? `The remote of source ${sourceId} was rewritten (${rewrite}) Push this checkout's history merged with it anyway, or replace the checkout with gbrain sources reclone ${sourceId}?`+ user_message: rewrite ? `The checkout of source ${sourceId} cannot be published on its own: ${rewrite} Push this checkout's history merged with the remote anyway, or replace the checkout with gbrain sources reclone ${sourceId}?`: `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.`,docs: 'docs/guides/write-refusals.md#refresh_diverged' };return error;diff --git a/test/refresh-publish-diverged-7686.test.ts b/test/refresh-publish-diverged-7686.test.tsindex c3e6589392..442bc9c79d 100644--- a/test/refresh-publish-diverged-7686.test.ts+++ b/test/refresh-publish-diverged-7686.test.ts@@ -203,23 +203,29 @@ test('setting on: a dry run publishes nothing and still refuses refresh_divergedexpect(f.head()).toBe(local);}), 120_000);-test('setting on: an upstream rewritten by a force-push is never published; the refresh refuses refresh_diverged and the remote keeps the rewrite', () => each(async f => {- f.push('alpha/purged.md', page('Purged', 'A page the upstream later removed by rewriting history.'));- expect(await refreshWorktree(f.engine, f.alpha)).toMatchObject({ status: 'completed' });- const purged = f.head();- git(f.upstream, 'reset', '-q', '--hard', 'HEAD~1');- commitFile(f.upstream, 'alpha/two.md', page('Alpha two', 'Rewritten upstream.'));- git(f.upstream, 'push', '-q', '--force', 'origin', 'main');- const rewritten = remoteHead(f);- writeFileSync(join(f.root, 'beta/local.md'), page('Local', 'A local commit nobody pushed.'));- git(f.root, 'add', 'beta/local.md'); git(f.root, 'commit', '-qm', 'local only');- const local = f.head();- await f.engine.setConfig(REFRESH_PUBLISH_DIVERGED_KEY, 'true');- const error = await refusedWith(refreshWorktree(f.engine, f.alpha), 'refresh_diverged');- expect(error.message).toContain(`no longer contains ${purged}`);- expect(error.suggestion).not.toContain('gbrain config set');- expect(remoteHead(f)).toBe(rewritten);- expect(() => git(f.root, 'cat-file', '-e', `origin/main:alpha/purged.md`)).toThrow();- expect(f.head()).toBe(local);- expect((await f.refreshRows()).filter(r => r.state !== 'completed')).toEqual([]);-}), 120_000);+for (const [label, forget] of [['', false], [' even when the first fetch to see the upstream is the one after the rewrite', true]] as const) {+ test(`setting on: an upstream rewritten by a force-push is never published${label}; the refresh refuses refresh_diverged and the remote keeps the rewrite`, () => each(async f => {+ f.push('alpha/purged.md', page('Purged', 'A page the upstream later removed by rewriting history.'));+ expect(await refreshWorktree(f.engine, f.alpha)).toMatchObject({ status: 'completed' });+ const purged = f.head();+ if (forget) {+ rmSync(git(f.root, 'rev-parse', '--path-format=absolute', '--git-path', 'logs/refs/remotes/origin/main').trim(), { force: true });+ await f.engine.executeRaw('DELETE FROM persistence_worktree_refreshes WHERE worktree_id=$1::uuid', [f.worktreeId]);+ }+ git(f.upstream, 'reset', '-q', '--hard', 'HEAD~1');+ commitFile(f.upstream, 'alpha/two.md', page('Alpha two', 'Rewritten upstream.'));+ git(f.upstream, 'push', '-q', '--force', 'origin', 'main');+ const rewritten = remoteHead(f);+ writeFileSync(join(f.root, 'beta/local.md'), page('Local', 'A local commit nobody pushed.'));+ git(f.root, 'add', 'beta/local.md'); git(f.root, 'commit', '-qm', 'local only');+ const local = f.head();+ await f.engine.setConfig(REFRESH_PUBLISH_DIVERGED_KEY, 'true');+ const error = await refusedWith(refreshWorktree(f.engine, f.alpha), 'refresh_diverged');+ expect(error.message).toContain(`no longer contains ${purged}`);+ expect(error.suggestion).not.toContain('gbrain config set');+ expect(remoteHead(f)).toBe(rewritten);+ expect(() => git(f.root, 'cat-file', '-e', 'origin/main:alpha/purged.md')).toThrow();+ expect(f.head()).toBe(local);+ expect((await f.refreshRows()).filter(r => r.state !== 'completed')).toEqual([]);+ }), 120_000);+}