Git Cannot Lock Ref with Parallel Coding Agents and CI: Safe Recovery
Git locks refs so concurrent updates cannot silently corrupt branch state. With parallel coding agents or CI jobs, cannot lock ref is often an architecture warning: multiple writers are sharing a repository or racing to update the same branch.
Do not immediately delete every .lock file. First determine whether another Git process is active.
Diagnose the exact failure
git status --short --branch
git rev-parse --git-dir
git show-ref --heads
ps aux | grep '[g]it'
Different messages imply different causes:
File exists: an active or stale lock may exist;is at X but expected Y: another writer updated the ref first;- namespace conflict: a ref name collides with an existing path;
- permission denied: repository ownership or filesystem access is wrong.
Stop concurrent writers
One working directory should not host several write-capable agents at once. Give agents separate branches and preferably separate Git worktrees. Serialize operations that update shared refs, tags, or the target branch.
CI jobs should not push directly from multiple matrix workers. Let workers produce results, then use one reviewed integration job to update the branch.
Handle a stale lock safely
Only after confirming no Git process uses the repository, inspect the exact lock path reported by Git. Preserve current work and repository state before removing that specific stale lock. Never use a broad recursive deletion pattern.
Then run:
git fsck --no-dangling
git fetch --prune
git status
If the expected/current ref values differ, fetch and rebase or merge through the teamβs normal workflow rather than forcing the ref.
Agent-safe design
- one worktree per agent;
- one branch per task;
- no background auto-fetch during critical writes where it causes contention;
- explicit ownership for integration and push;
- protected target branches;
- status and diff checks before commits;
- retry only after refreshing the expected ref.
The Git foundation explains worktrees and refs. Coding Agents covers agent workflows, GitHub Actions covers CI gates, and AI Testing & Evaluation covers checks before integration.
A lock error should result in coordination, not a force push.