fix(#2772): only disable worktree isolation when planned paths touch submodules (#2779)

* fix(#2772): only disable worktree isolation when planned paths touch submodules

The previous guard in execute-phase.md and quick.md unconditionally set
USE_WORKTREES=false whenever .gitmodules existed, penalising every plan in
a submodule project even when no plan touched a submodule path.

Replace with submodule-path parsing + per-plan path intersection:

- Parse SUBMODULE_PATHS once from .gitmodules via
  `git config --file .gitmodules --get-regexp '^submodule\..*\.path$'`.
- In execute-phase.md, intersect SUBMODULE_PATHS with each plan's
  files_modified frontmatter; disable worktree isolation only for plans
  with non-empty intersection. Fall back to safe-disable for that plan
  when files_modified is missing/unparseable, with a log line explaining
  why.
- In quick.md (no pre-declared paths), keep submodule-path parsing and
  document a fail-loud commit-time guard so the executor aborts only when
  it actually stages a submodule path.

Add tests/bug-2772-gitmodules-path-intersection.test.cjs covering both
files: no unconditional disable, submodule paths are parsed, intersection
logic exists in execute-phase, fallback path is documented.

Full suite: 5680 / 5680 pass.

Closes #2772

* test(#2772): replace source-grep with behavioral test of submodule path intersection

* fix(#2772): wire USE_WORKTREES_FOR_PLAN into dispatch + fix glob matcher + add quick.md commit guard

Address CodeRabbit review on PR #2779 — the original fix computed
USE_WORKTREES_FOR_PLAN but never read it, so the per-plan submodule
intersection was dead code. Dispatch sites still branched on the
project-level USE_WORKTREES.

Changes:

1. execute-phase.md (CRITICAL — dispatch wiring): Move per-plan
   computation into execute_waves as sub-step 2.5, run it for each plan
   before its dispatch, and gate all four dispatch sites on
   USE_WORKTREES_FOR_PLAN: worktree-mode header, sequential-mode header,
   "worktrees disabled" sequential rule, and post-wave cleanup. Document
   PLAN_FILES extraction via jq from the phase-plan-index JSON. Track
   WAVE_WORKTREE_PLANS so post-wave cleanup only runs when at least one
   plan in the wave actually used worktrees.

2. Per-plan gate matcher (MAJOR — glob safety): Strip leading "./" and
   trailing "/" from both submodule and planned paths. Match
   bidirectionally (pf inside sm AND sm inside pf). Handle globby
   planned paths like "vendor/**/*.c" by extracting the literal prefix
   before the first glob metachar and re-checking. Wrap the iteration
   in set -f / set +f so glob expansion does not corrupt patterns.
   Extracted the gate (~92 lines) into
   workflows/execute-phase/steps/per-plan-worktree-gate.md to keep
   execute-phase.md under the 1700-line XL budget.

3. quick.md (CRITICAL — fail-loud guard): Inject SUBMODULE_PATHS into
   the executor Task prompt and add a <submodule_commit_guard> bash
   block the executor must run before every git commit. The guard
   inspects staged paths via `git diff --cached --name-only`, normalizes
   paths, and aborts with a clear ABORT message + recovery instruction
   ("re-run with workflow.use_worktrees=false") when any staged path
   falls inside a submodule.

4. tests/bug-2772-gitmodules-path-intersection.test.cjs: 25 tests total.
   Updated GATE_SNIPPET to match the new bash matcher. Added
   normalization tests (./ prefix, trailing /, glob "vendor/**/*.c",
   parent directory, ./ in .gitmodules). Added workflow-markdown
   wiring assertions for all 4 dispatch sites + per-plan gate file
   extraction. Added quick.md guard tests: prompt injection assertion +
   behavioral fixture-repo tests that stage a submodule path and assert
   the guard exits non-zero with the ABORT message.

Test count: 5701 pass / 0 fail (was 5698/1 before).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-04-27 12:31:32 -04:00
committed by GitHub
parent 77d929429f
commit 8b6c44433f
4 changed files with 729 additions and 15 deletions

View File

@@ -84,16 +84,21 @@ Read worktree config:
USE_WORKTREES=$(gsd-sdk query config-get workflow.use_worktrees 2>/dev/null || echo "true")
```
If the project uses git submodules, worktree isolation is skipped regardless of the `workflow.use_worktrees` config — the executor commit protocol cannot correctly handle submodule commits inside isolated worktrees. Sequential execution handles submodules transparently.
If the project uses git submodules, worktree isolation is unsafe **only when a plan touches a submodule path** — the executor commit protocol cannot correctly handle submodule commits inside isolated worktrees. The previous behavior unconditionally disabled worktree isolation whenever `.gitmodules` existed, which penalised every plan in a submodule project even when the plan was nowhere near a submodule. Compute submodule paths once and intersect them per-plan with the plan's declared `files_modified` frontmatter.
```bash
# Parse submodule paths from .gitmodules once (empty if no .gitmodules).
# SUBMODULE_PATHS is a newline-separated list of repo-relative paths.
if [ -f .gitmodules ]; then
echo "[worktree] Submodule project detected (.gitmodules exists) — falling back to sequential execution"
USE_WORKTREES=false
SUBMODULE_PATHS=$(git config --file .gitmodules --get-regexp '^submodule\..*\.path$' 2>/dev/null | awk '{print $2}')
else
SUBMODULE_PATHS=""
fi
```
When `USE_WORKTREES` is `false`, all executor agents run without `isolation="worktree"` — they execute sequentially on the main working tree instead of in parallel worktrees.
`SUBMODULE_PATHS` is exported to the `execute_waves` step, where the per-plan decision actually happens (see "Per-plan worktree decision" sub-step inside `execute_waves`). The decision is per-plan because different plans in the same wave can touch different files — only plans whose paths intersect a submodule must drop worktree isolation; plans nowhere near a submodule keep parallel isolation.
When `USE_WORKTREES` (project-level) is `false`, all executor agents run without `isolation="worktree"` — they execute sequentially on the main working tree instead of in parallel worktrees. The per-plan decision below has no effect when worktrees are project-disabled.
Read context window size for adaptive prompt enrichment:
@@ -418,6 +423,12 @@ increases monotonically across waves. `{status}` is `complete` (success),
- Bad: "Executing terrain generation plan"
- Good: "Procedural terrain generator using Perlin noise — creates height maps, biome zones, and collision meshes. Required before vehicle physics can interact with ground."
2.5. **Per-plan worktree decision (run for each plan in this wave BEFORE its dispatch):**
Read and execute `get-shit-done/workflows/execute-phase/steps/per-plan-worktree-gate.md` for each plan. It extracts `PLAN_FILES` from the plan's JSON, intersects against `SUBMODULE_PATHS` (with normalization, bidirectional matching, and glob-prefix handling), and sets `USE_WORKTREES_FOR_PLAN` to `false` when the plan touches a submodule path. Append `plan_id` to a `WAVE_WORKTREE_PLANS` accumulator when `USE_WORKTREES_FOR_PLAN != false`.
The dispatch branches in step 3 below MUST gate on `USE_WORKTREES_FOR_PLAN` for the current plan, not on the project-level `USE_WORKTREES`.
3. **Spawn executor agents:**
**Emit a plan-start heartbeat (literal line, no tool call) immediately before
@@ -431,7 +442,7 @@ increases monotonically across waves. `{status}` is `complete` (success),
For 200k models, this keeps orchestrator context lean (~10-15%).
For 1M+ models (Opus 4.6, Sonnet 4.6), richer context can be passed directly.
**Worktree mode** (`USE_WORKTREES` is not `false`):
**Worktree mode** (`USE_WORKTREES_FOR_PLAN` is not `false` — evaluated per-plan in step 2.5):
Before spawning, capture the current HEAD:
```bash
@@ -562,7 +573,7 @@ increases monotonically across waves. `{status}` is `complete` (success),
> **ORCHESTRATOR RULE — CODEX RUNTIME**: After calling Task() above to spawn executor agent(s), stop working on this task immediately. Do not read more files, edit code, or run tests related to this task while the subagent is active. Wait for the subagent to return its result. This prevents duplicate work, conflicting edits, and wasted context. Only resume when the subagent result is available.
**Sequential mode** (`USE_WORKTREES` is `false`):
**Sequential mode** (`USE_WORKTREES_FOR_PLAN` is `false` — either project-level `USE_WORKTREES=false`, or per-plan submodule intersection forced it false in step 2.5):
Omit `isolation="worktree"` from the Task call. Replace the `<parallel_execution>` block with:
@@ -585,7 +596,7 @@ increases monotonically across waves. `{status}` is `complete` (success),
</success_criteria>
```
When worktrees are disabled, execute plans **one at a time within each wave** (sequential) regardless of the `PARALLELIZATION` setting — multiple agents writing to the same working tree concurrently would cause conflicts.
When worktrees are disabled for a plan (per-plan or project-level), that plan's executor runs on the main working tree. If **any** plan in the current wave dropped to sequential mode, execute the affected plan(s) **one at a time** to avoid concurrent writes to the main working tree — plans in the same wave that retained worktree isolation can still run in parallel alongside the sequential ones, but two non-worktree plans in the same wave must serialize. When the project-level `USE_WORKTREES=false`, all plans in the wave serialize regardless of the `PARALLELIZATION` setting.
4. **Wait for all agents in wave to complete.**
@@ -763,9 +774,11 @@ increases monotonically across waves. `{status}` is `complete` (success),
done < <(git worktree list --porcelain | grep "^worktree " | grep "\.claude/worktrees/agent-" | sed 's/^worktree //')
```
**If `workflow.use_worktrees` is `false`:** Agents ran on the main working tree — skip this step entirely.
**If no plan in this wave used worktree isolation** (project-level `USE_WORKTREES=false` OR every plan in the wave had `USE_WORKTREES_FOR_PLAN=false` — i.e. `WAVE_WORKTREE_PLANS` from step 2.5 is empty): all agents ran on the main working tree — skip this step entirely.
**If no worktrees found:** Skip silently — agents may have been spawned without worktree isolation.
**If at least one plan used worktrees but others did not:** still run this cleanup — it iterates over actual `git worktree list` output and only merges back the worktrees that were created, leaving sequential plans' commits on the main tree untouched.
**If no worktrees found at runtime:** Skip silently — agents may have been spawned without worktree isolation, or the orchestrator already cleaned them up.
5.6. **Post-merge build & test gate:**
@@ -780,9 +793,9 @@ increases monotonically across waves. `{status}` is `complete` (success),
Read and execute `get-shit-done/workflows/execute-phase/steps/post-merge-gate.md`.
5.7. **Post-wave shared artifact update (worktree mode only, skip if tests failed):**
5.7. **Post-wave shared artifact update (when at least one plan used worktrees, skip if tests failed):**
When executor agents ran with `isolation="worktree"`, they skipped STATE.md and ROADMAP.md updates to avoid last-merge-wins overwrites. The orchestrator is the single writer for these files. After worktrees are merged back, update shared artifacts once.
When **any** executor agent in this wave ran with `isolation="worktree"`, that agent skipped STATE.md and ROADMAP.md updates to avoid last-merge-wins overwrites. The orchestrator is the single writer for these files. After worktrees are merged back, update shared artifacts once for every completed plan in the wave (worktree-mode plans **and** sequential plans that ran on the main tree but deferred to the orchestrator for tracking writes).
**Only update tracking when tests passed (TEST_EXIT=0).**
If tests failed or timed out, skip the tracking update — plans should
@@ -810,7 +823,7 @@ increases monotonically across waves. `{status}` is `complete` (success),
Where `WAVE_PLAN_IDS` is the space-separated list of plan IDs that completed in this wave.
**If `workflow.use_worktrees` is `false`:** Sequential agents already updated STATE.md and ROADMAP.md themselves — skip this step.
**If no plan in this wave used worktrees** (project-level `USE_WORKTREES=false` OR `WAVE_WORKTREE_PLANS` is empty): sequential agents already updated STATE.md and ROADMAP.md themselves — skip this step.
5.8. **Handle test gate failures (when `WAVE_FAILURE_COUNT > 0`):**

View File

@@ -0,0 +1,94 @@
# Per-plan worktree decision (#2772)
Run this for **each plan in the current wave** before its `Task()` dispatch. The output `USE_WORKTREES_FOR_PLAN` gates the dispatch branch (worktree mode vs sequential mode) for that plan only — other plans in the same wave can still take the worktree path.
`SUBMODULE_PATHS` is computed once in the `initialize` step (parsed from `.gitmodules`).
`PLAN_FILES` is the whitespace-separated list of paths the plan declared it will touch, extracted from the `phase-plan-index` JSON loaded in `discover_and_group_plans`:
```bash
# plan_json is the JSON object for this plan from PLAN_INDEX.plans[]
# files_modified is an array of strings (repo-relative paths or globs)
PLAN_FILES=$(jq -r '.files_modified // [] | join(" ")' <<<"$plan_json")
plan_id=$(jq -r '.id' <<<"$plan_json")
```
Then run the per-plan gate:
```bash
USE_WORKTREES_FOR_PLAN="$USE_WORKTREES"
if [ -n "$SUBMODULE_PATHS" ] && [ "$USE_WORKTREES_FOR_PLAN" != "false" ]; then
if [ -z "$PLAN_FILES" ]; then
# Fallback: planned paths are unknown/unparseable — fall back to the safe
# behavior (disable worktree isolation for this plan) and log why.
echo "[worktree] Plan ${plan_id}: files_modified missing/unparseable — disabling worktree isolation as a safety fallback (submodule project)"
USE_WORKTREES_FOR_PLAN=false
else
# Compute intersection with glob-safe normalization. Both sides are
# normalized (strip leading "./", strip trailing "/") and matched
# bidirectionally so a globby planned path like "vendor/**/*.c" still
# matches submodule "vendor/foo", and "./vendor/foo/bar.c" matches
# submodule "vendor/foo".
INTERSECT=""
set -f # disable globbing while iterating literal patterns
for sm_raw in $SUBMODULE_PATHS; do
# Normalize submodule path: strip ./ prefix and trailing /
sm="${sm_raw#./}"
sm="${sm%/}"
[ -z "$sm" ] && continue
for pf_raw in $PLAN_FILES; do
# Normalize planned path the same way
pf="${pf_raw#./}"
pf="${pf%/}"
[ -z "$pf" ] && continue
matched=0
# Direction 1: planned path is the submodule or lies inside it
case "$pf" in
"$sm"|"$sm"/*) matched=1 ;;
esac
# Direction 2: submodule lies inside the planned path (e.g. plan
# declares "vendor" or a glob expanding to a directory containing
# the submodule).
if [ "$matched" -eq 0 ]; then
case "$sm" in
"$pf"|"$pf"/*) matched=1 ;;
esac
fi
# Direction 3: planned path uses a glob — strip glob wildcards
# and check whether the resulting prefix overlaps the submodule
# path in either direction.
if [ "$matched" -eq 0 ]; then
case "$pf" in
*'*'*|*'?'*|*'['*)
# Take the literal prefix before the first glob metachar.
prefix="${pf%%[*?[]*}"
prefix="${prefix%/}"
if [ -n "$prefix" ]; then
case "$sm" in
"$prefix"|"$prefix"/*) matched=1 ;;
esac
if [ "$matched" -eq 0 ]; then
case "$prefix" in
"$sm"|"$sm"/*) matched=1 ;;
esac
fi
fi
;;
esac
fi
if [ "$matched" -eq 1 ]; then
INTERSECT="$INTERSECT $pf_raw"
fi
done
done
set +f
if [ -n "$INTERSECT" ]; then
echo "[worktree] Plan ${plan_id}: planned paths intersect submodule paths (${INTERSECT# }) — disabling worktree isolation for this plan"
USE_WORKTREES_FOR_PLAN=false
fi
fi
fi
```
After running this for the plan, the dispatch branches in `execute_waves` step 3 MUST gate on `USE_WORKTREES_FOR_PLAN` for the current plan, not on the project-level `USE_WORKTREES`. Track which plans in this wave actually used worktrees (append `plan_id` to a `WAVE_WORKTREE_PLANS` accumulator when `USE_WORKTREES_FOR_PLAN != false`) — the post-wave cleanup step (5.5) uses this to decide whether worktree-merge cleanup is needed at all.

View File

@@ -152,15 +152,24 @@ Parse JSON for: `planner_model`, `executor_model`, `checker_model`, `verifier_mo
USE_WORKTREES=$(gsd-sdk query config-get workflow.use_worktrees 2>/dev/null || echo "true")
```
If the project uses git submodules, worktree isolation is skipped:
If the project uses git submodules, worktree isolation is unsafe **only when the quick task touches a submodule path**. The previous behavior unconditionally disabled worktree isolation whenever `.gitmodules` existed, which penalised every quick task in a submodule project even when the task was nowhere near a submodule. Parse submodule paths from `.gitmodules` so the executor can act on actual submodule paths rather than the mere file's existence:
```bash
# Parse submodule paths from .gitmodules once (empty if no .gitmodules).
# SUBMODULE_PATHS is a newline-separated list of repo-relative paths used as
# a fail-loud commit-time guard inside the quick-task executor — if the
# executor stages any path that falls inside SUBMODULE_PATHS, it must abort
# the commit and surface the conflict rather than silently corrupting the
# submodule state.
if [ -f .gitmodules ]; then
echo "[worktree] Submodule project detected (.gitmodules exists) — falling back to sequential execution"
USE_WORKTREES=false
SUBMODULE_PATHS=$(git config --file .gitmodules --get-regexp '^submodule\..*\.path$' 2>/dev/null | awk '{print $2}')
else
SUBMODULE_PATHS=""
fi
```
Quick mode does not have a pre-declared `files_modified` list (the task is freeform), so use a fail-loud guard at commit time: when the executor stages files for the quick-task commit, if any staged path falls inside a `SUBMODULE_PATHS` entry, abort with a clear error explaining that worktree-isolated commits cannot safely span submodule boundaries — the user can re-run with `workflow.use_worktrees=false` to fall back to sequential execution on the main tree. If `SUBMODULE_PATHS` is empty (no `.gitmodules` in the repo), worktree isolation proceeds normally.
**If `roadmap_exists` is false:** Error — Quick mode requires an active project with ROADMAP.md. Run `/gsd-new-project` first.
Quick tasks can run mid-phase - validation only checks ROADMAP.md exists, not phase status.
@@ -627,9 +636,44 @@ This corrects a known issue where EnterWorktree creates branches from main inste
${AGENT_SKILLS_EXECUTOR}
<submodule_commit_guard>
SUBMODULE_PATHS for this project: ${SUBMODULE_PATHS}
If SUBMODULE_PATHS is non-empty, you MUST run this fail-loud guard immediately
before EVERY git commit you create during this quick task (after \`git add\`,
before \`git commit\`). Quick mode does not have a pre-declared files_modified
list, so the guard runs at commit time:
\`\`\`bash
SUBMODULE_PATHS=\"${SUBMODULE_PATHS}\"
if [ -n \"\$SUBMODULE_PATHS\" ]; then
STAGED=\$(git diff --cached --name-only)
for sm_raw in \$SUBMODULE_PATHS; do
sm=\"\${sm_raw#./}\"
sm=\"\${sm%/}\"
[ -z \"\$sm\" ] && continue
for f_raw in \$STAGED; do
f=\"\${f_raw#./}\"
f=\"\${f%/}\"
case \"\$f\" in
\"\$sm\"|\"\$sm\"/*)
echo \"ABORT: staged path \$f_raw falls inside submodule \$sm — worktree-isolated commits cannot safely span submodule boundaries. Re-run with workflow.use_worktrees=false.\" >&2
exit 1 ;;
esac
done
done
fi
\`\`\`
If the guard aborts, do NOT attempt the commit, do NOT remove the staged files,
and do NOT continue subsequent tasks. Surface the abort message in your
SUMMARY.md and stop — the user must rerun with worktrees disabled.
</submodule_commit_guard>
<constraints>
- Execute all tasks in the plan
- Commit each task atomically (code changes only)
- Run the <submodule_commit_guard> bash block before every \`git commit\` if SUBMODULE_PATHS is non-empty
- Create summary at: ${QUICK_DIR}/${quick_id}-SUMMARY.md
- Do NOT commit docs artifacts (SUMMARY.md, STATE.md, PLAN.md) — the orchestrator handles the docs commit in Step 8
- Do NOT update ROADMAP.md (quick tasks are separate from planned phases)