cli-git concurrent commits #
Grilling session started 2026-09-25. Status: design in progress; nothing implemented.
Goal #
Several git commit invocations against the same worktree and branch run at the same time,
and all of them land as separate sequential commits.
Native Git rejects the later ones with index.lock EEXIST;
issue #560 is a real collision.
Evidence #
package/git-policy/cli/src/policy-engine/commit-transaction-workspace.tsopens<index>.lockwithwx, so a second transaction fails immediately instead of waiting.- The lock is held across every policy pass,
the real
git commitincluding its hooks, and post-commit index installation (package/git-policy/cli/SPEC.md, "Transaction protocol"). - Explicit-path commits already build the commit tree in a private index from
HEADplus selected paths. - Policies may read
trackedFilesfor any pathspec andheadOid, and candidatechange/revisionare relative toHEAD(SPEC.md, "Public authoring declarations"), so a verdict can depend onHEADbeyond the candidate bytes. - Local real Git 2.55.0 has
git hook runandgit merge-tree --write-tree --merge-base. git help git,GIT_OPTIONAL_LOCKS:git statustakesindex.lockto refresh the index, so non-cli-git lock holders are routine.- Wrapper-added commit latency in the fixture benchmark is roughly 0.3 to 0.45 seconds
(
package/git-policy/cli/perf/lifecycle-latency-2026-07-16.json); real-repo lock hold time with this repo's plugins is unmeasured.
Private HEAD prototype, 2026-09-25 #
Disposable fixture,
real Git 2.55.0 at /usr/bin/git,
global and system config disabled,
SSH commit signing configured.
- Native
git commitwithGIT_INDEX_FILEprivate and--git-dirpointing at a private per-worktree admin dir (registeredgit worktree add --detach --no-checkout, or hand-builtHEADpluscommondirfile orGIT_COMMON_DIR) and--work-treeat the real worktree ran pre-commit, prepare-commit-msg, commit-msg, post-commit, the editor, template and cleanup, and signing. - Hooks ran with the real worktree top level as cwd,
saw the private index and private
HEAD, and read real worktree files. - Shared
HEAD,refs/heads/main, their reflogs, and real.git/indexbytes stayed unchanged. - Replay with
git merge-tree --write-tree --merge-base,git commit-tree, and compare-and-swapgit update-ref <ref> <new> <old>produced the right tree, parent, author, and committer. Non-overlapping hunks in one file merged; overlapping hunks exited 1 and still printed a tree ID, so callers must check the exit status.
Measured caveats:
- The real index is stale after the ref moves; an ordinary commit afterwards committed a revert. The landing-time real index update is mandatory.
- Hooks inherit
GIT_DIRand relativeGIT_WORK_TREE=.; a hook that changes into a subdirectory and runs Git sees the wrong top level. Ordinary commits export neither. git commit-treeignorescommit.gpgsign; replay must pass-Swhen signing is configured.git update-refwithout-mwrites an empty reflog message.- A registered no-checkout worktree protects its private commit from
gc, appears ingit worktree list, and needsgit worktree remove --force. An unregistered admin dir is invisible, butgit gc --prune=nowdeleted its commits.
Untested:
concurrency,
the wrapper on PATH,
hook frameworks,
GPG signing,
user config,
--amend and --verbose with a private HEAD,
sparse checkout,
submodules,
core.hooksPath,
extensions.worktreeConfig.
Hook environment probe, 2026-09-25 #
Disposable fixture,
real Git 2.55.0.
Driver scripts and raw reports lived in the session scratchpad;
the durable write-ups are
git-hook-disable-switches.md
and
git-private-admin-dir-hook-environment.md.
Handover:
doc/handover/cli-git-concurrent-commits.md.
- No plain invocation gives hooks an absolute
GIT_WORK_TREE: Git rewrites--work-treeandGIT_WORK_TREEto.for hooks. core.worktreefrom-c,GIT_CONFIG_COUNT, or the admin dir'sconfigis ignored, and-c extensions.worktreeConfig=trueis not honoured. Onlyextensions.worktreeConfigin the real common config plus<admin>/config.worktreeworks, which is a persistent repository config write.hook.<event>.enabled=falsesuppresses config-based hooks but not the hookdir hook, contradictinggit help config.-c core.hooksPath=<dir>does not disable config-based hooks.- A dispatcher shim works for hookdir and config-based hooks:
-c core.hooksPath=<shim>plus-c hook.<event>.enabled=falsefor each event, where each shim event exportsGIT_WORK_TREE="$(pwd)"and runsgit -c hook.<event>.enabled=true -c core.hooksPath=<original> hook run --ignore-missing <event> -- "$@". Hooks saw an absolute work tree and correct subdirectory views, failures propagated, andpost-commitdid not run. Every-cleaks to hook children throughGIT_CONFIG_PARAMETERS. - After landing,
git hook run post-commitin the real worktree runs hookdir and config hooks with no private variables, but without the nativeGIT_INDEX_FILE,GIT_AUTHOR_*, andGIT_EDITOR=:. - A
git stash push --keep-indexandgit stash popinside a private pre-commit hook left real index bytes unchanged but transiently reverted the shared worktree's unstaged edit and pushed a transient entry onto the sharedrefs/stash.
Foreign index.lock research, 2026-09-25 #
Git source at commit 0f8e75abebff plus experiments with real Git 2.55.0.
- Git's only index lock is the
O_EXCLfile; there is no advisory lock, and the fd isO_CLOEXEC. - Native
git commit -a,-i,-o, interactive, and partial commits close the lock fd but keepindex.lockon disk through pre-commit, prepare-commit-msg, the editor, and commit-msg (builtin/commit.c, lines 402 to 550 and 1957). Measured: a 3 second hook meant 3 seconds of lock with no holder. So no open holder does not mean abandoned. - Plain
git commitof staged changes releases the lock before hooks run. git statusheld the lock for a median of about 3.2 ms in a 10,000-file fixture.core.lockfilePid=true(default false, present in 2.55.0) writesindex~pid.lockwith the owner PID; Git's ownEEXISTmessage useskill(pid, 0)to call a lock stale, and Git never deletes it.- Git has no index lock timeout;
its other lock timeouts
(
core.packedRefsTimeout,core.configLockTimeout, 1000 ms defaults) retry with quadratic backoff and jitter. - After
kill -9, the lock and PID file remained, and an orphaned hook still pointedGIT_INDEX_FILEat the lock. - Holder scans must compare device and inode,
not paths;
/procvisibility stops at other users,hidepid, PID namespaces, and network filesystems. macOS denial is silent. On Windows, aDELETEprobe could delay Git's own rename. git help stash:popwithout an argument takesstash@{0}, the latest entry of sharedrefs/stash, so hook A's pop after hook B's push restores B's stash.
Decisions #
- Meaning: concurrent separate invocations, not one invocation producing several commits.
- Scope: default on in every repository the wrapper runs in.
- Mechanism: parallel preparation, serial landing. The owner chose this over a lock queue because the engineering capacity exists now.
- Replay:
three-way content merge from the preparation base onto the new
HEAD. - Replay conflict: fail, nothing lands, and the diagnostic names conflicting paths and the winning commit; never re-prepare from current worktree bytes.
- Policy re-run after replay:
record each policy's lazy reads
(candidate bytes,
trackedFilespathspecs,headOid) and re-run only policies whose read set changed. Corrected default: an undeclared policy is assumed to read anything and always re-runs. A policy may declare that it reads only through the context, or list its external inputs (worktree files, executables, revisions passed to tools), which cli-git fingerprints. Evidence for the correction: every shipped plugin reads outside the API (forbidden-stringsandmarkdown-lintspawn tools with repository cwd;repository-policycallsreadFileand spawnsgit ls-filesandgit cat-file). - Hook parallelism declaration:
hooks: { concurrentCommits: true }incli-git.config, default false. - Policy input declaration:
inputs?: 'unrestricted' | { readonly external: readonly PolicyInput[] }, default'unrestricted';{ external: [] }means context-only reads.PolicyInputkinds:worktree(pathspecs),executable(path),revision(rev),env(name). Precedent: Nx taskinputs, broad when absent. - No opt-out: no config key and no environment variable disables concurrent commits. Owner rationale: a misbehaving wrapper is a bug to fix, not a reason to disable parts of it.
- Config keys:
indexLock: { unprovenOwnerTimeoutMs: 1000 }andlanding: { reserveAfterLostRaces: 2 }. - Forwarded index writers
(
add,rm,mv,restore --staged,reset, and similar) wait onindex.lockunder the foreign-owner rules before forwarding, and re-forward after a lockEEXISTonly when a disposable fixture proves that command fails before side effects.git statusneeds nothing because its optional lock is skipped silently. Rationale: concurrent agents already collide ongit addtoday. The earlier claim that concurrent commits raise neighbor collision rates was retracted: landing holdsindex.lockfar shorter than today's whole-transaction hold, and the net effect is unmeasured. - Hooks and editor:
run during preparation.
The editor,
prepare-commit-msg, andcommit-msgrun once;pre-commitre-runs outside the landing lock against the replayed index whenever the replayed tree differs, then landing retries. - Landing order: preparation completion order.
- Starvation guard: after K lost landing races a commit reserves the next landing slot; others keep preparing and revalidating but cannot land until it lands or fails. K defaults to 2, is tunable, and the concurrent-commit benchmark confirms the default.
- Waiting:
unbounded while the cli-git landing owner is alive;
bounded for an
index.lockwithout a known owner. --amendand merge, cherry-pick, revert conclusions fail whenHEADmoved.- Hook concurrency:
a per-repository hook lock serializes preparation hooks and post-landing
post-commitby default;cli-git.configcan declare the repository's hooks safe for parallel preparation. - Foreign
index.lock: cli-git injectscore.lockfilePid=trueinto every forwarded and spawned Git. Proven-live owners (open holder by device and inode, or a PID file naming a live process started no later than the lock's ctime) get an unbounded wait with one line naming the holder. Dead or evidence-free owners get Git-style quadratic backoff up to 1000 ms, configurable incli-git.config, then a diagnostic listing the evidence. cli-git never deletes a lock. - Index commits participate with the index captured at invocation.
- Auto-push: single-flight per branch. A landed commit joins an in-flight push covering its OID or pushes the branch tip itself, and exits only once the remote contains its OID.
Recommendation calibration #
Owner,
2026-09-25:
engineering budget is not a constraint;
recommend the most correct and performant option,
never the cheapest to build.
This applies to this design session only;
the owner declined an AGENTS.md rule.
Settled by the decisions, veto open #
- Same worktree and branch only; Git refuses one branch checked out in two worktrees.
- Each commit captures selected bytes at invocation, inherent in parallel preparation.
- The post-commit real index is computed at landing against the then-current real index, never against the invocation-time copy, or a landing would erase another commit's staging.
- Transaction journals become per transaction, so several prepared transactions coexist; recovery handles each.
- Replay onto a moved
HEADusesgit merge-tree --write-tree --merge-base; cli-git declares a minimum Git version covering the plumbing it uses. - Preparation runs native
git commitagainst a private index and a private admin dirHEAD, per the prototype. - When
HEADdid not move, landing advances the ref to the prepared commit itself, keeping its signature. - Replay signs with
git commit-tree -Swhenever the prepared commit was signed. - The landing critical section holds the landing lock and real
index.lock, advances the ref by compare-and-swap with a-mreflog message carrying the recovery nonce, installs the real index, then releases, so no ordinary commit can observe a moved ref with a stale index. - Pending prepared commits are protected from
gcby a private ref underrefs/cli-git/, deleted at landing, abort, or recovery; the private admin dir stays unregistered, sogit worktree listnever shows it. The ref is briefly visible togit for-each-refandgit log --all. - Hooks during preparation run through the dispatcher shim.
It resolves the repository's own
core.hooksPath, respects user-disabled events, omitspost-commit, exports an absoluteGIT_WORK_TREE, and restores the caller's originalGIT_CONFIG_PARAMETERSbefore dispatch. Shim executables follow the repository's no-shell-script rule.extensions.worktreeConfigis rejected: it mutates every repository's config and still needs the shim forpost-commit. post-commitruns once after landing throughgit hook run post-commitin the real worktree, with native-equivalentGIT_INDEX_FILE,GIT_AUTHOR_*, andGIT_EDITOR=:.- A replay conflict is a
core-findingJSONL event with exit1, matching other expected commit rejections. - New JSONL events report replays and lost landing races.
- Each commit records the symbolic
HEADtarget at invocation; if it changed before landing (branch switch), the commit fails like a moved amend base. DetachedHEADlands by compare-and-swap onHEADitself. - A crashed reservation holder releases its slot through the same owner-liveness check.
git cli-git fixholds the landing lock across its worktree installation and real-index verification, so a concurrent landing cannot falsify its byte-identical real index check.- Windows holder detection skips the
DELETE-access probe, which can delay Git's own rename, and relies on the PID file and Restart Manager. - Missing optional Git features degrade per feature
(no
core.lockfilePidmeans no PID evidence); missing replay plumbing falls back to today's fail-fast behavior. - Required disposable fixtures and lifecycle benchmarks gain concurrent-commit scenarios.
Rejected #
- Lock queue with the unchanged transaction: owner prefers parallel preparation now.
- Batch syntax producing several commits from one invocation.
Open questions #
None. Awaiting owner confirmation of shared understanding.
Next action #
Owner confirms shared understanding.
Then promote this plan to doc/decision/,
update package/git-policy/cli/SPEC.md,
and open the implementation issue.
No implementation before confirmation.