Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): git-durability push probe passes a moved remote the Git effect publishes itself

garrytanad6751547315
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 622908d34e..dcfd3be9b9 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1197,6 +1197,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// Side-unknown file_drift holds and the pending-import fix (GBRA-133). `since` is stamped at the merge slot.
{ since: '0.60.417.0', id: 'legacy_validate_stamp_drift', text: 'A page an older gbrain imported, whose database copy carries the v0.13.1 grandfather stamp `validate: false` that its file lacks, is no longer held `file_drift` when its file is committed again: sync compares and imports such a file the way a page write already did (#6429), so the first sync records the page and a later commit imports, and the page keeps the stamp. A `file_drift` hold that has no import record now says it cannot tell whether the file or the database changed, instead of saying the page changed in the database. A hold already open stays held, because its baseline commit has moved past the edit: preview it with `gbrain repair file-drift --source <source> --held --side unknown --prefer file` (writes nothing) and apply the set the user approves.' },
{ since: '0.60.417.0', id: 'pending_import_owner_safe_fix', text: 'A write refused because its page\'s file holds a committed Git change sync has not imported yet (`pending_import`) no longer tells the caller to run `gbrain sync --source <source> --no-pull`. A running sync owner (`gbrain serve`, autopilot or a sync job) imports the commit on its own, and a second sync beside it competes with that owner. The fix of every such refusal, `put_page` included, is now the read-only `gbrain sync status --source <source> --json`, and the frozen `remember` refusal carries that fix too.' },
+ // GBRA-133 wave 6 (#7402 explicit request_id facts replay; git-durability push probe on a moved remote). `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'A managed facts write retried with the caller\'s own `request_id` now always returns that request\'s recorded outcome, a retained file refusal included; only a page-triggered or re-admitted facts job rechecks a refusal once its hold clears (#7402).' },
+ { since: 'TBD', text: '`gbrain sources writer git-durability <source> --enable` no longer refuses with `git_push_unavailable` when the remote branch has commits the checkout lacks (`[rejected] (fetch first)` or `(non-fast-forward)` from the read-only push probe): the Git effect publishes that case itself by merging the remote commits in memory, without pulling into the checkout, so enable succeeds and reports `push_probe.remote_moved: true`. Authentication, permission, protected-branch and unreachable-remote failures are still refused.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.ts
index 78e9132fc5..024ab19fa7 100644
--- a/src/core/persistence/effect-git.ts
+++ b/src/core/persistence/effect-git.ts
@@ -316,7 +316,7 @@ export async function gitRootAhead(root: string, signal?: AbortSignal): Promise<
}
/** Git's refusal of a push because the remote branch moved (LC_ALL=C keeps it untranslated). */
-const NON_FAST_FORWARD = /\[rejected\][^\n]*\((?:non-fast-forward|fetch first)\)/;
+export const NON_FAST_FORWARD = /\[rejected\][^\n]*\((?:non-fast-forward|fetch first)\)/;
/**
* Push the current branch to its tracking remote. A plain push is tried first (idempotent, cannot import remote
diff --git a/src/core/persistence/git-durability-administration.ts b/src/core/persistence/git-durability-administration.ts
index eed0fa9b54..a4a94dd63f 100644
--- a/src/core/persistence/git-durability-administration.ts
+++ b/src/core/persistence/git-durability-administration.ts
@@ -21,6 +21,7 @@ import { execFileBounded } from '../bounded-child-exec.ts';
import { classifyGitCheckout } from '../git-checkout.ts';
import { durableSsrfFlags, GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS } from '../git-remote.ts';
import { gitChildEnv } from '../git-env.ts';
+import { NON_FAST_FORWARD } from './effect-git.ts';
import { ensureGbrainHome, resolveGbrainHome } from '../gbrain-home.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
@@ -100,14 +101,22 @@ export async function inspectDurabilityCheckout(root: string): Promise<{ branch:
return { branch, remote: tracked ? remote.stdout.trim() : null, merge: tracked ? merge.stdout.trim() : null };
}
-export type PushProbe = { ok: true; skipped?: 'no_tracking_remote' } | { ok: false; reason: 'auth' | 'protected' | 'unreachable' | 'other'; detail: string };
+export type PushProbe = { ok: true; skipped?: 'no_tracking_remote'; remote_moved?: true; detail?: string }
+ | { ok: false; reason: 'auth' | 'protected' | 'unreachable' | 'other'; detail: string };
-/** `git push --dry-run` to the branch's tracking remote: proves push authority without a commit; the same refspec the Git effect pushes. */
+/**
+ * `git push --dry-run` to the branch's tracking remote: proves push authority without a commit; the same refspec the Git effect pushes.
+ * GBRA-133: a rejection only because the remote moved (`fetch first`, `non-fast-forward`) comes after the remote accepted
+ * the push connection, and the Git effect publishes that case itself (it merges the remote commits in memory and pushes,
+ * #7010, `pushGitRoot`), so the probe passes it with `remote_moved`. Auth, protected-branch and unreachable refusals still fail.
+ */
export async function probeDurabilityPush(root: string, checkout: { remote: string | null; merge: string | null }, redact: (s: string) => string): Promise<PushProbe> {
if (!checkout.remote || !checkout.merge) return { ok: true, skipped: 'no_tracking_remote' };
const push = await git(root, ['push', ...GIT_SSRF_SUBCOMMAND_FLAGS, '--dry-run', '--', checkout.remote, `HEAD:${checkout.merge}`], true);
if (push.code === 0) return { ok: true };
const detail = redact(`${push.stderr}\n${push.stdout}`).replace(/\s+/g, ' ').trim().slice(0, 200);
+ if (NON_FAST_FORWARD.test(push.stderr)) return { ok: true, remote_moved: true,
+ detail: 'the remote branch has commits this checkout lacks; the Git effect merges them in memory and pushes the merge (#7010) without pulling into the checkout, and holds a same-file conflict as integrate_conflict for the user to choose' };
const low = detail.toLowerCase();
const reason = low.includes('authentication') || low.includes('403') || low.includes('permission') || low.includes('could not read') ? 'auth'
: low.includes('protected') || low.includes('pre-receive') || low.includes('hook declined') ? 'protected'
diff --git a/test/git-durability-probe-remote-moved-gbra133.test.ts b/test/git-durability-probe-remote-moved-gbra133.test.ts
new file mode 100644
index 0000000000..6324e8fefc
--- /dev/null
+++ b/test/git-durability-probe-remote-moved-gbra133.test.ts
@@ -0,0 +1,155 @@
+/**
+ * GBRA-133: the read-only push probe of `gbrain sources writer git-durability --enable` refused a checkout whose
+ * remote branch had moved since the last fetch (`[rejected] ... (fetch first)` or `(non-fast-forward)`), so enable
+ * failed with git_push_unavailable even though the Git effect publishes that case itself: it merges the remote commits
+ * in memory and pushes the merge without moving the checkout (#7010, `pushGitRoot`). The probe now passes a
+ * remote-moved rejection (`remote_moved`), and auth, protected-branch and unreachable failures stay refused.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
+import { probeDurabilityPush } from '../src/core/persistence/git-durability-administration.ts';
+import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { gitAsync } from './helpers/git-publication.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';
+
+let engine: PGLiteEngine;
+const homes: string[] = [];
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); for (const home of homes) rmSync(home, { recursive: true, force: true }); });
+
+async function isolated<T>(run: (home: string) => Promise<T>): Promise<T> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-probe-moved-')); homes.push(home);
+ try {
+ return await withEnv({ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,
+ GBRAIN_GIT_ALLOW_FILE_TRANSPORT: '1' }, async () => { await registerLocalWriter(engine, 'cli'); return run(home); });
+ } finally { await disposePersistenceConsumer(engine); }
+}
+
+async function identity(root: string): Promise<void> {
+ await gitAsync(root, 'config', 'user.name', 'Example Writer');
+ await gitAsync(root, 'config', 'user.email', '[email protected]');
+}
+
+/** A checkout tracking a bare remote, and a second clone of that remote standing in for another writer. */
+async function checkoutWithRemote(home: string): Promise<{ root: string; remote: string; other: string }> {
+ const id = randomUUID().slice(0, 8);
+ const root = join(home, `root-${id}`); mkdirSync(root);
+ await gitAsync(root, 'init', '-q', '-b', 'main'); await identity(root);
+ writeFileSync(join(root, 'initial.md'), 'Initial\n');
+ await gitAsync(root, 'add', '-A'); await gitAsync(root, 'commit', '-q', '-m', 'Initial');
+ const remote = join(home, `remote-${id}.git`); mkdirSync(remote);
+ await gitAsync(remote, 'init', '-q', '--bare');
+ await gitAsync(root, 'remote', 'add', 'origin', remote); await gitAsync(root, 'push', '-q', '-u', 'origin', 'main');
+ const other = join(home, `other-${id}`);
+ await gitAsync(home, 'clone', '-q', '-b', 'main', remote, other); await identity(other);
+ return { root, remote, other };
+}
+
+async function commit(root: string, file: string): Promise<void> {
+ writeFileSync(join(root, file), `${file}\n`);
+ await gitAsync(root, 'add', file); await gitAsync(root, 'commit', '-q', '-m', file);
+}
+
+async function moveRemote(other: string): Promise<void> {
+ await commit(other, 'remote-only.md');
+ await gitAsync(other, 'push', '-q', 'origin', 'main');
+}
+
+const tracking = { remote: 'origin', merge: 'refs/heads/main' };
+const same = (text: string) => text;
+
+/** A `git` earlier on PATH that answers `push` with the given stderr and exit 1, and hands every other command to the real git. */
+function stubPush(home: string, stderr: string): string {
+ const realGit = Bun.which('git')!;
+ const dir = join(home, `stub-${randomUUID().slice(0, 8)}`); mkdirSync(dir);
+ const script = join(dir, 'git');
+ writeFileSync(script, `#!/bin/sh\nfor a in "$@"; do if [ "$a" = push ]; then printf '%s\\n' '${stderr.replace(/'/g, "'\\''")}' >&2; exit 1; fi; done\nexec '${realGit}' "$@"\n`);
+ chmodSync(script, 0o755);
+ return `${dir}:${process.env.PATH ?? ''}`;
+}
+
+describe('GBRA-133 git-durability push probe: a moved remote is publishable', () => {
+ test('the remote moves after a local commit: the probe passes remote_moved, enable succeeds, and nothing is pulled into the checkout', () => isolated(async home => {
+ const { root, other } = await checkoutWithRemote(home);
+ await commit(root, 'local.md');
+ await moveRemote(other);
+ const head = (await gitAsync(root, 'rev-parse', 'HEAD')).trim();
+
+ expect(await probeDurabilityPush(root, tracking, same)).toMatchObject({ ok: true, remote_moved: true, detail: expect.stringContaining('merges them in memory') });
+
+ const sourceId = `vault-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await claimWorktree(engine, sourceId, root, localHostId());
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ try {
+ const preview = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, dry_run: true });
+ expect(preview).toMatchObject({ dry_run: true, push_probe: { ok: true, remote_moved: true } });
+ const applied = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, ...await reviewedWriterIntent(engine, 'writer_git_durability') });
+ expect(applied).toMatchObject({ applied: true, git_durability: { before: null, after: 'enabled' }, push_probe: { ok: true, remote_moved: true } });
+ expect((await getWorktreeBinding(engine, sourceId, localHostId()))!.git_durability).toBe('enabled');
+ } finally {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ // A dry-run probe never fetches into, merges into or moves the checkout.
+ expect((await gitAsync(root, 'rev-parse', 'HEAD')).trim()).toBe(head);
+ expect((await gitAsync(root, 'ls-files')).split('\n')).not.toContain('remote-only.md');
+ }), 120_000);
+
+ test('a diverged branch whose remote commits were already fetched (non-fast-forward) passes the same way', () => isolated(async home => {
+ const { root, other } = await checkoutWithRemote(home);
+ await moveRemote(other);
+ await gitAsync(root, 'fetch', '-q', 'origin');
+ await commit(root, 'local.md');
+ expect(await probeDurabilityPush(root, tracking, same)).toMatchObject({ ok: true, remote_moved: true });
+ }), 120_000);
+
+ test('an up-to-date checkout probes plain ok, and no tracking remote is still skipped', () => isolated(async home => {
+ const { root } = await checkoutWithRemote(home);
+ await commit(root, 'local.md');
+ expect(await probeDurabilityPush(root, tracking, same)).toEqual({ ok: true });
+ expect(await probeDurabilityPush(root, { remote: null, merge: null }, same)).toEqual({ ok: true, skipped: 'no_tracking_remote' });
+ }), 120_000);
+
+ test('a missing remote stays refused, and enable records nothing', () => isolated(async home => {
+ const { root, remote } = await checkoutWithRemote(home);
+ await commit(root, 'local.md');
+ rmSync(remote, { recursive: true, force: true });
+ const probe = await probeDurabilityPush(root, tracking, same);
+ expect(probe.ok).toBe(false);
+ expect(probe).not.toHaveProperty('remote_moved');
+
+ const sourceId = `vault-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await claimWorktree(engine, sourceId, root, localHostId());
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ try {
+ const refused = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, ...await reviewedWriterIntent(engine, 'writer_git_durability') })
+ .then(() => null, (error: unknown) => error as { code?: string });
+ expect(refused?.code).toBe('git_push_unavailable');
+ expect((await getWorktreeBinding(engine, sourceId, localHostId()))!.git_durability).not.toBe('enabled');
+ } finally {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ }), 120_000);
+
+ test.each([
+ ['auth', 'fatal: Authentication failed for the example remote'],
+ ['auth', 'remote: Permission to example/brain.git denied to example-bot. The requested URL returned error: 403'],
+ ['protected', ' ! [remote rejected] HEAD -> main (protected branch hook declined)'],
+ ['unreachable', 'fatal: unable to access the example remote: Could not resolve host: git.example.invalid'],
+ ] as const)('a refusal classified %s stays refused, never read as a moved remote', (reason, stderr) => isolated(async home => {
+ const { root } = await checkoutWithRemote(home);
+ await commit(root, 'local.md');
+ const probe = await withEnv({ PATH: stubPush(home, stderr) }, () => probeDurabilityPush(root, tracking, same));
+ expect(probe).toMatchObject({ ok: false, reason });
+ expect(probe).not.toHaveProperty('remote_moved');
+ }), 120_000);
+});