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

recover from an abandoned git lock instead of wedging submodule checkout forever

[._.]/ Adam Eivyf53f8d42532e
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index ee921dca37..ed6354fc6e 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -414,6 +414,41 @@ max_memory_restart: '500M'
## Development Issues
+### "Another git process seems to be running" — but none is
+
+**Symptom**: every git command against one repo (or, most often, every submodule
+checkout) fails with:
+
+```
+fatal: Unable to create '<repo>/.git/modules/lib/slashdo/index.lock': File exists.
+Another git process seems to be running in this repository, or the lock file may be stale
+fatal: Unable to checkout '<sha>' in submodule path 'lib/slashdo'
+```
+
+**Cause**: a git process was killed before it could remove its lock file — a PM2
+tree-kill during self-update, an `execGit` timeout, a reaped CoS agent. The lock
+outlives the process and nothing else removes it, so the failure is permanent.
+A submodule lock lives in `.git/modules/<submodule>/`, which every git worktree
+of the repo shares, so ONE dead process wedges submodule checkout for the primary
+checkout, every CoS agent worktree, `update.sh` and `npm run setup` at once.
+
+**PortOS clears this itself** on the paths that hit it — the Submodules tab's
+Update button and CoS worktree creation both remove a lock older than 30 minutes
+and retry, `update.sh` / `update.ps1` sweep one before they start (they are the
+likeliest producer), and `npm run doctor` names the lock as the blocker instead
+of telling you to run the command that will fail. One rule, in
+`server/lib/gitStaleLock.js`: a lock young enough to still belong to a running
+git command is never touched.
+
+**Manual recovery** (confirm no git process is really running first):
+
+```bash
+ps aux | grep '[g]it' # must show nothing working on this repo
+find .git -name '*.lock' -not -path '*/rr-cache/*'
+rm <the-lock-path>
+git submodule update --init --recursive
+```
+
### Hot Reload Not Working
**Symptom**: Frontend changes require manual refresh.
diff --git a/scripts/doctor.js b/scripts/doctor.js
index 3562a990db..e1165c3a27 100644
--- a/scripts/doctor.js
+++ b/scripts/doctor.js
@@ -49,6 +49,7 @@ import { fileURLToPath } from 'url';
import { certPaths } from '../lib/certPaths.js';
import { commandExists } from '../server/lib/commandExists.js';
+import { isStaleGitLock } from '../server/lib/gitStaleLock.js';
import { scrubHomePath } from '../server/lib/homePath.js';
import { MIN_NODE, compareVersions, satisfiesMinNode } from './checkNodeVersion.js';
import { MIN_NPM, parseNpmUserAgent, readBundledNpmVersion } from './checkNpmVersion.js';
@@ -209,11 +210,24 @@ async function probeNpm() {
: { available: false, detail: `${version} is below ${MIN_NPM} — installs rewrite package-lock.json (npm install -g npm@${MIN_NPM})` };
}
+/**
+ * An empty `lib/slashdo` usually just means setup never ran — but when a stale
+ * lock sits in the submodule's git dir, the remediation this printed until now
+ * is the exact command that will fail, reporting a git process that exited long
+ * ago. Name the real blocker instead. The lock lives in the PARENT repo's
+ * `.git/modules/`, shared by every worktree, so one dead process explains a
+ * missing checkout in all of them at once.
+ */
async function probeSubmodule(root) {
- return probePath(root, join('lib', 'slashdo', 'package.json'), {
+ const probe = probePath(root, join('lib', 'slashdo', 'package.json'), {
presentDetail: 'lib/slashdo checked out',
missingDetail: 'lib/slashdo is empty — run: git submodule update --init --recursive',
});
+ if (probe.available) return probe;
+ const lockPath = join(root, '.git', 'modules', 'lib', 'slashdo', 'index.lock');
+ return isStaleGitLock(lockPath)
+ ? { available: false, detail: `lib/slashdo checkout is blocked by a stale git lock — delete ${lockPath}, then run: git submodule update --init --recursive` }
+ : probe;
}
async function probeWorkspaceDeps(root, workspace) {
diff --git a/scripts/update-submodules.test.js b/scripts/update-submodules.test.js
index 4641e14994..1c944f60c6 100644
--- a/scripts/update-submodules.test.js
+++ b/scripts/update-submodules.test.js
@@ -41,4 +41,14 @@ describe.each(SCRIPT_COMMANDS)('$path submodule update contract', ({ path, pull,
it('does not advance submodules past the commits reviewed by PortOS', () => {
expect(source).not.toMatch(/git submodule update[^\n]*--remote/);
});
+
+ // This script is the most likely producer of an abandoned lock (PM2 tree-kills
+ // it mid-run), and without the sweep every later self-update fails identically
+ // on a file under `.git/` only a human would find. Both platforms call the one
+ // Node helper rather than each reimplementing "is this lock abandoned?".
+ it('clears locks a previously killed update left behind, before it takes any', () => {
+ const sweepIndex = source.indexOf('clearStaleGitLocksIn');
+ expect(sweepIndex).toBeGreaterThanOrEqual(0);
+ expect(sweepIndex).toBeLessThan(source.indexOf(pull));
+ });
});
diff --git a/server/lib/README.md b/server/lib/README.md
index c066c60bba..82137224bc 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -372,6 +372,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `sshHostAlias.js` | `resolveSshHostAlias`, `parseSshHostAliases` — resolves a personal SSH `Host` alias (`git@github-acme:…`, backed by `HostName github.com` in `~/.ssh/config`) to the host a remote actually connects to. Every remote-URL host parser (`gitForge.parseGitRemote`, `gitRemote.parseGitRemoteUrl`, `workTracker.hostFromOriginUrl`) canonicalizes through it, so multi-account checkouts classify as GitHub instead of an unreachable unknown host. |
| `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`, `classifyOriginRemote`, `parseGitRemoteUrl`, `readRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — safely reads and classifies checkout remotes against PortOS or a caller-supplied canonical upstream. Used by self-update and managed integrations to detect forks. |
+| `gitStaleLock.js` | `gitLockPathFromError`, `isStaleGitLock`, `clearStaleGitLock`, `clearStaleGitLocksIn`, `STALE_GIT_LOCK_MIN_AGE_MS` — recognizes the `*.lock` a KILLED git process left behind and removes it so the caller can retry. A lock under `.git/modules/<submodule>/` is shared by every worktree of the repo, so one dead process wedges submodule checkout install-wide with a bogus "another git process is running". Removal requires a `.lock` path under a `.git` directory (so a malformed message cannot aim the unlink at `yarn.lock`) that is older than 30 minutes — 3x the longest git command PortOS runs (`worktreeManager.WORKTREE_ADD_TIMEOUT_MS`, pinned by a test), which is what keeps it from deleting a LIVE competitor's lock. The threshold is deliberately not a parameter. `clearStaleGitLock(message)` is the reactive form, wired into `services/git.js#updateSubmodule` and `worktreeManager.addWorktreeWithRetry`; `clearStaleGitLocksIn(gitDir)` sweeps ahead of `update.sh`/`update.ps1`, the most likely producer. `scripts/doctor.js` reports one as the blocker. |
| `repoLinkFields.js` | `deriveRepoLinkFields(url)` / `normalizeRepoLinkFields(link)` / `linkIsRepo(link)` / `repoLinkLabel(link)` — the repository metadata a Brain link carries, plus the dual-write/tolerant-read shim that keeps the pre-multi-host `isGitHubRepo` field names readable across federated peers. |
| `repoUrl.js` | `parseRepoUrl(url)` → `{ host, provider, owner, repo }` / `isRepoUrl(url)` / `repoCloneUrl(parsed)` / `repoBrowseUrl(parsed)` / `parseGitHubUrl(url)` / `isGitHubRepoUrl(url)` — authoritative "is this a clonable repo URL?" rule, with per-host behavior (subgroup nesting, clone layout) in the `REPO_HOSTS` table. Re-exported by `client/src/lib/repoUrl.js` so the Brain capture boxes reveal the post-clone agent options for exactly the URLs the server will clone. |
| `glabArgs.js` | `GLAB_JSON_ARGS`, `withGlabJson(args)` — pure `glab` argv conventions. The JSON output flag is `--output json`, NOT `-F json`: on `glab issue list` (and only there) `-F` is `--output-format` (details/ids/urls), so `-F json` is accepted, ignored, and answers with the human table at exit 0. Shared by all three `glab` runners so the spelling has one definition; guarded tree-wide by `services/gitlab.glabFlags.test.js`. |
diff --git a/server/lib/gitStaleLock.js b/server/lib/gitStaleLock.js
new file mode 100644
index 0000000000..2f14014809
--- /dev/null
+++ b/server/lib/gitStaleLock.js
@@ -0,0 +1,184 @@
+/**
+ * Recognize and clear the `*.lock` files a KILLED git process leaves behind.
+ *
+ * Git guards each index/ref write with a lock file it removes on exit. A git
+ * process that never gets to exit — PM2 tree-killing the server mid-update, an
+ * `execGit` timeout firing, a reaped CoS agent — leaves the lock on disk, and
+ * every later git command on that repo fails with:
+ *
+ * fatal: Unable to create '<path>/index.lock': File exists.
+ * Another git process seems to be running in this repository…
+ *
+ * Nothing removes it, so the failure is PERMANENT until a human deletes a file
+ * buried under `.git/`. The submodule case is the worst of them: the lock lives
+ * in `.git/modules/<submodule>/`, which every git worktree of the repo shares,
+ * so one dead process wedges submodule checkout for the primary checkout, every
+ * CoS agent worktree, `update.sh`, and `npm run setup` at once — all of them
+ * reporting a concurrent git process that does not exist.
+ *
+ * Deleting a lock a LIVE git process still holds would corrupt that write, so
+ * `isStaleGitLock` clears one only when all three hold:
+ *
+ * 1. the path ends in `.lock` and sits under a `.git` directory. This is what
+ * keeps a malformed or attacker-shaped error message from aiming the
+ * unlink at a repository file — `yarn.lock` also ends in `.lock`, and it
+ * lives in the repo ROOT, outside `.git`.
+ * 2. the file still exists (a concurrent retry may have already cleared it).
+ * 3. its mtime is older than `STALE_GIT_LOCK_MIN_AGE_MS`. Git does not touch
+ * a lock's mtime while it works, so age is measured from lock CREATION;
+ * the threshold therefore has to exceed the longest git command PortOS can
+ * have in flight. The ceiling is `execGit`'s largest caller timeout (600s
+ * for `git worktree add`), after which the process is killed and its lock
+ * is stale by definition — 30 minutes leaves 3x headroom over that.
+ *
+ * Bare repos (`<name>.git/index.lock`, no `.git` path segment) are deliberately
+ * out of scope: PortOS creates them only as test fixtures, never on a path that
+ * needs this rescue.
+ */
+
+import { existsSync, readFileSync, readdirSync, statSync, unlinkSync } from 'fs';
+import { dirname, join, resolve } from 'path';
+
+import { scrubHomePath } from './homePath.js';
+
+/** See rule 3 above — 3x the longest git command PortOS can have in flight. */
+export const STALE_GIT_LOCK_MIN_AGE_MS = 30 * 60 * 1000;
+
+// Git quotes the offending path in every wording that reports lock contention
+// ("Unable to create '<path>': File exists", "cannot lock ref '…': Unable to
+// create '<path>'"). Anchoring on the quoted `.lock` path rather than on the
+// sentence keeps this working across git's phrasings and locales-in-English.
+const QUOTED_LOCK_PATH = /'([^']*\.lock)'/;
+
+/**
+ * The lock path a git error names, or null when the message reports something
+ * other than lock contention.
+ * @param {string} message - git stderr / Error message
+ * @returns {string|null}
+ */
+export function gitLockPathFromError(message) {
+ if (typeof message !== 'string') return null;
+ return message.match(QUOTED_LOCK_PATH)?.[1] ?? null;
+}
+
+/**
+ * True when `lockPath` is a git lock file left behind by a process that is gone.
+ *
+ * The threshold is deliberately NOT a parameter: this predicate is the only
+ * thing standing between a caller and an unlink, and an injectable `minAgeMs`
+ * is an argument away from `0` — a caller that deletes whatever lock the error
+ * named, live process or not. Tests back-date a real lock's mtime instead.
+ *
+ * @param {string} lockPath
+ * @returns {boolean}
+ */
+export function isStaleGitLock(lockPath) {
+ if (typeof lockPath !== 'string' || !lockPath.endsWith('.lock')) return false;
+ // Accept both separators: a Windows git reports backslash paths, and a POSIX
+ // path can reach a Windows Node through a checked-in fixture or a log.
+ if (!lockPath.split(/[\\/]/).includes('.git')) return false;
+ if (!existsSync(lockPath)) return false;
+ return Date.now() - statSync(lockPath).mtimeMs >= STALE_GIT_LOCK_MIN_AGE_MS;
+}
+
+/**
+ * Clear the stale lock a failed git command named, so the caller can retry.
+ *
+ * Returns the removed path (for the caller's log line) or null when there was
+ * nothing safe to remove — no lock in the message, a lock too young to call
+ * abandoned, or one another retry already cleared. Never throws: a failed
+ * rescue must surface as the ORIGINAL git error, not as an unlink error that
+ * hides it.
+ *
+ * @param {string} message - git stderr / Error message from the failed command
+ * @returns {string|null} the lock path that was removed
+ */
+export function clearStaleGitLock(message) {
+ const lockPath = gitLockPathFromError(message);
+ if (!lockPath || !isStaleGitLock(lockPath)) return null;
+ try {
+ unlinkSync(lockPath);
+ } catch {
+ return null;
+ }
+ // Segments below `.git/` name repository internals, never user records, but
+ // the absolute prefix embeds the OS username — scrub it rather than trim a
+ // fixed depth, which keeps `/Users/<name>` for a repo checked out shallowly.
+ console.log(`🧹 Cleared stale git lock: ${scrubHomePath(lockPath)}`);
+ return lockPath;
+}
+
+// `objects/` holds tens of thousands of entries and none of the locks that
+// wedge a checkout (index, refs, packed-refs, and each submodule's copies of
+// those under `modules/`), so walking it would dominate the sweep's cost for
+// nothing. `rr-cache/` is rerere state, likewise not in the wedge path.
+const UNSWEPT_GIT_DIRS = new Set(['objects', 'rr-cache']);
+
+/**
+ * Sweep a repository's git directory for abandoned locks, BEFORE running the
+ * commands that would trip over them.
+ *
+ * The reactive form above only helps a caller that gets to see the failure and
+ * retry. `update.sh` / `update.ps1` are the most likely PRODUCER of an
+ * abandoned lock in the first place — PM2 tree-kills the server mid-update and
+ * takes the `git submodule update` subprocess with it — and, before this, had
+ * no recovery at all: every later self-update failed the same way, on a lock
+ * only a human could find. They call this first so the update that follows
+ * starts from a clean repo.
+ *
+ * Same three-condition rule as `isStaleGitLock`, so there is ONE definition of
+ * "abandoned" rather than a second copy in shell.
+ *
+ * @param {string} gitDir - the repository's git directory (`<repo>/.git`)
+ * @returns {string[]} the lock paths removed
+ */
+export function clearStaleGitLocksIn(gitDir) {
+ const root = resolveCommonGitDir(gitDir);
+ if (!root) return [];
+ const cleared = [];
+ const walk = (dir) => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (!UNSWEPT_GIT_DIRS.has(entry.name)) walk(full);
+ } else if (entry.name.endsWith('.lock') && isStaleGitLock(full)) {
+ try {
+ unlinkSync(full);
+ cleared.push(full);
+ console.log(`🧹 Cleared stale git lock: ${scrubHomePath(full)}`);
+ } catch {
+ // Best effort — an unreadable lock is the caller's original problem
+ // to report, not a reason to abort the update before it starts.
+ }
+ }
+ }
+ };
+ walk(root);
+ return cleared;
+}
+
+/**
+ * Resolve a `.git` path to the SHARED git directory whose locks actually wedge
+ * things, or null when it names no repository.
+ *
+ * Two indirections have to be followed, and both matter here:
+ * - in a git WORKTREE (every CoS agent runs in one), `.git` is a FILE holding
+ * `gitdir: <path>` — reading it as a directory is the difference between
+ * sweeping and throwing;
+ * - that per-worktree git dir holds only its own HEAD/index locks. The locks
+ * shared by every worktree — `modules/<submodule>/index.lock`, the refs —
+ * live in the COMMON dir, which git names in a `commondir` file beside it.
+ * Sweeping the worktree's own dir would miss the exact lock this module
+ * exists for.
+ */
+function resolveCommonGitDir(gitPath) {
+ if (typeof gitPath !== 'string' || !existsSync(gitPath)) return null;
+ const pointer = statSync(gitPath).isDirectory()
+ ? gitPath
+ : resolve(dirname(gitPath), readFileSync(gitPath, 'utf8').match(/^gitdir:\s*(.+)$/m)?.[1].trim() ?? '');
+ if (!existsSync(pointer) || !statSync(pointer).isDirectory()) return null;
+ const commondir = join(pointer, 'commondir');
+ return existsSync(commondir)
+ ? resolve(pointer, readFileSync(commondir, 'utf8').trim())
+ : pointer;
+}
diff --git a/server/lib/gitStaleLock.test.js b/server/lib/gitStaleLock.test.js
new file mode 100644
index 0000000000..da631ea8fc
--- /dev/null
+++ b/server/lib/gitStaleLock.test.js
@@ -0,0 +1,144 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { existsSync, mkdirSync, utimesSync, writeFileSync } from 'fs';
+import { mkdtemp, rm } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import { STALE_GIT_LOCK_MIN_AGE_MS, clearStaleGitLock, clearStaleGitLocksIn, gitLockPathFromError, isStaleGitLock } from './gitStaleLock.js';
+
+/** Old enough that no running git command could still hold it. */
+const ABANDONED = STALE_GIT_LOCK_MIN_AGE_MS + 60_000;
+
+// The message git actually prints, verbatim — the whole helper keys off this
+// wording, so a paraphrase here would stop proving it parses the real thing.
+const gitLockError = (path) => `fatal: Unable to create '${path}': File exists.\n\nAnother git process seems to be running in this repository, or the lock file may be stale`;
+
+let dir;
+
+/** A lock file whose mtime says it was created `ageMs` ago. */
+function writeLock(relativePath, ageMs) {
+ const full = join(dir, relativePath);
+ mkdirSync(join(full, '..'), { recursive: true });
+ writeFileSync(full, '');
+ const seconds = (Date.now() - ageMs) / 1000;
+ utimesSync(full, seconds, seconds);
+ return full;
+}
+
+beforeEach(async () => {
+ dir = await mkdtemp(join(tmpdir(), 'git-stale-lock-'));
+});
+
+afterEach(async () => {
+ await rm(dir, { recursive: true, force: true });
+});
+
+describe('gitLockPathFromError', () => {
+ it('extracts the lock path git names in a contention failure', () => {
+ expect(gitLockPathFromError(gitLockError('/repo/.git/modules/lib/slashdo/index.lock')))
+ .toBe('/repo/.git/modules/lib/slashdo/index.lock');
+ });
+
+ it('extracts the lock path from ref-lock wording, not just index-lock wording', () => {
+ const message = "error: cannot lock ref 'refs/heads/main': Unable to create '/repo/.git/refs/heads/main.lock': File exists";
+ expect(gitLockPathFromError(message)).toBe('/repo/.git/refs/heads/main.lock');
+ });
+
+ it('returns null for a failure that is not lock contention', () => {
+ expect(gitLockPathFromError("fatal: invalid reference: 'origin/nope'")).toBeNull();
+ expect(gitLockPathFromError(undefined)).toBeNull();
+ });
+});
+
+describe('isStaleGitLock', () => {
+ it('accepts an abandoned lock under .git', () => {
+ expect(isStaleGitLock(writeLock('.git/modules/lib/dep/index.lock', ABANDONED))).toBe(true);
+ });
+
+ it('refuses a lock young enough to belong to a running git command', () => {
+ // The destructive half of the guard: a live `git worktree add` holds its
+ // lock for as long as the checkout runs, and unlinking it corrupts that write.
+ expect(isStaleGitLock(writeLock('.git/index.lock', 5 * 60_000))).toBe(false);
+ });
+
+ it('refuses a stale-aged .lock that is NOT under a .git directory', () => {
+ // `yarn.lock` ends in `.lock` and lives in the repo root. Nothing may aim
+ // the unlink at a repository file, however old it is.
+ expect(isStaleGitLock(writeLock('yarn.lock', STALE_GIT_LOCK_MIN_AGE_MS * 10))).toBe(false);
+ });
+
+ it('refuses a path that is not a lock file at all', () => {
+ expect(isStaleGitLock(writeLock('.git/index', STALE_GIT_LOCK_MIN_AGE_MS * 10))).toBe(false);
+ });
+
+ it('refuses a lock that is already gone', () => {
+ expect(isStaleGitLock(join(dir, '.git/index.lock'))).toBe(false);
+ });
+});
+
+describe('clearStaleGitLock', () => {
+ it('removes the abandoned lock named by a git error and reports the path', () => {
+ const lock = writeLock('.git/modules/lib/dep/index.lock', ABANDONED);
+
+ expect(clearStaleGitLock(gitLockError(lock))).toBe(lock);
+ expect(existsSync(lock)).toBe(false);
+ });
+
+ it('leaves a live competitor\'s lock on disk and reports nothing cleared', () => {
+ const lock = writeLock('.git/index.lock', 60_000);
+
+ expect(clearStaleGitLock(gitLockError(lock))).toBeNull();
+ expect(existsSync(lock)).toBe(true);
+ });
+
+ it('reports nothing cleared for a failure that names no lock', () => {
+ expect(clearStaleGitLock('fatal: not a git repository')).toBeNull();
+ });
+});
+
+describe('clearStaleGitLocksIn', () => {
+ it('sweeps abandoned locks anywhere under the git dir, submodules included', () => {
+ // The wedge this exists for: the parent index lock and a submodule lock in
+ // .git/modules/, which every worktree of the repo shares.
+ const index = writeLock('.git/index.lock', ABANDONED);
+ const submodule = writeLock('.git/modules/lib/dep/index.lock', ABANDONED);
+ const ref = writeLock('.git/refs/heads/main.lock', ABANDONED);
+
+ expect(clearStaleGitLocksIn(join(dir, '.git')).sort()).toEqual([index, submodule, ref].sort());
+ for (const lock of [index, submodule, ref]) expect(existsSync(lock)).toBe(false);
+ });
+
+ it('leaves a lock a running git command may still hold', () => {
+ const live = writeLock('.git/index.lock', 60_000);
+
+ expect(clearStaleGitLocksIn(join(dir, '.git'))).toEqual([]);
+ expect(existsSync(live)).toBe(true);
+ });
+
+ it('does not walk objects/, where the sweep would pay for tens of thousands of entries', () => {
+ const inObjects = writeLock('.git/objects/pack/tmp.lock', ABANDONED);
+
+ expect(clearStaleGitLocksIn(join(dir, '.git'))).toEqual([]);
+ expect(existsSync(inObjects)).toBe(true);
+ });
+
+ it('reports nothing for a repo with no git dir', () => {
+ expect(clearStaleGitLocksIn(join(dir, 'nope'))).toEqual([]);
+ });
+
+ // Every CoS agent runs in a worktree, where `.git` is a FILE pointing at
+ // `<common>/.git/worktrees/<name>` — and the lock that wedges submodule
+ // checkout is not in there, it is in the COMMON dir both trees share.
+ it('follows a worktree\'s .git FILE out to the shared common dir', () => {
+ const shared = writeLock('.git/modules/lib/dep/index.lock', ABANDONED);
+ const worktreeGitDir = join(dir, '.git/worktrees/agent-1');
+ mkdirSync(worktreeGitDir, { recursive: true });
+ writeFileSync(join(worktreeGitDir, 'commondir'), '../..\n');
+ mkdirSync(join(dir, 'tree'), { recursive: true });
+ const pointerFile = join(dir, 'tree/.git');
+ writeFileSync(pointerFile, `gitdir: ${worktreeGitDir}\n`);
+
+ expect(clearStaleGitLocksIn(pointerFile)).toEqual([shared]);
+ expect(existsSync(shared)).toBe(false);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 89f7a1e248..edb0042ff4 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -353,6 +353,7 @@ export * from './gitCommitProbe.js';
export * from './gitForge.js';
export * from './gitOutputParsers.js';
export * from './gitRemote.js';
+export * from './gitStaleLock.js';
export * from './repoUrl.js';
export * from './glabArgs.js';
export * from './goalFeatureMap.js';
diff --git a/server/services/git.js b/server/services/git.js
index 5a4e016735..e047e3657b 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -3,6 +3,7 @@ import { join, resolve } from 'path';
import { safeJSONParse, PATHS, sleep } from '../lib/fileUtils.js';
import { isGitLockError, listWorktrees, reapMergedWorktrees } from './worktreeManager.js';
import { execGit, execGitSafe } from '../lib/execGit.js';
+import { clearStaleGitLock } from '../lib/gitStaleLock.js';
import { resolveForgeForRepo } from './forgeAuth.js';
export { resolveForgeForRepo, resolveForgeTokenEnv } from './forgeAuth.js';
import {
@@ -1719,7 +1720,17 @@ export async function updateSubmodule(subPath, { repoPath, commit: shouldCommit
throw new ServerError(`Unknown submodule path: ${subPath}`, { status: 400, code: 'VALIDATION_ERROR' });
}
console.log(`📦 Updating submodule ${subPath}...`);
- await execGit(['submodule', 'update', '--init', '--recursive', '--remote', subPath], root, { timeout: 60000 });
+ const updateArgs = ['submodule', 'update', '--init', '--recursive', '--remote', subPath];
+ // A submodule's lock lives in `.git/modules/<subPath>/`, which every worktree
+ // of the parent repo shares, so one killed git process wedges this button
+ // permanently — each press re-reports a concurrent git process that exited
+ // long ago. Clear the abandoned lock and retry ONCE; a lock too young to call
+ // stale, or a failure that names no lock, rethrows untouched so a genuinely
+ // concurrent update still reports contention rather than racing it.
+ await execGit(updateArgs, root, { timeout: 60000 }).catch(async (err) => {
+ if (!clearStaleGitLock(err.message)) throw err;
+ await execGit(updateArgs, root, { timeout: 60000 });
+ });
console.log(`✅ Submodule ${subPath} updated`);
const statusResult = await execGit(['submodule', 'status', subPath], root);
const parsed = parseSubmoduleStatusLine(statusResult.stdout);
diff --git a/server/services/git.submodules.test.js b/server/services/git.submodules.test.js
index 7be5044c8e..9212d8ae87 100644
--- a/server/services/git.submodules.test.js
+++ b/server/services/git.submodules.test.js
@@ -10,7 +10,12 @@ vi.mock('../lib/execGit.js', () => {
};
});
+// Mocked so the retry path is driven by a decision, not by real file mtimes —
+// `lib/gitStaleLock.test.js` owns proving WHICH locks it agrees to remove.
+vi.mock('../lib/gitStaleLock.js', () => ({ clearStaleGitLock: vi.fn(() => null) }));
+
import { execGit } from '../lib/execGit.js';
+import { clearStaleGitLock } from '../lib/gitStaleLock.js';
const REPO = '/Users/me/project';
const SUB = 'lib/dep';
@@ -102,6 +107,44 @@ describe('updateSubmodule', () => {
expect(callsFor('commit')).toHaveLength(0);
});
+ // A killed git process leaves `index.lock` inside `.git/modules/<subPath>/`,
+ // which every worktree of the repo shares — so without this, pressing Update
+ // Submodule fails forever, blaming a git process that exited long ago.
+ it('clears an abandoned lock and retries once', async () => {
+ scriptGit();
+ const lockError = new Error("fatal: Unable to create '/Users/me/project/.git/modules/lib/dep/index.lock': File exists");
+ let updates = 0;
+ const scripted = execGit.getMockImplementation();
+ execGit.mockImplementation(async (args, cwd, options) => {
+ if (args[0] === 'submodule' && args[1] === 'update' && ++updates === 1) throw lockError;
+ return scripted(args, cwd, options);
+ });
+ clearStaleGitLock.mockReturnValue('/Users/me/project/.git/modules/lib/dep/index.lock');
+ const { updateSubmodule } = await import('./git.js');
+
+ const result = await updateSubmodule(SUB, { repoPath: REPO });
+
+ expect(result).toEqual({ newCommit: '1111111', committed: false });
+ expect(clearStaleGitLock).toHaveBeenCalledWith(lockError.message);
+ expect(callsFor('submodule').filter(([args]) => args[1] === 'update')).toHaveLength(2);
+ });
+
+ it('surfaces the lock failure when the lock is too young to clear', async () => {
+ // A genuinely concurrent update must be REPORTED, not raced: clearing
+ // refused, so there is nothing to retry.
+ scriptGit();
+ const lockError = new Error("fatal: Unable to create '/Users/me/project/.git/modules/lib/dep/index.lock': File exists");
+ execGit.mockImplementation(async (args) => {
+ if (args[0] === 'submodule' && args[1] === 'update') throw lockError;
+ return ok(' 1111111222222233333334444444555555566 lib/dep (heads/main)\n');
+ });
+ clearStaleGitLock.mockReturnValue(null);
+ const { updateSubmodule } = await import('./git.js');
+
+ await expect(updateSubmodule(SUB, { repoPath: REPO })).rejects.toThrow(/Unable to create/);
+ expect(callsFor('submodule').filter(([args]) => args[1] === 'update')).toHaveLength(1);
+ });
+
it('rejects a path that is not a submodule of the repo', async () => {
scriptGit();
const { updateSubmodule } = await import('./git.js');
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 8d0c0fb4d5..a7b71b7ffd 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -16,6 +16,7 @@ import { ensureDir, isPathInsideDir, PATHS, sleep, tryReadFile } from '../lib/fi
import { DONE_SENTINEL_NAME, doneSentinelName } from '../lib/agentSentinel.js';
import { AGENT_SCRATCH_PATHS, matchesScratchRoot } from '../lib/agentScratchPaths.js';
import { execGit } from '../lib/execGit.js';
+import { clearStaleGitLock } from '../lib/gitStaleLock.js';
import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';
import { forkRemoteName, normalizeForkHead } from '../lib/forkHead.js';
@@ -59,7 +60,12 @@ const WORKTREE_ADD_RETRY_DELAY_MS = 250;
// defeats the orphan-branch cleanup ("Cannot delete branch … checked out at …").
// Ten minutes is far above any healthy add and still bounded. Applies to
// `worktree move` too — it routes through this same wrapper.
-const WORKTREE_ADD_TIMEOUT_MS = 10 * 60 * 1000;
+//
+// EXPORTED because it is the ceiling `STALE_GIT_LOCK_MIN_AGE_MS` is sized
+// against: the longest a git command PortOS launches can legitimately still be
+// holding its lock. Raising this without raising that one would let the
+// stale-lock sweep delete a live checkout's lock — the test below pins it.
+export const WORKTREE_ADD_TIMEOUT_MS = 10 * 60 * 1000;
/**
* True when a git error message indicates lock/contention on the worktree or
@@ -128,6 +134,13 @@ export function addWorktreeWithRetry(args, repo, attempt = 1, firstError = null)
err.firstAttemptError = originalError;
throw err;
}
+ // The retry budget above assumes CONTENTION — a live competitor that will
+ // release the lock within a second. An ABANDONED lock (a killed git process
+ // never removed it) releases never, so all four attempts fail and the task
+ // blocks with `worktree-failed` on a repo nothing is actually using. Clear
+ // it before backing off; `clearStaleGitLock` refuses anything young enough
+ // to still belong to a running command, so a real competitor is untouched.
+ clearStaleGitLock(err.message);
console.log(`🌳 Worktree ${args[1] || 'add'} lock contention (attempt ${attempt}/${WORKTREE_ADD_MAX_ATTEMPTS}), retrying in ${WORKTREE_ADD_RETRY_DELAY_MS}ms: ${err.message}`);
return sleep(WORKTREE_ADD_RETRY_DELAY_MS)
.then(() => addWorktreeWithRetry(args, repo, attempt + 1, originalError));
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index f563bff2e6..849b5db042 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -21,6 +21,11 @@ vi.mock('fs/promises', () => ({
// adoptWorktree ensures the worktrees root exists before moving a tree into it.
mkdir: vi.fn().mockResolvedValue(undefined),
}));
+// The retry path asks whether the lock it just hit was abandoned. Mocked here
+// (the `fs` stub above has no `statSync`, and real mtimes would make this a
+// clock test); `lib/gitStaleLock.test.js` owns which locks it agrees to remove.
+const clearStaleGitLockMock = vi.fn().mockReturnValue(null);
+vi.mock('../lib/gitStaleLock.js', () => ({ clearStaleGitLock: (...args) => clearStaleGitLockMock(...args) }));
vi.mock('./instanceIdentity.js', () => ({ ensureInstanceId: vi.fn().mockResolvedValue('instance-1') }));
const getDefaultBranchMock = vi.fn().mockResolvedValue('main');
const hasBranchMergeEvidenceMock = vi.fn().mockResolvedValue(false);
@@ -43,6 +48,7 @@ const {
createWorktree,
createPersistentWorktree,
listWorktrees,
+ WORKTREE_ADD_TIMEOUT_MS,
} = await import('./worktreeManager.js');
const { isPathInsideDir } = await import('../lib/fileUtils.js');
const { worktreeOwnershipReason } = await import('../lib/worktreeOwnership.js');
@@ -648,6 +654,7 @@ describe('listWorktrees line endings', () => {
describe('addWorktreeWithRetry (lock-contention retry, #2193)', () => {
beforeEach(() => {
execGitMock.mockReset();
+ clearStaleGitLockMock.mockClear();
vi.useFakeTimers();
});
afterEach(() => {
@@ -685,6 +692,28 @@ describe('addWorktreeWithRetry (lock-contention retry, #2193)', () => {
expect(execGitMock).toHaveBeenCalledTimes(2);
});
+ // Retrying alone cannot clear an ABANDONED lock — nothing is coming to
+ // release it, so all four attempts would fail and block the task.
+ it('tries to clear an abandoned lock before backing off', async () => {
+ const lockError = new Error("Unable to create '/repo/.git/index.lock': File exists");
+ execGitMock
+ .mockRejectedValueOnce(lockError)
+ .mockResolvedValueOnce({ stdout: '', stderr: '', exitCode: 0 });
+ const p = addWorktreeWithRetry(['worktree', 'add', '/wt', 'main'], '/repo');
+ await vi.runAllTimersAsync();
+ await p;
+ expect(clearStaleGitLockMock).toHaveBeenCalledWith(lockError.message);
+ });
+
+ // `STALE_GIT_LOCK_MIN_AGE_MS`'s safety argument is "3x the longest git command
+ // PortOS can have in flight", and that ceiling is THIS constant — in another
+ // file, where raising it would silently erode the headroom and let the sweep
+ // unlink a live `git worktree add`'s lock mid-checkout.
+ it('keeps the stale-lock threshold clear of the longest git command in flight', async () => {
+ const { STALE_GIT_LOCK_MIN_AGE_MS } = await vi.importActual('../lib/gitStaleLock.js');
+ expect(STALE_GIT_LOCK_MIN_AGE_MS).toBeGreaterThanOrEqual(3 * WORKTREE_ADD_TIMEOUT_MS);
+ });
+
it('gives up after the max attempts on persistent lock contention', async () => {
execGitMock.mockRejectedValue(new Error('cannot lock ref'));
const p = addWorktreeWithRetry(['worktree', 'add', '/wt', 'main'], '/repo');
@@ -700,6 +729,9 @@ describe('addWorktreeWithRetry (lock-contention retry, #2193)', () => {
await expect(addWorktreeWithRetry(['worktree', 'add', '/wt', 'origin/nope'], '/repo'))
.rejects.toThrow(/invalid reference/);
expect(execGitMock).toHaveBeenCalledTimes(1);
+ // …and nothing reached for the unlink: a failure that named no lock must
+ // never put the stale-lock sweep in motion.
+ expect(clearStaleGitLockMock).not.toHaveBeenCalled();
});
it('does NOT retry an "already exists" precondition failure', async () => {
diff --git a/update.ps1 b/update.ps1
index 2d18856be8..d4a06632a1 100644
--- a/update.ps1
+++ b/update.ps1
@@ -305,6 +305,12 @@ if ($currentBranch -ne "main") {
# post-pull HEAD yields exactly the pull's delta on main, so a manifest change
# the update brings is detected even when launched from another branch.
$prePullSha = git rev-parse HEAD 2>$null
+# Clear locks a PREVIOUS killed update left behind, before anything tries to
+# take them again — see the matching comment in update.sh. The rule for
+# "abandoned" lives in the Node helper so neither shell carries a second copy
+# of it. Never fatal: a failed sweep must not block the update.
+node -e "import('./server/lib/gitStaleLock.js').then(m => m.clearStaleGitLocksIn('.git')).catch(() => {})" 2>$null
+$global:LASTEXITCODE = 0
Invoke-Logged git pull --rebase --autostash
if ($LASTEXITCODE -ne 0) { Stop-UpdateScript $LASTEXITCODE }
Step "git-pull" "done" "Latest changes pulled"
diff --git a/update.sh b/update.sh
index efba285c9e..d5f0ab20ca 100755
--- a/update.sh
+++ b/update.sh
@@ -148,6 +148,15 @@ fi
# post-pull HEAD yields exactly the pull's delta on main, so a manifest change
# the update brings is detected even when launched from another branch.
pre_pull_sha=$(git rev-parse HEAD 2>/dev/null || echo "")
+# Clear locks a PREVIOUS killed update left behind, before anything tries to
+# take them again. This script is the most likely producer of one: PM2 tree-kills
+# the server mid-run and takes the `git pull` / `git submodule update` subprocess
+# with it, and the abandoned lock then fails every later self-update identically,
+# on a file buried under `.git/` that only a human would find. The rule for
+# "abandoned" lives in the Node helper so shell doesn't carry a second copy of
+# it; it refuses any lock young enough to still belong to a running command.
+# Builtins-only, so it runs before `npm install` — and never fatal.
+node -e "import('./server/lib/gitStaleLock.js').then(m => m.clearStaleGitLocksIn('.git')).catch(() => {})" 2>/dev/null || true
run git pull --rebase --autostash
step "git-pull" "done" "Latest changes pulled"