Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(refresh): a failing branch or remote read is git_unavailable; the durability-probe test runs real git

garrytan8e14a185a150
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index e6f6b0277d..4f0ae6b458 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -379,8 +379,9 @@ this anchor (`--json` puts them in one object on stdout); the command exits 1.
| --- | --- | --- | --- |
| <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="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. | 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. `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). |
diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.ts
index 752b0453b5..462a5c049f 100644
--- a/src/core/persistence/worktree-refresh.ts
+++ b/src/core/persistence/worktree-refresh.ts
@@ -24,6 +24,7 @@ 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 { classifyGitCheckout } from '../git-checkout.ts';
import type { Action } from '../agent-output.ts';
import { opError, OperationError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
@@ -203,16 +204,27 @@ async function precheck(engine: BrainEngine, git: Git, sourceId: string, fetchTi
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();
+ if (classifyGitCheckout(root) === 'not_git') throw refusal('refresh_no_upstream',
+ `The checkout ${root} is not a Git checkout, so there is no upstream to fast-forward to; gbrain never initializes Git on its own.`,
+ 'Nothing to refresh: only a Git checkout whose branch tracks an upstream can be fast-forwarded, and turning this directory into one is the user\'s call.');
+ const read = async (args: string[], ...expected: number[]) => {
+ const out = await git(['-C', root, ...args]);
+ if (out.code === 0 || expected.includes(out.code)) return out;
+ throw opError('git_unavailable', `git ${args.join(' ')} ${out.timedOut ? 'did not finish within its bound or could not start'
+ : `failed (${out.stderr.trim().split('\n')[0] || `exit ${out.code}`})`}, so the checkout's branch, upstream and remote are unknown; nothing changed.`,
+ `Check that git works in the checkout (git -C ${q(root)} status), then retry gbrain sources refresh ${sourceId}.`,
+ { fix: readFix('Git prints why it cannot read this checkout; read-only.', { argv: ['git', '-C', root, 'status'] }) });
+ };
+ const branch = (await read(['symbolic-ref', '--quiet', '--short', 'HEAD'], 1)).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';
+ const remote = (await read(['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();
+ const remote = (await read(['config', '--get', `branch.${branch}.remote`], 1)).stdout.trim();
+ const merge = (await read(['config', '--get', `branch.${branch}.merge`], 1)).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',
diff --git a/test/bounded-child-exec.test.ts b/test/bounded-child-exec.test.ts
index e1ad5378df..907ee14c11 100644
--- a/test/bounded-child-exec.test.ts
+++ b/test/bounded-child-exec.test.ts
@@ -1,11 +1,23 @@
import { afterAll, expect, test } from 'bun:test';
-import { mkdtempSync, rmSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { execFileBounded, isDurabilityHardenedAsync } from '../src/core/brain-repo-durability.ts';
const dir = mkdtempSync(join(tmpdir(), 'gbrain-bounded-exec-'));
afterAll(() => rmSync(dir, { recursive: true, force: true }));
+// Hardened two ways, so losing either probe's output reads as "not hardened": one hook sits in
+// core.hooksPath, the other in a separate git directory that `<checkout>/.git/hooks` does not reach.
+const hooksPathRepo = join(dir, 'hooks-path'), separateGitDirRepo = join(dir, 'separate-git-dir');
+const hook = '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\nexit 0\n';
+execFileSync('git', ['init', '-q', hooksPathRepo]);
+execFileSync('git', ['-C', hooksPathRepo, 'config', 'core.hooksPath', 'custom-hooks']);
+mkdirSync(join(hooksPathRepo, 'custom-hooks'));
+writeFileSync(join(hooksPathRepo, 'custom-hooks', 'post-commit'), hook, { mode: 0o755 });
+execFileSync('git', ['init', '-q', `--separate-git-dir=${join(dir, 'separate.git')}`, separateGitDirRepo]);
+mkdirSync(join(dir, 'separate.git', 'hooks'), { recursive: true });
+writeFileSync(join(dir, 'separate.git', 'hooks', 'post-commit'), hook, { mode: 0o755 });
/**
* Starts short-lived children whose first exit callback re-enters the event
@@ -50,6 +62,14 @@ test('bounded execution settles by its deadline when the runtime drops child eve
test('the persistence durability probe settles when the runtime drops child events', async () => {
const probes = await within(20_000, nestedTickDuring(() => Array.from({ length: 20 }, () => isDurabilityHardenedAsync(dir))));
expect(probes).toEqual(Array(20).fill(false));
+ const repos = Array.from({ length: 20 }, (_, i) => i % 2 ? separateGitDirRepo : hooksPathRepo);
+ expect(await Promise.all([hooksPathRepo, separateGitDirRepo].map(repo => isDurabilityHardenedAsync(repo)))).toEqual([true, true]);
+ const outcomes = await within(20_000, nestedTickDuring(() => repos.map(repo => isDurabilityHardenedAsync(repo).catch((error: Error) => error))));
+ expect(outcomes).not.toBe('unsettled');
+ for (const outcome of outcomes as Array<boolean | Error>) {
+ if (outcome instanceof Error) expect(outcome).toMatchObject({ code: 'git_unavailable', suggestion: expect.stringContaining('(ETIMEDOUT)') });
+ else expect(outcome).toBe(true);
+ }
}, 30_000);
test('bounded execution keeps execFile exit codes and stdout', async () => {
diff --git a/test/persistence-worktree-refresh.test.ts b/test/persistence-worktree-refresh.test.ts
index 371a95b2f7..3a7ab7a52a 100644
--- a/test/persistence-worktree-refresh.test.ts
+++ b/test/persistence-worktree-refresh.test.ts
@@ -16,8 +16,10 @@
* drained, fenced and merged points; no production behavior is replaced.
*/
import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
-import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -38,6 +40,7 @@ import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
import { git, page, withRefreshFixture, type RefreshFixture } from './helpers/worktree-refresh-fixture.ts';
const backends = testBackends();
@@ -118,6 +121,58 @@ test('3. a fetch killed by its bound leaves no refresh row and HEAD unchanged',
expect(f.head()).toBe(head);
}), 120_000);
+/** Runs `fn` with a PATH git that fails (stderr line, then `code`) whenever an argument equals `token`; every other command is the real git. */
+async function withFailingGit<T>(token: string, code: number, fn: () => Promise<T>): Promise<T> {
+ const bin = mkdtempSync(join(tmpdir(), 'gbrain-failing-git-'));
+ const realGit = execFileSync('sh', ['-c', 'command -v git'], { encoding: 'utf8' }).trim();
+ writeFileSync(join(bin, 'git'), `#!/bin/sh
+for a in "$@"; do if [ "$a" = "${token}" ]; then echo "fatal: injected failure of ${token}" >&2; exit ${code}; fi; done
+exec ${realGit} "$@"
+`, { mode: 0o755 });
+ try { return await withEnv({ PATH: `${bin}:${process.env.PATH}` }, fn); } finally { rmSync(bin, { recursive: true, force: true }); }
+}
+const refusedOnGit = async (f: RefreshFixture, token: string, code: number, command: string) => {
+ const head = f.head();
+ const error = await withFailingGit(token, code, () => refusedWith(refreshWorktree(f.engine, f.alpha), 'git_unavailable'));
+ expect(error.message).toContain(`git ${command} failed (fatal: injected failure of ${token})`);
+ expect(error.suggestion).toContain(`gbrain sources refresh ${f.alpha}`);
+ expect(await f.refreshRows()).toEqual([]);
+ expect(f.head()).toBe(head);
+};
+
+test('3b. a failing git symbolic-ref is a git failure, not a detached HEAD', () => each(async f => {
+ f.push('alpha/two.md', page('Alpha two', 'Upstream.'));
+ await refusedOnGit(f, 'symbolic-ref', 128, 'symbolic-ref --quiet --short HEAD');
+ git(f.root, 'checkout', '-q', '--detach');
+ const detached = await refusedWith(refreshWorktree(f.engine, f.alpha), 'refresh_no_upstream');
+ expect(detached.message).toContain('(detached HEAD)');
+}), 120_000);
+
+test('3c. a failing git remote is a git failure, not a checkout without remotes', () => each(async f => {
+ git(f.root, 'branch', '--unset-upstream');
+ await refusedOnGit(f, 'remote', 128, 'remote');
+ const noUpstream = await refusedWith(refreshWorktree(f.engine, f.alpha), 'refresh_no_upstream');
+ expect(noUpstream.suggestion).toContain('branch --set-upstream-to origin/main');
+}), 120_000);
+
+test('3d. a failing git config --get of the branch remote or merge is a git failure, not an unset key', () => each(async f => {
+ const target = f.push('alpha/two.md', page('Alpha two', 'Upstream.'));
+ await refusedOnGit(f, 'branch.main.remote', 3, 'config --get branch.main.remote');
+ await refusedOnGit(f, 'branch.main.merge', 3, 'config --get branch.main.merge');
+ expect((await refreshWorktree(f.engine, f.alpha)).status).toBe('completed');
+ expect(f.head()).toBe(target);
+}), 120_000);
+
+test('3e. a checkout that is not a Git checkout is refresh_no_upstream naming that, not a detached HEAD or a git failure', () => each(async f => {
+ renameSync(join(f.root, '.git'), join(f.dir, 'moved.git'));
+ try {
+ const error = await refusedWith(refreshWorktree(f.engine, f.alpha), 'refresh_no_upstream');
+ expect(error.message).toContain(`The checkout ${f.root} is not a Git checkout`);
+ expect(error.suggestion).toContain('Nothing to refresh');
+ expect(await f.refreshRows()).toEqual([]);
+ } finally { renameSync(join(f.dir, 'moved.git'), join(f.root, '.git')); }
+}), 120_000);
+
test('4. a diverged checkout is refused with no row and HEAD unchanged', () => each(async f => {
f.push('alpha/two.md', page('Alpha two', 'Upstream side.'));
writeFileSync(join(f.root, 'beta/local.md'), page('Local', 'A local commit nobody pushed.'));