Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix(git): stop the Git tab's Update button failing on a harmless fetch race

[._.]/ Adam Eivy89d65f7a5b1f
diff --git a/server/lib/README.md b/server/lib/README.md
index 4e9627bcd7..c6b0821d83 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -209,7 +209,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). |
| `gitCommitProbe.js` | `commitsSince(workspacePath, sinceMs)` / `committedDuringRun(workspacePath, sinceMs)` — the run-window commit probe: how many commits landed with a COMMITTER date inside a run's window (so a rebase/commit by the agent counts, a merely-pulled remote commit does not). The single machine-checkable "did this run commit anything?" primitive shared by finalize's success-criteria evaluation, run completion, runner completion, and orphan recovery — it replaced the unsatisfiable task-id commit-marker grep (#3637). Non-throwing: a non-repo, empty repo, or git timeout is 0. |
| `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — pure GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. |
-| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. |
+| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. `isBenignConcurrentFetchRefRace(stderr)` reads a non-zero `git fetch` as a SUCCESS when its only failure is a lost compare-and-swap whose refs already hold the fetched commits — the routine outcome when the Git tab, `getRemoteBranches`, and CoS agent worktrees fetch one `.git` at once. |
| `gitRemote.js` | `getOriginInfo`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — classifies the local `origin` remote vs the upstream atomantic/PortOS repo. Used by the update flow to detect forks. |
| `githubRepoUrl.js` | `parseGitHubUrl(url)` → `{ owner, repo }` / `isGitHubRepoUrl(url)` — authoritative "is this a clonable GitHub repo URL?" rule, re-exported by `services/githubCloner.js`. Mirrored to `client/src/lib/githubRepoUrl.js` (parity pinned by `githubRepoUrl.mirror.test.js`) so the Brain capture boxes reveal the post-clone agent options for exactly the URLs the server will clone. |
| `killWithEscalation.js` | `killWithEscalation(proc, {label, stillRunning, delayMs=8000})` — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after `delayMs` only when `stillRunning()` holds and the child hasn't exited (`exitCode===null && signalCode===null`). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths. |
diff --git a/server/lib/gitOutputParsers.js b/server/lib/gitOutputParsers.js
index 534021dfe9..5ca9ec2afd 100644
--- a/server/lib/gitOutputParsers.js
+++ b/server/lib/gitOutputParsers.js
@@ -168,3 +168,90 @@ export function extractAgentSummary(output) {
return summary;
}
+
+// A ref-update failure git reports as
+// error: cannot lock ref '<ref>': is at <current> but expected <expected>
+// This is NOT lock contention (no `.lock` file was in the way) — it is a failed
+// compare-and-swap: git read <expected> when the fetch began, and by the time it
+// went to write the ref another process had already moved it to <current>.
+const CANNOT_LOCK_REF_RE =
+ /cannot lock ref '([^']+)':\s*is at ([0-9a-f]+) but expected ([0-9a-f]+)/gi;
+
+// The paired per-ref line in `git fetch` output naming the value the fetch WANTED
+// to write: ` ! <old>..<new> <src> -> <dst> (unable to update local ref)`
+// `..` for a fast-forward, `...` for a forced update. Any other parenthetical
+// git annotates the line with is skipped rather than assumed absent.
+const UNABLE_TO_UPDATE_REF_RE =
+ /^\s*!\s+([0-9a-f]+)\.{2,3}([0-9a-f]+)\s+\S+\s+->\s+(\S+)\s+(?:\([^)]*\)\s*)*\(unable to update local ref\)/gim;
+
+/** Two object names refer to the same commit when either abbreviates the other. */
+function sameObject(a, b) {
+ if (!a || !b) return false;
+ const x = a.toLowerCase();
+ const y = b.toLowerCase();
+ return x.startsWith(y) || y.startsWith(x);
+}
+
+/**
+ * True when a `git fetch` failure is ONLY the benign "someone else already
+ * fetched this" race: every ref git could not lock already holds exactly the
+ * value this fetch was trying to write, so the fetch's goal is satisfied and
+ * the local remote-tracking refs are correct.
+ *
+ * PortOS hits this constantly because several writers share one `.git`: the Git
+ * tab's update button (`updateBranches` → `fetchOrigin`), the same tab's remote
+ * branch list (`getRemoteBranches` → `git fetch origin --prune`), and every CoS
+ * agent worktree. When two fetches overlap, the loser reports a non-zero exit
+ * for work the winner already completed.
+ *
+ * Retrying that is the wrong remedy — the ref is already correct, so a retry
+ * spends another full network fetch to discover there is nothing to do, and on
+ * a busy repo (agents pushing branches) every attempt can lose the same race and
+ * surface a red error for a fetch that actually succeeded. Callers treat a true
+ * return as success instead. Distinguishing "already applied by another writer"
+ * from "failed" is the sentinel-and-validate rule in CLAUDE.md.
+ *
+ * Deliberately strict — it returns false, leaving the existing retry/throw path
+ * in charge, when:
+ * - there is no compare-and-swap failure at all (plain `index.lock` contention),
+ * - a locked ref's current value is NOT what the fetch wanted (e.g. the ref was
+ * rolled back locally), so the fetch genuinely did not achieve its goal,
+ * - a locked ref has no paired `(unable to update local ref)` line to confirm
+ * the intended value against, or
+ * - the output carries any other `error:`/`fatal:` line, so a real failure
+ * riding alongside the race is never swallowed.
+ *
+ * @param {string} stderr - Combined stderr from `git fetch`
+ * @returns {boolean}
+ */
+export function isBenignConcurrentFetchRefRace(stderr) {
+ if (!stderr) return false;
+
+ const locked = [...stderr.matchAll(CANNOT_LOCK_REF_RE)]
+ .map(([, ref, current]) => ({ ref, current }));
+ if (!locked.length) return false;
+
+ // Intended value per ref, keyed on the short `origin/main` form git prints in
+ // the `!` line as well as on the full `refs/remotes/origin/main` the lock error
+ // names, so either spelling resolves.
+ const intended = new Map();
+ for (const [, , next, dst] of stderr.matchAll(UNABLE_TO_UPDATE_REF_RE)) {
+ intended.set(dst, next);
+ intended.set(`refs/remotes/${dst}`, next);
+ }
+
+ const everyRefAlreadyCorrect = locked.every(({ ref, current }) => {
+ const want = intended.get(ref) ?? intended.get(ref.replace(/^refs\/remotes\//, ''));
+ return sameObject(current, want);
+ });
+ if (!everyRefAlreadyCorrect) return false;
+
+ // Any diagnostic that is not one of the two lines this race produces means
+ // something else also went wrong — defer to the caller's error handling.
+ // Uses a non-global copy: `.test()` on a /g regex advances its lastIndex and
+ // would skip every other line.
+ const casLine = new RegExp(CANNOT_LOCK_REF_RE.source, 'i');
+ return !stderr.split('\n').some(
+ line => /^\s*(error|fatal):/i.test(line) && !casLine.test(line)
+ );
+}
diff --git a/server/lib/gitOutputParsers.test.js b/server/lib/gitOutputParsers.test.js
index fdaeb10fa1..7faf0b1746 100644
--- a/server/lib/gitOutputParsers.test.js
+++ b/server/lib/gitOutputParsers.test.js
@@ -5,7 +5,8 @@ import {
parseBranchVerboseLine,
parseSubmoduleStatusLine,
SUBMODULE_STATUS_RE,
- extractAgentSummary
+ extractAgentSummary,
+ isBenignConcurrentFetchRefRace
} from './gitOutputParsers.js';
describe('parseStatus', () => {
@@ -271,3 +272,67 @@ describe('extractAgentSummary', () => {
);
});
});
+
+describe('isBenignConcurrentFetchRefRace', () => {
+ // Verbatim shape of a real lost compare-and-swap: another fetch against the
+ // same .git advanced origin/main to f485411 — exactly what this fetch wanted
+ // to write — between this one reading f538668 and updating the ref.
+ const raced = [
+ "error: cannot lock ref 'refs/remotes/origin/main': is at f485411c6fcc274d9c298f0476ef91990748ad0a but expected f538668661cc298c15abeb6cf78e886b71eae623",
+ 'From github.com:example/example',
+ ' ! f538668..f485411 main -> origin/main (unable to update local ref)',
+ ' * [new branch] claim/issue-1234 -> origin/claim/issue-1234'
+ ].join('\n');
+
+ it('treats a ref already holding the fetched value as success', () => {
+ expect(isBenignConcurrentFetchRefRace(raced)).toBe(true);
+ });
+
+ it('accepts the forced-update spelling of the paired line', () => {
+ expect(isBenignConcurrentFetchRefRace([
+ "error: cannot lock ref 'refs/remotes/origin/main': is at f485411c6fcc274d9c298f0476ef91990748ad0a but expected f538668661cc298c15abeb6cf78e886b71eae623",
+ ' ! f538668...f485411 main -> origin/main (forced update) (unable to update local ref)'
+ ].join('\n'))).toBe(true);
+ });
+
+ it('rejects a ref left at a value the fetch did not want', () => {
+ // Local rollback, not a concurrent fetch: the ref sits at some third commit,
+ // so the fetch genuinely did not achieve its goal.
+ expect(isBenignConcurrentFetchRefRace([
+ "error: cannot lock ref 'refs/remotes/origin/main': is at 9999999999999999999999999999999999999999 but expected f538668661cc298c15abeb6cf78e886b71eae623",
+ ' ! f538668..f485411 main -> origin/main (unable to update local ref)'
+ ].join('\n'))).toBe(false);
+ });
+
+ it('rejects a locked ref with no paired line to confirm the intended value', () => {
+ expect(isBenignConcurrentFetchRefRace(
+ "error: cannot lock ref 'refs/remotes/origin/main': is at f485411c6fcc274d9c298f0476ef91990748ad0a but expected f538668661cc298c15abeb6cf78e886b71eae623"
+ )).toBe(false);
+ });
+
+ it('rejects plain index.lock contention so it still retries', () => {
+ expect(isBenignConcurrentFetchRefRace(
+ "fatal: Unable to create '/repo/.git/index.lock': File exists."
+ )).toBe(false);
+ });
+
+ it('does not swallow a real failure riding alongside the race', () => {
+ expect(isBenignConcurrentFetchRefRace(`${raced}\nfatal: could not read from remote repository`))
+ .toBe(false);
+ });
+
+ it('checks every locked ref, not just the first', () => {
+ expect(isBenignConcurrentFetchRefRace([
+ "error: cannot lock ref 'refs/remotes/origin/main': is at f485411c6fcc274d9c298f0476ef91990748ad0a but expected f538668661cc298c15abeb6cf78e886b71eae623",
+ "error: cannot lock ref 'refs/remotes/origin/release': is at 9999999999999999999999999999999999999999 but expected 1111111111111111111111111111111111111111",
+ ' ! f538668..f485411 main -> origin/main (unable to update local ref)',
+ ' ! 1111111..2222222 release -> origin/release (unable to update local ref)'
+ ].join('\n'))).toBe(false);
+ });
+
+ it('returns false for empty or clean output', () => {
+ expect(isBenignConcurrentFetchRefRace('')).toBe(false);
+ expect(isBenignConcurrentFetchRefRace(undefined)).toBe(false);
+ expect(isBenignConcurrentFetchRefRace('From github.com:example/example\n * [new branch] x -> origin/x')).toBe(false);
+ });
+});
diff --git a/server/services/git.fetchOrigin.test.js b/server/services/git.fetchOrigin.test.js
index 87bfcd5d53..43aa8b1a66 100644
--- a/server/services/git.fetchOrigin.test.js
+++ b/server/services/git.fetchOrigin.test.js
@@ -32,6 +32,19 @@ describe('fetchOrigin', () => {
expect(execGitMock).toHaveBeenNthCalledWith(2, ['fetch', 'origin'], '/repo');
});
+ it('accepts a lost compare-and-swap without a second fetch', async () => {
+ // The concurrent winner already wrote origin/main to the very commit this
+ // fetch wanted, so the refs are correct and there is nothing left to do.
+ execGitMock.mockRejectedValueOnce(new Error([
+ "error: cannot lock ref 'refs/remotes/origin/main': is at f485411c6fcc274d9c298f0476ef91990748ad0a but expected f538668661cc298c15abeb6cf78e886b71eae623",
+ 'From github.com:example/example',
+ ' ! f538668..f485411 main -> origin/main (unable to update local ref)'
+ ].join('\n')));
+
+ await expect(fetchOrigin('/repo')).resolves.toBe(true);
+ expect(execGitMock).toHaveBeenCalledTimes(1);
+ });
+
it('does not retry a permanent fetch failure', async () => {
execGitMock.mockRejectedValueOnce(new Error('fatal: repository not found'));
diff --git a/server/services/git.js b/server/services/git.js
index ed6a5ac448..bb4383080e 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -9,7 +9,8 @@ import {
parseDiffStat,
parseBranchVerboseLine,
parseSubmoduleStatusLine,
- extractAgentSummary
+ extractAgentSummary,
+ isBenignConcurrentFetchRefRace
} from '../lib/gitOutputParsers.js';
import {
parseGitRemote,
@@ -190,6 +191,13 @@ function fetchOriginAttempt(dir, attempt) {
return execGit(['fetch', 'origin'], dir).then(
() => true,
(err) => {
+ // A concurrent fetch that already wrote the exact refs this one wanted is
+ // a SUCCESS reported as a failure — git exits non-zero on the lost
+ // compare-and-swap even though the remote-tracking refs now hold the
+ // right commits. Retrying re-runs a whole network fetch to learn there is
+ // nothing to do, and on a busy repo every attempt loses the same race, so
+ // the caller surfaced a red error for work that had actually completed.
+ if (isBenignConcurrentFetchRefRace(err.message)) return true;
// Another PortOS surface or agent may advance the same remote ref mid-fetch.
if (attempt >= FETCH_MAX_ATTEMPTS || !isGitLockError(err.message)) throw err;
return sleep(FETCH_RETRY_DELAY_MS).then(() => fetchOriginAttempt(dir, attempt + 1));