diff --git a/docs/reference/FEATURES.md b/docs/reference/FEATURES.md index 19db34a4..38998006 100644 --- a/docs/reference/FEATURES.md +++ b/docs/reference/FEATURES.md @@ -50,7 +50,7 @@ GENERATED , do not hand-edit. Regenerate: `bash lib/registry/feature-registry.sh | `/kit:verify` | `[H/I]` | Re-run the test levels (kit:task-verifier + kit:integration-verifier + kit:acceptance-verifier, plus kit:system-verifier only with --full) … | SPEC-002, SPEC-003, SPEC-006 +57 | test-board-digest.sh, test-board-hermes.sh, test-board-lock-required.sh +35 | | `/kit:visual-team` | `[H/I]` | Parallel multi-lens critique of a visual/UI design. Dispatches 5 design lenses, merges findings, reports a verdict. Report-only, downstream… | SPEC-016, SPEC-018, SPEC-019 +12 | test-command-emit-sweep.sh, test-meta-review-verifiers.sh, test-meta-spec-depth.sh +1 | | `/kit:wayfind` | `[H]` | Plan a chunk of work too big for one agent session as a shared decision map: map.md + typed decision tickets in the mega-goal folder, resol… | SPEC-206, SPEC-207, SPEC-217 +2 | - | -| `/kit:wrap` | `[H/I]` | The session-scoped landing step after ship: flips board rows, merges green PRs, checks deploys, tidies worktrees, prints the skim-first rep… | SPEC-020, SPEC-060, SPEC-072 +75 | test-bash32-parse.sh, test-bin-forwarders.sh, test-board-lock-required.sh +56 | +| `/kit:wrap` | `[H/I]` | The session-scoped landing step after ship: flips board rows, merges green PRs, checks deploys, tidies worktrees, prints the skim-first rep… | SPEC-020, SPEC-060, SPEC-072 +75 | test-bash32-parse.sh, test-bin-forwarders.sh, test-board-lock-required.sh +57 | ## Agents diff --git a/docs/verification/worktree-removers-ignored-guard.md b/docs/verification/worktree-removers-ignored-guard.md new file mode 100644 index 00000000..3087a7f5 --- /dev/null +++ b/docs/verification/worktree-removers-ignored-guard.md @@ -0,0 +1,154 @@ +# Verification: worktree-removers-ignored-guard + +Headless shell library fix (off `origin/master`): no visible UI surface. + +Closes the remaining user-worktree removal paths outside `lib/wrap/wrap-apply.sh` that still called `git worktree remove --force` / `-f -f` without checking for unique ignored files, hidden index edits, initialized submodules, or uncommitted work: + +- `lib/goal/wt.sh` (`close`) +- `lib/queue/orchestrate.sh` (`_wave_worktree`) + +`lib/adapters/hermes/board-writeback.sh` stays identical to `origin/master` by design: writeback creates and owns its throwaway scratch worktree on the fixed `chore/board-sync` branch for only its own staged edit, and refusing removal there wedges later writeback runs on `chore/board-sync`. + +## Root cause and fix + +1. Extracted the worktree safety helpers (`_san`, `_ignored_match`, `_ARCHIVE_IGNORED_REGENERABLE`, `_wt_status_raw`, `_wt_status`, `_wt_hidden_edits`, `_wt_init_submodule`, `_wt_synced_copy`, `_wt_ignored_blockers`, `_wt_ignored_guard`) out of `lib/wrap/wrap-common.sh` and `lib/wrap/wrap-apply.sh` into one shared file: `lib/wrap/wt-guard.sh`, safe under both `set -uo pipefail` and `set -euo pipefail` and bash 3.2+. Added `_wt_main_checkout` and `_wt_remove_guard` (two-pass status check with `cmp -s` stability verification right before `git worktree remove`). +2. `lib/wrap/wrap-common.sh` and `lib/wrap/wrap-apply.sh` source `lib/wrap/wt-guard.sh` instead of keeping duplicate definitions. +3. `lib/goal/wt.sh`: sources `lib/wrap/wt-guard.sh`, runs `_wt_remove_guard` before removing `$wt`, checks `git worktree remove -f -f "$wt"` exit status, and releases the registry claim (`goal-registry.sh release`) only after the worktree removal succeeds. Any guard or remove failure exits 1 with the reason on stderr and leaves the registry claim, worktree, local branch, and remote branch untouched. +4. `lib/queue/orchestrate.sh`: sources `lib/wrap/wt-guard.sh` and runs `_wt_remove_guard` inside `_wave_worktree` before removing any non-reusable worktree. Refusal returns 1 with the guard reason on stderr and leaves the worktree intact. Fixed 7 pre-existing shellcheck `-S warning` lines in `orchestrate.sh` (`SC1010` quoted `"done"` args, `SC2097`/`SC2098` local capture before subshell). + +## Baseline red runs + +### 1. Missing worktree guard on unmodified origin/master (e75b5b2d) + +```text +Command: bash tests/test-worktree-removers-ignored.sh +Exit: 1 +Output: +=== A. lib/goal/wt.sh close === + FAIL wt env: refuses (nonzero) + FAIL wt env: says why (.env) + FAIL wt env: kept file exists +... +=== B. lib/queue/orchestrate.sh (_wave_worktree) === + FAIL wave env: refuses (nonzero) + FAIL wave env: says why (.env) + FAIL wave env: .env kept +... +test-worktree-removers-ignored: 28 passed, 92 FAILED of 120 +Verdict: RED (reproduced on unmodified origin/master) +``` + +### 2. Early registry-claim release before failed worktree remove (review B2, red before fix) + +```text +Command: /bin/bash tests/test-worktree-removers-ignored.sh +Exit: 1 +Output: + PASS wt rmfail: setup claim exists + PASS wt rmfail: refuses (nonzero) + PASS wt rmfail: says worktree remove failed + FAIL wt rmfail: registry claim survives + PASS wt rmfail: kept file exists + PASS wt rmfail: worktree exists + PASS wt rmfail: local branch exists + PASS wt rmfail: origin branch exists +... +test-worktree-removers-ignored: 106 passed, 1 FAILED of 107 +Verdict: RED (claim was released before git worktree remove failed) +``` + +## Green runs + +### 1. Shellcheck across all touched shell scripts + +```text +Command: shellcheck --norc -S warning lib/wrap/wt-guard.sh lib/goal/wt.sh lib/queue/orchestrate.sh tests/test-worktree-removers-ignored.sh +Exit: 0 +Output: +(no warnings or errors) +Verdict: PASS +``` + +### 2. New remover suite, wrap-apply-ignored, orchestrate, and adapter suites on macOS bash 3.2 and bash 5 + +```text +Command: /bin/bash tests/test-worktree-removers-ignored.sh && bash tests/test-worktree-removers-ignored.sh && /bin/bash tests/test-wrap-apply-ignored.sh && bash tests/test-wrap-apply-ignored.sh && /bin/bash lib/adapters/tests/test-adapters.sh && bash lib/adapters/tests/test-adapters.sh && /bin/bash tests/test-orchestrate-hardening.sh && /bin/bash tests/test-wave-converge.sh +Exit: 0 +Output: +test-worktree-removers-ignored: all 107 passed +test-worktree-removers-ignored: all 107 passed +test-wrap-apply-ignored: all 211 passed +test-wrap-apply-ignored: all 211 passed +=== 218 passed, 0 failed === +=== 218 passed, 0 failed === +=== 13/13 passed, 0 failed === +All wave-converge tests passed. +Verdict: PASS +``` + +### 3. Feature registry freshness + +```text +Command: bash lib/registry/feature-registry.sh check +Exit: 0 +Output: +feature-registry: docs/reference/FEATURES.md is fresh +Verdict: PASS +``` + +### 4. Diff-scoped affected suites (`run-all.sh --changed --time`, all 90/90 green) + +```text +Command: RUN_ALL_TIMEOUT_SECS=450 bash tests/run-all.sh --changed --time +Exit: 0 +Output: +run-all: --changed against e75b5b2d: 9 changed files -> 91 suites (84 named, the rest always-on) +test-harness-dispatch skip (needs opencode) +run-all: 90 suites, 4 at a time, 1 serial +test-board-writeback ok (13s) +test-branch-merged-callers ok (37s) +test-kit-contract ok (5s) +test-meta-docs-registry ok (15s) +test-no-personal-paths ok (1s) +test-no-scattered-ids ok (2s) +test-operator-pin ok (6s) +test-orchestrate ok (109s) +test-shared-lookups ok (1s) +test-worktree-removers-ignored ok (16s) +test-wrap-apply-ignored ok (47s) +test-wrap-apply ok (226s) +test-wrap-sweep ok (48s) +lib-adapters-test-adapters ok (33s) +run-all: all 90 suites passed, 1 skipped for missing tooling +Verdict: PASS +``` + +## Negative control + +Four planted faults tested in isolated scratch copies against `tests/test-worktree-removers-ignored.sh` under `/bin/bash` (3.2): bypassing `_wt_remove_guard` in `wt.sh` (`m1-wt-bypass`) and `orchestrate.sh` (`m2-orch-bypass`), moving `goal-registry.sh release` back before `git worktree remove` in `wt.sh` (`m3-wt-early-release`), and dropping the second-pass `cmp -s "$raw1" "$raw2"` check in `lib/wrap/wt-guard.sh` (`m4-drop-2nd-pass`). Every mutant turned the suite red: + +```text +Command: python3 # plants 1 fault per scratch copy and runs /bin/bash tests/test-worktree-removers-ignored.sh +Exit: 1 +Output: +MUTANT m1-wt-bypass exit=1 test-worktree-removers-ignored: 53 passed, 54 FAILED of 107 +MUTANT m2-orch-bypass exit=1 test-worktree-removers-ignored: 85 passed, 22 FAILED of 107 +MUTANT m3-wt-early-release exit=1 test-worktree-removers-ignored: 106 passed, 1 FAILED of 107 +MUTANT m4-drop-2nd-pass exit=1 test-worktree-removers-ignored: 101 passed, 6 FAILED of 107 +Verdict: RED, as expected +``` + +## Not proven locally + +- Linux / Ubuntu 26.04 execution is verified on GitHub Actions CI (`ubuntu-latest`). +- D22a (`lib/queue/orchestrate.sh` goal-done semantics) was not implemented and was stopped for design clarification in the round-1 report. + +## Rollback + +Revert the branch or merge commit to restore `lib/wrap/wrap-common.sh`, `lib/wrap/wrap-apply.sh`, `lib/goal/wt.sh`, `lib/queue/orchestrate.sh`, and `docs/reference/FEATURES.md`, and remove `lib/wrap/wt-guard.sh`, `tests/test-worktree-removers-ignored.sh`, and this proof file: + +```bash +git revert +``` + +No persistent on-disk state, config schema, or ledger format changes. diff --git a/lib/goal/wt.sh b/lib/goal/wt.sh index d57f8228..9b134600 100755 --- a/lib/goal/wt.sh +++ b/lib/goal/wt.sh @@ -27,6 +27,10 @@ cd "$MAIN" || exit 2 LIB="$MAIN/lib" # shellcheck source=lib/gate/branch-merged.sh source "$LIB/gate/branch-merged.sh" || { echo "wt.sh: lib/gate/branch-merged.sh missing or unreadable" >&2; exit 2; } +_WT_GUARD="$LIB/wrap/wt-guard.sh" +[ -f "$_WT_GUARD" ] || _WT_GUARD="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/wrap/wt-guard.sh" +# shellcheck source=lib/wrap/wt-guard.sh +source "$_WT_GUARD" || { echo "wt.sh: lib/wrap/wt-guard.sh missing or unreadable" >&2; exit 2; } usage() { sed -n '2,20p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit "${1:-2}"; } verb="${1:-}"; shift || true @@ -82,10 +86,22 @@ case "$verb" in if [ -n "$rsha" ] && [ "$rsha" != "$tip" ]; then echo "wt.sh: refusing to close: LEAVE remote $rsha (origin/$br is not at the judged tip)" >&2; exit 1 fi - bash "$LIB/goal/goal-registry.sh" release "$slug" 2>/dev/null || true + if [ -d "$wt" ]; then + main_wt="$(_wt_main_checkout "$MAIN" 2>/dev/null || true)" + if _wt_remove_guard "$wt" "$main_wt"; then + echo "wt.sh: refusing to close: $(_san "$wt"): ${WT_IGN_MSG}" >&2 + exit 1 + fi + fi # -f -f: a single --force no-ops on a locked worktree, and the `git branch -D` below then # fails with "used by worktree", which reads as a second unrelated problem. - [ -d "$wt" ] && git worktree remove -f -f "$wt" + if [ -d "$wt" ]; then + if ! git worktree remove -f -f "$wt"; then + echo "wt.sh: refusing to close: worktree remove failed for $(_san "$wt")" >&2 + exit 1 + fi + fi + bash "$LIB/goal/goal-registry.sh" release "$slug" 2>/dev/null || true git branch -D "$br" >/dev/null # Leased to the tip that was judged: an origin branch that moved on (a newer PR from the same head) stays. git push origin --force-with-lease="refs/heads/$br:$tip" ":refs/heads/$br" >/dev/null 2>&1 || true diff --git a/lib/queue/orchestrate.sh b/lib/queue/orchestrate.sh index a6b8bd69..78805174 100755 --- a/lib/queue/orchestrate.sh +++ b/lib/queue/orchestrate.sh @@ -140,7 +140,7 @@ BACKLOG_LIB="${BACKLOG_LIB:-$LIB_ROOT/board/backlog.sh}" # boxes of SG-NN sub-goals only: a parked box is not done and is never auto-picked, so it is never listed. # shellcheck source=../mega/box.sh . "$LIB_ROOT/mega/box.sh" || exit 1 -_SG_BOX_RE="$(box_re open done)" +_SG_BOX_RE="$(box_re open "done")" # Multi-vendor dispatch adapter: vendor -> headless argv + prompt-delivery mode. # SOURCED, unlike dispatch-gate.sh which must be a subprocess because its `set -euo` would leak `-e` @@ -163,6 +163,9 @@ CONFIG_LIB="${CONFIG_LIB:-$LIB_ROOT/config/kit-config.sh}" # the converge guard's base. Idempotent if a caller already sourced it. # shellcheck source=lib/config/merge-command.sh . "$LIB_ROOT/config/merge-command.sh" || { echo "FATAL: lib/config/merge-command.sh missing or unreadable" >&2; exit 1; } +# Worktree removal guard: keeps unique ignored/uncommitted work before removing a stale worktree. +# shellcheck source=lib/wrap/wt-guard.sh +. "$LIB_ROOT/wrap/wt-guard.sh" || { echo "FATAL: lib/wrap/wt-guard.sh missing or unreadable" >&2; exit 1; } # _kit_bool01 -- normalize a TOML `true`/`false` (or already-0/1) config # value to the `0`/`1` shape orchestrate.sh's env-var knobs use; anything else (unset, typo) @@ -406,7 +409,7 @@ _subgoals() { id=$(printf '%s' "$line" | grep -oE "$BOX_SG_RE" | head -1) [ -n "$id" ] || continue policy=$(printf '%s' "$line" | awk -F',' '{for(i=1;i<=NF;i++){f=$i; gsub(/^[ \t]+|[ \t]+$/,"",f); lf=tolower(f); if(lf=="auto"||lf=="gate"||lf=="gate!"){print lf; exit}}}') - box_line_is done "$line" && checked=1 + box_line_is "done" "$line" && checked=1 printf '%s\t%s\t%s\n' "$id" "${policy:-gate}" "$checked" done || true } @@ -1007,11 +1010,11 @@ cmd_flip() { # megadir id # Re-read the line UNDER the lock: a sibling flip may have checked it since the pre-lock probe. local line rc=0 line=$(_sg_line "$roadmap" "$id") - box_line_is done "$line" && { _unlock "$lockdir"; return 0; } # already checked -> idempotent no-op + box_line_is "done" "$line" && { _unlock "$lockdir"; return 0; } # already checked -> idempotent no-op local tmp tmp=$(mktemp "$megadir/.roadmap.flip.XXXXXX" 2>/dev/null) || { _unlock "$lockdir"; echo "flip: mktemp failed" >&2; return 1; } - if awk -v id="$id" -v otok="$(box_token open)" -v dtok="$(box_token done)" \ + if awk -v id="$id" -v otok="$(box_token open)" -v dtok="$(box_token "done")" \ '{ pre = "- " otok " "; if (index($0, pre id " ") == 1) $0 = "- " dtok " " substr($0, length(pre) + 1); print }' \ "$roadmap" > "$tmp" && mv -f "$tmp" "$roadmap"; then _emit_event "$megadir" "$id" flip "box checked" @@ -1470,13 +1473,21 @@ _wave_worktree() { # repo id branch if [ -e "$wt/.git" ]; then # A linked worktree carries a `.git` FILE (a gitdir pointer). Clean + on => resume. - local dirty cur + local dirty cur main_wt dirty=$(git -C "$wt" status --porcelain 2>/dev/null) cur=$(git -C "$wt" rev-parse --abbrev-ref HEAD 2>/dev/null) if [ -z "$dirty" ] && [ "$cur" = "$branch" ]; then printf '%s\n' "$wt"; return 0 fi - git -C "$repo" worktree remove --force "$wt" 2>/dev/null || true + main_wt="$(_wt_main_checkout "$repo" 2>/dev/null || true)" + if _wt_remove_guard "$wt" "$main_wt"; then + echo "[orchestrate] [wave] $id: refusing to remove worktree $(_san "$wt"): ${WT_IGN_MSG}" >&2 + return 1 + fi + if ! git -C "$repo" worktree remove --force "$wt" 2>/dev/null; then + echo "[orchestrate] [wave] $id: failed to remove worktree $(_san "$wt")" >&2 + return 1 + fi elif [ -e "$wt" ]; then # non-worktree collision at the path (leftover from a crash): move aside, never delete. mv -f "$wt" "${TMPDIR:-/tmp}/wave-wt-stale.$id.$$.$RANDOM" 2>/dev/null || true @@ -2066,8 +2077,9 @@ _wave_spawn() { # megadir roadmap repo mega_abs id # restores the pre-fix spawn so a test can prove the stop; never an operator flag. [ "${NC_SKIP_WAVE_DETACH:-0}" = 1 ] || { command -v perl >/dev/null 2>&1 && [ -x "$ORCH_DIR/detach-run" ] && detach_cmd="$ORCH_DIR/detach-run"; } [ "${_WAVE_ABORTED:-0}" = 1 ] && { rm -f "$pfile"; return 1; } + local orig_claude="$CLAUDE_CMD" set -m - ( cd "$wt" 2>/dev/null && KIT_DETACH_CMD="$CLAUDE_CMD" CLAUDE_CMD="$detach_cmd" \ + ( cd "$wt" 2>/dev/null && KIT_DETACH_CMD="$orig_claude" CLAUDE_CMD="$detach_cmd" \ _run_one_session "$megadir" "$id" "$pfile" "$route_flags" 0 ) & pid=$! set +m @@ -3429,8 +3441,8 @@ cmd_run() { # A box checked on origin with NO `PR #` is a claim, not a completion: it is never retried # either (the fast-forward above may already show it checked locally, and a retry would read # that as a flip), so the loop halts for a human exactly as before. - box_line_is done "$rline" && ! printf '%s' "$rline" | grep -qE 'PR #[0-9]+' && bare_remote=1 - if box_line_is done "$rline" && printf '%s' "$rline" | grep -qE 'PR #[0-9]+'; then + box_line_is "done" "$rline" && ! printf '%s' "$rline" | grep -qE 'PR #[0-9]+' && bare_remote=1 + if box_line_is "done" "$rline" && printf '%s' "$rline" | grep -qE 'PR #[0-9]+'; then checked=1 _say "[orchestrate] [reconcile] $id box is checked on origin with $(printf '%s' "$rline" | grep -oE 'PR #[0-9]+' | head -1); accepting the merged-PR flip." # Mirror the merged flip into the LOCAL ROADMAP when the fast-forward could not run diff --git a/lib/wrap/wrap-apply.sh b/lib/wrap/wrap-apply.sh index 87c84279..ac1913b3 100644 --- a/lib/wrap/wrap-apply.sh +++ b/lib/wrap/wrap-apply.sh @@ -1,4 +1,6 @@ # wrap-apply.sh -- the apply verb and its helpers; sourced by lib/wrap/wrap.sh. +# shellcheck source=lib/wrap/wt-guard.sh +[ -n "${_KIT_WT_GUARD_LOADED:-}" ] || source "${BASH_SOURCE[0]%/*}/wt-guard.sh" || { echo "FATAL: lib/wrap/wt-guard.sh missing or unreadable" >&2; exit 1; } _scanned_tip() { awk -v b="$1" '$1 == b { print $2 }' "$TIPS_FILE"; } @@ -340,41 +342,8 @@ _emit_sweep_row() { }' >> "$_SWEEP_ROWS_FILE" } -# _wt_status_raw -- writes raw NUL-delimited status including all untracked and ignored paths. -_wt_status_raw() { git -C "$1" --no-optional-locks status --porcelain=v1 -z --untracked-files=all --ignored=matching > "$2" 2>/dev/null; } -# _wt_hidden_edits -- 0 on skip-worktree/assume-unchanged ([[:lower:]] for bash 3.2) or ls-files failure. -_wt_hidden_edits() { - local lv; lv="$(git -C "$1" ls-files -v 2>/dev/null)" || { WT_IGN_MSG="git ls-files failed"; return 0; } - case $'\n'"$lv" in *$'\n'[[:lower:]S]' '*) WT_IGN_MSG="skip-worktree or assume-unchanged entries hide their edits"; return 0 ;; esac - return 1 -} -# _wt_init_submodule -- 0 on an initialized submodule/gitlink or ls-files failure; sets WT_IGN_MSG. -_wt_init_submodule() { - local wt="$1" lsf rec mode p - lsf="$(mktemp "${TMPDIR:-/tmp}/kit.XXXXXX")" || { WT_IGN_MSG="mktemp failed"; return 0; } - git -C "$wt" ls-files -s -z > "$lsf" 2>/dev/null || { rm -f "$lsf"; WT_IGN_MSG="git ls-files failed"; return 0; } - while IFS= read -r -d '' rec; do - mode="${rec%% *}"; p="${rec#*$'\t'}" - [ "$mode" = 160000 ] && { [ -e "$wt/$p/.git" ] || [ -L "$wt/$p/.git" ]; } && { rm -f "$lsf"; WT_IGN_MSG="holds an initialized submodule ($(_san "$p"))"; return 0; } - done < "$lsf" - rm -f "$lsf"; return 1 -} -# _wt_ignored_guard
[] -- 0 when removal would lose work or a check fails; sets WT_IGN_MSG. -WT_IGN_MSG=""; WT_IGN_DIRTY=false -_wt_ignored_guard() { - local wt="$1" main="$2" raw="${3:-}" gd mods blockers nb first - WT_IGN_MSG=""; WT_IGN_DIRTY=false - _wt_status "$wt" "$raw" || { WT_IGN_MSG="git status failed"; return 0; } - [ "$WT_ST_ODD" = 1 ] && { WT_IGN_MSG="a path holds a newline or tab"; return 0; } - [ "$WT_ST_DIRTY" = 1 ] && { WT_IGN_MSG="dirty (uncommitted changes)"; WT_IGN_DIRTY=true; return 0; } - _wt_hidden_edits "$wt" && return 0 - _wt_init_submodule "$wt" && return 0 - gd="$(git -C "$wt" rev-parse --path-format=absolute --git-dir 2>/dev/null)" && [ -n "$gd" ] || { WT_IGN_MSG="git dir unreadable"; return 0; } - [ -d "$gd/modules" ] && { ! mods="$(ls -A "$gd/modules/" 2>/dev/null)" || [ -n "$mods" ]; } && { WT_IGN_MSG="holds submodule data in git dir (modules/)"; return 0; } - blockers="$(_wt_ignored_blockers "$wt" "$main")"; [ -n "$blockers" ] || return 1 - nb="$(printf '%s\n' "$blockers" | grep -c .)"; first="${blockers%%$'\n'*}" - WT_IGN_MSG="${nb} ignored paths would be lost, first $(_san "$first")"; return 0 -} +# Worktree safety guard helpers (_wt_status_raw, _wt_hidden_edits, _wt_init_submodule, +# _wt_ignored_guard) live in lib/wrap/wt-guard.sh (sourced via wrap-common.sh / above). # A worktree path may carry a newline, so the record stream is NUL-delimited: `--porcelain -z` # terminates every attribute with NUL, which keeps the path whole. @@ -827,49 +796,7 @@ _apply_archive_unmerged() { done } -# _ARCHIVE_IGNORED_REGENERABLE -- ignored entries `apply --archive-worktrees` may delete with a -# worktree, because a build or an install recreates them (forms: _ignored_match). Never land's -# list or wrap.land_ignored_allow: those also allow local config such as `.env` and `.envrc`, -# which in a stale worktree may be the only copy. -_ARCHIVE_IGNORED_REGENERABLE="node_modules .wrangler dist build .next coverage *.tsbuildinfo __pycache__ target .pytest_cache/ .venv/ .mypy_cache/ .ruff_cache/ .DS_Store tests/.cache .claude/session-state lib/*/bin/*-rs" - -# _wt_status -- one `git status` read for every archive guard, with --no-optional-locks so -# the read never rewrites a worktree's index. Sets WT_ST_DIRTY and WT_ST_UNMERGED (0/1), -# WT_ST_ODD (1 when an uncommitted path holds a newline or tab, which the newline lists below -# cannot carry), WT_ST_N (non-ignored records), and newline lists: WT_ST_PATHS (every -# non-ignored path, renamed-from included, for the idle age), WT_ST_NEW (untracked, added and -# renamed-to paths, for the secret scan), WT_ST_NESTED (`??` directories holding .git) and -# WT_ST_IGNORED (`!!` paths, trailing `/` stripped), plus WT_ST_MOD (modified tracked paths). In `all` mode git lists untracked files one -# by one but stops at a nested repository and prints it as a directory ending in `/`. -# Returns 1 when the read fails. -_wt_status() { - local wt="$1" raw="${2:-}" tmp rec xy p orig - WT_ST_DIRTY=0; WT_ST_UNMERGED=0; WT_ST_ODD=0; WT_ST_N=0 - WT_ST_PATHS=""; WT_ST_NEW=""; WT_ST_MOD=""; WT_ST_NESTED=""; WT_ST_IGNORED="" - [ -n "$raw" ] && tmp="$raw" || { tmp="$(mktemp "${TMPDIR:-/tmp}/kit.XXXXXX")" || return 1; } - if ! _wt_status_raw "$wt" "$tmp"; then [ -n "$raw" ] || rm -f "$tmp"; return 1; fi - while IFS= read -r -d '' rec; do - xy="${rec:0:2}"; p="${rec:3}"; orig="" - # -z reverses a rename: `R ` NUL ``, on either side (` R` is an intent-to-add - # rename in the worktree). - case "$xy" in R?|C?|?R|?C) IFS= read -r -d '' orig || orig="" ;; esac - case "$p$orig" in *$'\n'*|*$'\t'*) WT_ST_ODD=1; continue ;; esac - if [ "$xy" = '!!' ]; then WT_ST_IGNORED+="${p%/}"$'\n'; continue; fi - WT_ST_DIRTY=1; WT_ST_N=$(( WT_ST_N + 1 )) - case "$xy" in DD|AU|UD|UA|DU|AA|UU) WT_ST_UNMERGED=1 ;; esac - WT_ST_PATHS+="${p%/}"$'\n' - [ -n "$orig" ] && WT_ST_PATHS+="${orig}"$'\n' - case "$xy" in - '??') case "$p" in */) { [ -e "$wt/${p}.git" ] || [ -L "$wt/${p}.git" ]; } \ - && WT_ST_NESTED+="${p%/}"$'\n' ;; esac - WT_ST_NEW+="${p%/}"$'\n' ;; - A?|R?|C?|?A|?R|?C) WT_ST_NEW+="${p}"$'\n' ;; - M?|?M|T?|?T) WT_ST_MOD+="${p}"$'\n' ;; - esac - done < "$tmp" - [ -n "$raw" ] || rm -f "$tmp" - return 0 -} +# _ARCHIVE_IGNORED_REGENERABLE and _wt_status live in lib/wrap/wt-guard.sh. # _wt_idle_secs -- prints the idle age in seconds, after _wt_status. The # newest of: the newest reflog entry's own time (`%gd` with --date=unix, never `%ct`, which is @@ -905,44 +832,7 @@ _wt_idle_secs() { echo $(( now - newest )) } -# _wt_synced_copy
-- 0 when every non-directory entry at or under -# / has a twin at the same relative path in the main checkout: a byte-identical -# regular file, or a link with the same target. The main checkout copies such `.claude/` -# paths into each worktree and keeps the canonical copy, so removing the worktree loses -# nothing. A failed listing, a missing twin, or any other file type returns 1. -_wt_synced_copy() { - local wt="$1" main="$2" p="$3" lst f rel d rc=0 - [ -n "$main" ] && [ "$main" != "$wt" ] || return 1 - lst="$(mktemp "${TMPDIR:-/tmp}/kit.XXXXXX")" || return 1 - if ! find "$wt/$p" ! -type d -print0 > "$lst" 2>/dev/null; then rm -f "$lst"; return 1; fi - while IFS= read -r -d '' f; do - rel="${f#"$wt"/}"; d="$rel" - while case "$d" in */*) true ;; *) false ;; esac; do d="${d%/*}"; [ ! -L "$main/$d" ] || { rc=1; break 2; }; done - if [ -L "$f" ]; then - [ -L "$main/$rel" ] && [ "$(readlink "$f")" = "$(readlink "$main/$rel")" ] || { rc=1; break; } - elif [ -f "$f" ]; then - [ -f "$main/$rel" ] && [ ! -L "$main/$rel" ] && cmp -s "$f" "$main/$rel" || { rc=1; break; } - else - rc=1; break - fi - done < "$lst" - rm -f "$lst" - return "$rc" -} - -# _wt_ignored_blockers
-- prints each WT_ST_IGNORED path removal would -# lose: on neither _ARCHIVE_IGNORED_REGENERABLE nor a `.claude/` copy identical to the main -# checkout's (_wt_synced_copy). -_wt_ignored_blockers() { - local wt="$1" main="$2" p - [ -n "$WT_ST_IGNORED" ] || return 0 - while IFS= read -r p; do - [ -n "$p" ] || continue - _ignored_match "$p" "$_ARCHIVE_IGNORED_REGENERABLE" && continue - case "$p" in .claude|.claude/*) _wt_synced_copy "$wt" "$main" "$p" && continue ;; esac - printf '%s\n' "$p" - done <<< "$WT_ST_IGNORED" -} +# _wt_synced_copy and _wt_ignored_blockers live in lib/wrap/wt-guard.sh. # _wt_trees -- prints ` `, or `ERR ` and # returns 1. The staged tree is the worktree's real index; the snapshot tree is the working diff --git a/lib/wrap/wrap-common.sh b/lib/wrap/wrap-common.sh index 92b073eb..7da30a3b 100644 --- a/lib/wrap/wrap-common.sh +++ b/lib/wrap/wrap-common.sh @@ -4,6 +4,10 @@ # that wt.sh and the hooks can source without the wrap library. # shellcheck source=lib/gate/branch-merged.sh source "${BASH_SOURCE[0]%/*}/../gate/branch-merged.sh" || { echo "FATAL: lib/gate/branch-merged.sh missing or unreadable" >&2; exit 1; } +# The worktree-removal safety guard (_wt_ignored_guard, _wt_remove_guard, _ignored_match, _san, ...) lives in one file +# shared with wt.sh, orchestrate.sh, and board-writeback.sh. +# shellcheck source=lib/wrap/wt-guard.sh +source "${BASH_SOURCE[0]%/*}/wt-guard.sh" || { echo "FATAL: lib/wrap/wt-guard.sh missing or unreadable" >&2; exit 1; } # --------------------------------------------------------------------------- helpers @@ -204,51 +208,6 @@ _fmode() { stat -c %a "$1" 2>/dev/null || stat -f %Lp "$1" 2>/dev/null; } _short() { printf '%s' "${1:0:7}"; } -# _ignored_match -- 0 when one of the space-separated covers -# (a `git status` entry, trailing `/` already stripped). Forms: no `/` globs the LAST -# component only, never an ancestor; a trailing `/` covers the whole subtree under any -# directory of that name; any other entry with a `/` globs the whole path or a leading run of -# its components. Split under set -f so an entry such as `*.json` never expands against the -# cwd. `land`'s ignored-file guard and `apply --archive-worktrees` each pass their own list. -_ignored_match() { - local p="$1" entries="$2" entry name last prefix part comp rest restore="" hit=1 - case "$-" in *f*) ;; *) restore=1; set -f ;; esac - last="${p##*/}" - for entry in $entries; do - case "$entry" in - */) - name="${entry%/}" - case "$name" in - */*) entry="$name" ;; - *) rest="$p" - while :; do - comp="${rest%%/*}" - # shellcheck disable=SC2254 - case "$comp" in $name) hit=0; break ;; esac - case "$rest" in */*) rest="${rest#*/}" ;; *) break ;; esac - done - [ "$hit" -eq 0 ] && break - continue ;; - esac ;; - */*) ;; - *) # shellcheck disable=SC2254 - case "$last" in $entry) hit=0; break ;; esac - continue ;; - esac - prefix=""; rest="$p" - while :; do - part="${rest%%/*}" - prefix="${prefix:+${prefix}/}${part}" - # shellcheck disable=SC2254 - case "$prefix" in $entry) hit=0; break ;; esac - case "$rest" in */*) rest="${rest#*/}" ;; *) break ;; esac - done - [ "$hit" -eq 0 ] && break - done - [ -z "$restore" ] || set +f - return "$hit" -} - # _SECRET_SHAPED_NAMES -- basename globs (matched lower-cased) that name a credential or a # key file. _SECRET_SHAPED_DIRS -- path components that hold them. `apply --archive-worktrees` # never pushes an uncommitted path either list covers: the push is the one step a ref delete @@ -289,10 +248,6 @@ _secret_shaped() { return "$hit" } -# _san -- control characters replaced by `?`, so a path or an error line cannot -# rewrite the report. -_san() { printf '%s' "$1" | env LC_ALL=C tr '[:cntrl:]' '?'; } - # _open_own_prs -- the open PRs the operator authored, as a JSON array. # # The author filter runs HERE, not on the server: `gh pr list --author` sends gh to the diff --git a/lib/wrap/wt-guard.sh b/lib/wrap/wt-guard.sh new file mode 100644 index 00000000..02f05f78 --- /dev/null +++ b/lib/wrap/wt-guard.sh @@ -0,0 +1,269 @@ +# shellcheck shell=bash +# wt-guard.sh -- shared worktree-removal safety guard; sourced by wrap, wt.sh, and orchestrate.sh. +# Keeps unique ignored paths, uncommitted edits, hidden index flags, and initialized submodules from being destroyed +# by `git worktree remove --force`. Safe under both `set -uo pipefail` and `set -euo pipefail`, and bash 3.2+. + +[ -n "${_KIT_WT_GUARD_LOADED:-}" ] && return 0 +_KIT_WT_GUARD_LOADED=1 + +# _san -- control characters replaced by `?`, so a path or an error line cannot +# rewrite the report. +_san() { printf '%s' "$1" | env LC_ALL=C tr '[:cntrl:]' '?'; } + +# _ignored_match -- 0 when one of the space-separated covers +# (a `git status` entry, trailing `/` already stripped). Forms: no `/` globs the LAST +# component only, never an ancestor; a trailing `/` covers the whole subtree under any +# directory of that name; any other entry with a `/` globs the whole path or a leading run of +# its components. Split under set -f so an entry such as `*.json` never expands against the +# cwd. `land`'s ignored-file guard and worktree cleanup each pass their own list. +_ignored_match() { + local p="$1" entries="$2" entry name last prefix part comp rest restore="" hit=1 + case "$-" in *f*) ;; *) restore=1; set -f ;; esac + last="${p##*/}" + for entry in $entries; do + case "$entry" in + */) + name="${entry%/}" + case "$name" in + */*) entry="$name" ;; + *) rest="$p" + while :; do + comp="${rest%%/*}" + # shellcheck disable=SC2254 + case "$comp" in $name) hit=0; break ;; esac + case "$rest" in */*) rest="${rest#*/}" ;; *) break ;; esac + done + if [ "$hit" -eq 0 ]; then break; fi + continue ;; + esac ;; + */*) ;; + *) # shellcheck disable=SC2254 + case "$last" in $entry) hit=0; break ;; esac + continue ;; + esac + prefix=""; rest="$p" + while :; do + part="${rest%%/*}" + prefix="${prefix:+${prefix}/}${part}" + # shellcheck disable=SC2254 + case "$prefix" in $entry) hit=0; break ;; esac + case "$rest" in */*) rest="${rest#*/}" ;; *) break ;; esac + done + if [ "$hit" -eq 0 ]; then break; fi + done + if [ -n "$restore" ]; then set +f; fi + return "$hit" +} + +# _ARCHIVE_IGNORED_REGENERABLE -- ignored entries worktree removal may delete with a +# worktree, because a build or an install recreates them (forms: _ignored_match). Never land's +# list or wrap.land_ignored_allow: those also allow local config such as `.env` and `.envrc`, +# which in a stale worktree may be the only copy. +_ARCHIVE_IGNORED_REGENERABLE="node_modules .wrangler dist build .next coverage *.tsbuildinfo __pycache__ target .pytest_cache/ .venv/ .mypy_cache/ .ruff_cache/ .DS_Store tests/.cache .claude/session-state lib/*/bin/*-rs" + +# _wt_main_checkout -- prints the physical path of the repo's main checkout. +_wt_main_checkout() { + local common + common="$(git -C "$1" rev-parse --path-format=absolute --git-common-dir 2>/dev/null)" || return 1 + [ -n "$common" ] || return 1 + common="${common%/.git}"; common="${common%/}" + ( cd "$common" 2>/dev/null && pwd -P ) +} + +# _wt_status_raw -- writes raw NUL-delimited status including all untracked and ignored paths. +_wt_status_raw() { git -C "$1" --no-optional-locks status --porcelain=v1 -z --untracked-files=all --ignored=matching > "$2" 2>/dev/null; } + +# _wt_status [] -- one `git status` read for worktree guards, with --no-optional-locks so +# the read never rewrites a worktree's index. Sets WT_ST_DIRTY and WT_ST_UNMERGED (0/1), +# WT_ST_ODD (1 when an uncommitted path holds a newline or tab, which the newline lists below +# cannot carry), WT_ST_N (non-ignored records), and newline lists: WT_ST_PATHS (every +# non-ignored path, renamed-from included, for the idle age), WT_ST_NEW (untracked, added and +# renamed-to paths, for the secret scan), WT_ST_NESTED (`??` directories holding .git) and +# WT_ST_IGNORED (`!!` paths, trailing `/` stripped), plus WT_ST_MOD (modified tracked paths). In `all` mode git lists untracked files one +# by one but stops at a nested repository and prints it as a directory ending in `/`. +# Returns 1 when the read fails. +_wt_status() { + local wt="$1" raw="${2:-}" tmp rec xy p orig + WT_ST_DIRTY=0; WT_ST_UNMERGED=0; WT_ST_ODD=0; WT_ST_N=0 + WT_ST_PATHS=""; WT_ST_NEW=""; WT_ST_MOD=""; WT_ST_NESTED=""; WT_ST_IGNORED="" + if [ -n "$raw" ]; then + tmp="$raw" + else + tmp="$(mktemp "${TMPDIR:-/tmp}/kit.XXXXXX")" || return 1 + fi + if ! _wt_status_raw "$wt" "$tmp"; then + [ -n "$raw" ] || rm -f "$tmp" + return 1 + fi + while IFS= read -r -d '' rec; do + xy="${rec:0:2}"; p="${rec:3}"; orig="" + # -z reverses a rename: `R ` NUL ``, on either side (` R` is an intent-to-add + # rename in the worktree). + case "$xy" in R?|C?|?R|?C) IFS= read -r -d '' orig || orig="" ;; esac + case "$p$orig" in *$'\n'*|*$'\t'*) WT_ST_ODD=1; continue ;; esac + if [ "$xy" = '!!' ]; then WT_ST_IGNORED+="${p%/}"$'\n'; continue; fi + WT_ST_DIRTY=1; WT_ST_N=$(( WT_ST_N + 1 )) + # shellcheck disable=SC2034 # read by wrap-apply.sh archive guards + case "$xy" in DD|AU|UD|UA|DU|AA|UU) WT_ST_UNMERGED=1 ;; esac + WT_ST_PATHS+="${p%/}"$'\n' + if [ -n "$orig" ]; then WT_ST_PATHS+="${orig}"$'\n'; fi + case "$xy" in + '??') + case "$p" in + */) + if [ -e "$wt/${p}.git" ] || [ -L "$wt/${p}.git" ]; then + WT_ST_NESTED+="${p%/}"$'\n' + fi ;; + esac + WT_ST_NEW+="${p%/}"$'\n' ;; + A?|R?|C?|?A|?R|?C) WT_ST_NEW+="${p}"$'\n' ;; + M?|?M|T?|?T) WT_ST_MOD+="${p}"$'\n' ;; + esac + done < "$tmp" + if [ -z "$raw" ]; then rm -f "$tmp"; fi + return 0 +} + +# _wt_hidden_edits -- 0 on skip-worktree/assume-unchanged ([[:lower:]] for bash 3.2) or ls-files failure. +_wt_hidden_edits() { + local lv + if ! lv="$(git -C "$1" ls-files -v 2>/dev/null)"; then + WT_IGN_MSG="git ls-files failed"; return 0 + fi + case $'\n'"$lv" in + *$'\n'[[:lower:]S]' '*) WT_IGN_MSG="skip-worktree or assume-unchanged entries hide their edits"; return 0 ;; + esac + return 1 +} + +# _wt_init_submodule -- 0 on an initialized submodule/gitlink or ls-files failure; sets WT_IGN_MSG. +_wt_init_submodule() { + local wt="$1" lsf rec mode p + lsf="$(mktemp "${TMPDIR:-/tmp}/kit.XXXXXX")" || { WT_IGN_MSG="mktemp failed"; return 0; } + if ! git -C "$wt" ls-files -s -z > "$lsf" 2>/dev/null; then + rm -f "$lsf"; WT_IGN_MSG="git ls-files failed"; return 0 + fi + while IFS= read -r -d '' rec; do + mode="${rec%% *}"; p="${rec#*$'\t'}" + if [ "$mode" = 160000 ] && { [ -e "$wt/$p/.git" ] || [ -L "$wt/$p/.git" ]; }; then + rm -f "$lsf"; WT_IGN_MSG="holds an initialized submodule ($(_san "$p"))"; return 0 + fi + done < "$lsf" + rm -f "$lsf" + return 1 +} + +# _wt_synced_copy
-- 0 when every non-directory entry at or under +# / has a twin at the same relative path in the main checkout: a byte-identical +# regular file, or a link with the same target. The main checkout copies such `.claude/` +# paths into each worktree and keeps the canonical copy, so removing the worktree loses +# nothing. A failed listing, a missing twin, or any other file type returns 1. +_wt_synced_copy() { + local wt="$1" main="$2" p="$3" lst f rel d rc=0 + [ -n "$main" ] && [ "$main" != "$wt" ] || return 1 + lst="$(mktemp "${TMPDIR:-/tmp}/kit.XXXXXX")" || return 1 + if ! find "$wt/$p" ! -type d -print0 > "$lst" 2>/dev/null; then rm -f "$lst"; return 1; fi + while IFS= read -r -d '' f; do + rel="${f#"$wt"/}"; d="$rel" + while case "$d" in */*) true ;; *) false ;; esac; do + d="${d%/*}" + if [ -L "$main/$d" ]; then rc=1; break 2; fi + done + if [ -L "$f" ]; then + if ! { [ -L "$main/$rel" ] && [ "$(readlink "$f")" = "$(readlink "$main/$rel")" ]; }; then + rc=1; break + fi + elif [ -f "$f" ]; then + if ! { [ -f "$main/$rel" ] && [ ! -L "$main/$rel" ] && cmp -s "$f" "$main/$rel"; }; then + rc=1; break + fi + else + rc=1; break + fi + done < "$lst" + rm -f "$lst" + return "$rc" +} + +# _wt_ignored_blockers
-- prints each WT_ST_IGNORED path removal would +# lose: on neither _ARCHIVE_IGNORED_REGENERABLE nor a `.claude/` copy identical to the main +# checkout's (_wt_synced_copy). +_wt_ignored_blockers() { + local wt="$1" main="$2" p + [ -n "$WT_ST_IGNORED" ] || return 0 + while IFS= read -r p; do + [ -n "$p" ] || continue + if _ignored_match "$p" "$_ARCHIVE_IGNORED_REGENERABLE"; then continue; fi + case "$p" in + .claude|.claude/*) if _wt_synced_copy "$wt" "$main" "$p"; then continue; fi ;; + esac + printf '%s\n' "$p" + done <<< "$WT_ST_IGNORED" +} + +# _wt_ignored_guard
[] -- 0 when removal would lose work or a check fails; sets WT_IGN_MSG. +WT_IGN_MSG="" +# shellcheck disable=SC2034 # WT_IGN_DIRTY is read by wrap-apply.sh sweep rows +WT_IGN_DIRTY=false +_wt_ignored_guard() { + local wt="$1" main="$2" raw="${3:-}" wt_c main_c="" gd mods blockers nb first + WT_IGN_MSG="" + # shellcheck disable=SC2034 + WT_IGN_DIRTY=false + if ! wt_c="$(cd "$wt" 2>/dev/null && pwd -P)"; then + WT_IGN_MSG="worktree path unreadable"; return 0 + fi + if [ -n "$main" ]; then + main_c="$(cd "$main" 2>/dev/null && pwd -P)" || main_c="" + fi + if ! _wt_status "$wt_c" "$raw"; then + WT_IGN_MSG="git status failed"; return 0 + fi + if [ "$WT_ST_ODD" = 1 ]; then + WT_IGN_MSG="a path holds a newline or tab"; return 0 + fi + if [ "$WT_ST_DIRTY" = 1 ]; then + WT_IGN_MSG="dirty (uncommitted changes)"; WT_IGN_DIRTY=true; return 0 + fi + if _wt_hidden_edits "$wt_c"; then return 0; fi + if _wt_init_submodule "$wt_c"; then return 0; fi + if ! gd="$(git -C "$wt_c" rev-parse --path-format=absolute --git-dir 2>/dev/null)" || [ -z "$gd" ]; then + WT_IGN_MSG="git dir unreadable"; return 0 + fi + if [ -d "$gd/modules" ]; then + if ! mods="$(ls -A "$gd/modules/" 2>/dev/null)" || [ -n "$mods" ]; then + WT_IGN_MSG="holds submodule data in git dir (modules/)"; return 0 + fi + fi + blockers="$(_wt_ignored_blockers "$wt_c" "$main_c")" + [ -n "$blockers" ] || return 1 + nb="$(printf '%s\n' "$blockers" | grep -c .)" + first="${blockers%%$'\n'*}" + WT_IGN_MSG="${nb} ignored paths would be lost, first $(_san "$first")" + return 0 +} + +# _wt_remove_guard
-- two-pass worktree safety check right before `git worktree remove`. +# Returns 0 when removal would lose unique/uncommitted work, status changed between reads, or a check +# failed (WT_IGN_MSG carries the reason); returns 1 when safe to remove. +_wt_remove_guard() { + local wt="$1" main="$2" raw1="" raw2="" + WT_IGN_MSG="" + # shellcheck disable=SC2034 # WT_IGN_DIRTY is part of the shared guard result surface + WT_IGN_DIRTY=false + raw1="$(mktemp "${TMPDIR:-/tmp}/kit.XXXXXX" 2>/dev/null)" || raw1="" + raw2="$(mktemp "${TMPDIR:-/tmp}/kit.XXXXXX" 2>/dev/null)" || raw2="" + if [ -z "$raw1" ] || [ -z "$raw2" ]; then + WT_IGN_MSG="mktemp failed" + elif _wt_ignored_guard "$wt" "$main" "$raw1"; then + : + elif ! _wt_status_raw "$wt" "$raw2"; then + WT_IGN_MSG="git status failed" + elif ! cmp -s "$raw1" "$raw2"; then + WT_IGN_MSG="status changed before removal" + fi + if [ -n "$raw1$raw2" ]; then + rm -f ${raw1:+"$raw1"} ${raw2:+"$raw2"} + fi + [ -n "$WT_IGN_MSG" ] +} diff --git a/tests/test-worktree-removers-ignored.sh b/tests/test-worktree-removers-ignored.sh new file mode 100755 index 00000000..029193ac --- /dev/null +++ b/tests/test-worktree-removers-ignored.sh @@ -0,0 +1,448 @@ +#!/usr/bin/env bash +# test-worktree-removers-ignored.sh -- wt.sh and orchestrate.sh keep unique ignored/uncommitted work before removing a worktree. +# modules under test: lib/wrap/wt-guard.sh lib/wrap/wrap-common.sh lib/wrap/wrap-apply.sh lib/goal/wt.sh lib/queue/orchestrate.sh +set -uo pipefail + +KIT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +WT_SH="$KIT_DIR/lib/goal/wt.sh" +ORCH_SH="$KIT_DIR/lib/queue/orchestrate.sh" + +PASS=0; FAIL=0; TOTAL=0 +chk() { + TOTAL=$(( TOTAL + 1 )) + if [ "$2" -eq 0 ] 2>/dev/null; then echo " PASS $1"; PASS=$(( PASS + 1 )) + else echo " FAIL $1"; FAIL=$(( FAIL + 1 )); fi +} +chk_cmd() { local lbl="$1"; shift; if "$@"; then chk "$lbl" 0; else chk "$lbl" 1; fi; } +chk_not() { local lbl="$1"; shift; if "$@"; then chk "$lbl" 1; else chk "$lbl" 0; fi; } +chk_has() { + if { trap '' PIPE; printf '%s' "$2" 2>/dev/null || :; } | grep -qF -- "$3"; then chk "$1" 0 + else chk "$1" 1; fi +} + +SANDBOX="$(mktemp -d "${TMPDIR:-/tmp}/dk-wt-removers.XXXXXX")" || exit 1 +SANDBOX="$(cd "$SANDBOX" && pwd)" +trap 'chmod -R u+w "$SANDBOX" 2>/dev/null; rm -rf "$SANDBOX"' EXIT + +export HOME="$SANDBOX/home" +export XDG_CONFIG_HOME="$SANDBOX/xdg-config" +export XDG_STATE_HOME="$SANDBOX/xdg-state" +export XDG_CACHE_HOME="$SANDBOX/xdg-cache" +export XDG_DATA_HOME="$SANDBOX/xdg-data" +export GIT_CONFIG_GLOBAL="$SANDBOX/gitconfig" +export GIT_CONFIG_NOSYSTEM=1 +export GIT_TEMPLATE_DIR="$SANDBOX/git-template" +export CHROME=/nonexistent +export KIT_CONFIG_OPERATOR="$SANDBOX/no-operator-config" +export KIT_LEDGER_DIR="$SANDBOX/ledger" +export DWARVES_KIT_LOG_DIR="$SANDBOX/ledger" +export GOAL_REGISTRY_DIR="$SANDBOX/goal-reg" +mkdir -p "$HOME" "$XDG_CONFIG_HOME" "$XDG_STATE_HOME" "$XDG_CACHE_HOME" "$XDG_DATA_HOME" "$GIT_TEMPLATE_DIR" "$SANDBOX/stub" "$GOAL_REGISTRY_DIR" + +cat > "$GIT_CONFIG_GLOBAL" < "$SANDBOX/stub/gh" <<'STUB' +#!/usr/bin/env bash +case "$1 ${2:-}" in + "auth status") exit 0 ;; + "pr list") + state=""; head="" + while [ $# -gt 0 ]; do + case "$1" in + --state) state="$2"; shift 2 ;; + --head) head="$2"; shift 2 ;; + *) shift ;; + esac + done + if [ "$state" = "open" ]; then + printf '[]\n'; exit 0 + fi + if [ "$state" = "merged" ]; then + key="${head//\//_}" + if [ -f "$SHIM_DIR/merged-$key" ]; then + cat "$SHIM_DIR/merged-$key"; exit 0 + fi + printf '[]\n'; exit 0 + fi + exit 1 ;; + "pr create") + printf 'https://github.com/example/repo/pull/99\n'; exit 0 ;; +esac +exit 1 +STUB +chmod +x "$SANDBOX/stub/gh" +export SHIM_DIR +export PATH="$SANDBOX/stub:$PATH:/usr/sbin:/sbin" + +# Build a small submodule bare repo for submodule tests. +SUB_SEED="$SANDBOX/sub-seed" +SUB_BARE="$SANDBOX/sub-origin.git" +mkdir -p "$SUB_SEED" +git -C "$SUB_SEED" init -q +git -C "$SUB_SEED" symbolic-ref HEAD refs/heads/master +printf 'sub\n' > "$SUB_SEED/s.txt" +git -C "$SUB_SEED" add -A +git -C "$SUB_SEED" commit -q -m "chore: sub" +git clone -q --bare "$SUB_SEED" "$SUB_BARE" + +# =========================================================================== +echo "=== A. lib/goal/wt.sh close ===" +# =========================================================================== +mk_wt_case() { # mk_wt_case [with-submod] + local name="$1" with_sub="${2:-0}" + local seed="$SANDBOX/wt-seed-$name" bare="$SANDBOX/wt-bare-$name.git" clone="$SANDBOX/wt-clone-$name" tip + mkdir -p "$seed" "$clone" + git -C "$seed" init -q + git -C "$seed" symbolic-ref HEAD refs/heads/master + printf '.env\nnotes/\nsubrepo/\nnode_modules/\n.claude/rules/\n' > "$seed/.gitignore" + printf 'base\n' > "$seed/a.txt" + git -C "$seed" add -A + git -C "$seed" commit -q -m "chore: base" + git -C "$seed" checkout -q -b feat/x + printf 'feature\n' > "$seed/f.txt" + git -C "$seed" add f.txt + if [ "$with_sub" = 1 ]; then + git -C "$seed" -c protocol.file.allow=always submodule add -q "$SUB_BARE" sub >/dev/null 2>&1 + fi + git -C "$seed" commit -q -m "feat: x" + tip="$(git -C "$seed" rev-parse HEAD)" + git -C "$seed" checkout -q master + git -C "$seed" merge -q --no-ff --no-edit feat/x + git clone -q --bare "$seed" "$bare" + git -C "$clone" init -q + git -C "$clone" remote add origin "https://github.com/example/wt-$name.git" + git -C "$clone" config "url.$bare.insteadOf" "https://github.com/example/wt-$name.git" + git -C "$clone" fetch -q origin + git -C "$clone" checkout -q -b master origin/master + git -C "$clone" branch -q feat/x origin/feat/x + ln -s "$KIT_DIR/lib" "$clone/lib" + git -C "$clone" worktree add -q "$clone/.claude/worktrees/x" feat/x >/dev/null 2>&1 + if [ "$with_sub" = 1 ]; then + git -C "$clone/.claude/worktrees/x" -c protocol.file.allow=always submodule update --init -q >/dev/null 2>&1 + fi + printf '[{"headRefName":"feat/x","headRefOid":"%s","baseRefName":"master","mergedAt":"2026-01-01T00:00:00Z","isCrossRepository":false}]\n' "$tip" > "$SHIM_DIR/merged-feat_x" + WT_CLONE="$clone" + WT_BARE="$bare" + WT_DIR="$clone/.claude/worktrees/x" +} +run_wt_close() { ( cd "$WT_CLONE" && bash "$WT_SH" close x feat 2>&1 ); } +wt_kept() { + local lbl="$1" keep_file="$2" + chk_cmd "$lbl: kept file exists" test -e "$keep_file" + chk_cmd "$lbl: worktree exists" test -d "$WT_DIR" + chk_cmd "$lbl: local branch exists" git -C "$WT_CLONE" show-ref --verify --quiet refs/heads/feat/x + chk_cmd "$lbl: origin branch exists" git -C "$WT_BARE" show-ref --verify --quiet refs/heads/feat/x +} + +# A1: unique ignored .env -> refuses +mk_wt_case env +printf 'SECRET=1\n' > "$WT_DIR/.env" +out="$(run_wt_close)"; rc=$? +chk_cmd "wt env: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wt env: says why (.env)" "$out" "1 ignored paths would be lost, first .env" +wt_kept "wt env" "$WT_DIR/.env" + +# A2: ignored directory with file -> refuses +mk_wt_case dir +mkdir -p "$WT_DIR/notes" +printf 'keep me\n' > "$WT_DIR/notes/memo.txt" +out="$(run_wt_close)"; rc=$? +chk_cmd "wt dir: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wt dir: says why (notes)" "$out" "1 ignored paths would be lost, first notes" +wt_kept "wt dir" "$WT_DIR/notes/memo.txt" + +# A3: ignored embedded git repo -> refuses +mk_wt_case subrepo +mkdir -p "$WT_DIR/subrepo" +git -C "$WT_DIR/subrepo" init -q +printf 'inner\n' > "$WT_DIR/subrepo/inner.txt" +git -C "$WT_DIR/subrepo" add -A +git -C "$WT_DIR/subrepo" commit -q -m "chore: inner" +out="$(run_wt_close)"; rc=$? +chk_cmd "wt subrepo: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wt subrepo: says why (subrepo)" "$out" "1 ignored paths would be lost, first subrepo" +wt_kept "wt subrepo" "$WT_DIR/subrepo/inner.txt" + +# A4: dirty untracked file with showUntrackedFiles=no -> refuses +mk_wt_case dirty +git -C "$WT_CLONE" config status.showUntrackedFiles no +printf 'untracked\n' > "$WT_DIR/u.txt" +out="$(run_wt_close)"; rc=$? +chk_cmd "wt dirty: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wt dirty: says why (dirty)" "$out" "dirty (uncommitted changes)" +wt_kept "wt dirty" "$WT_DIR/u.txt" + +# A5: hidden edit (skip-worktree) -> refuses +mk_wt_case skipwt +git -C "$WT_DIR" update-index --skip-worktree a.txt +printf 'hidden\n' >> "$WT_DIR/a.txt" +out="$(run_wt_close)"; rc=$? +chk_cmd "wt skip-worktree: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wt skip-worktree: says why" "$out" "skip-worktree or assume-unchanged" +wt_kept "wt skip-worktree" "$WT_DIR/a.txt" + +# A6: initialized submodule -> refuses +mk_wt_case submod 1 +out="$(run_wt_close)"; rc=$? +chk_cmd "wt submodule: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wt submodule: says why" "$out" "holds an initialized submodule (sub)" +wt_kept "wt submodule" "$WT_DIR/sub/.git" + +# A7: differing .claude/ copy refuses; identical .claude/ copy removes +mk_wt_case cldiff +mkdir -p "$WT_CLONE/.claude/rules" "$WT_DIR/.claude/rules" +printf 'main copy\n' > "$WT_CLONE/.claude/rules/r.md" +printf 'local edit\n' > "$WT_DIR/.claude/rules/r.md" +out="$(run_wt_close)"; rc=$? +chk_cmd "wt claude-diff: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wt claude-diff: says why" "$out" "1 ignored paths would be lost, first .claude/rules" +wt_kept "wt claude-diff" "$WT_DIR/.claude/rules/r.md" + +mk_wt_case clsame +mkdir -p "$WT_CLONE/.claude/rules" "$WT_DIR/.claude/rules" +printf 'shared\n' > "$WT_CLONE/.claude/rules/r.md" +printf 'shared\n' > "$WT_DIR/.claude/rules/r.md" +out="$(run_wt_close)"; rc=$? +chk "wt claude-same: closes cleanly (rc 0)" "$rc" +chk_not "wt claude-same: worktree removed" test -e "$WT_DIR" +chk_not "wt claude-same: local branch deleted" git -C "$WT_CLONE" show-ref --verify --quiet refs/heads/feat/x + +# A8: regenerable node_modules only -> removes cleanly +mk_wt_case nm +mkdir -p "$WT_DIR/node_modules/pkg" +printf 'x\n' > "$WT_DIR/node_modules/pkg/index.js" +out="$(run_wt_close)"; rc=$? +chk "wt node_modules: closes cleanly (rc 0)" "$rc" +chk_not "wt node_modules: worktree removed" test -e "$WT_DIR" +chk_not "wt node_modules: local branch deleted" git -C "$WT_CLONE" show-ref --verify --quiet refs/heads/feat/x + +# A9: clean worktree -> closes cleanly and releases its registry claim +mk_wt_case clean +REG_CLEAN="$SANDBOX/reg-clean"; mkdir -p "$REG_CLEAN" +( cd "$WT_CLONE" && GOAL_REGISTRY_DIR="$REG_CLEAN" bash "$KIT_DIR/lib/goal/goal-registry.sh" claim x normal 'lib/**' >/dev/null 2>&1 ) +chk_cmd "wt clean: setup claim exists" test -f "$REG_CLEAN/x.goal" +out="$(GOAL_REGISTRY_DIR="$REG_CLEAN" run_wt_close)"; rc=$? +chk "wt clean: closes cleanly (rc 0)" "$rc" +chk_not "wt clean: registry claim released" test -e "$REG_CLEAN/x.goal" +chk_not "wt clean: worktree removed" test -e "$WT_DIR" +chk_not "wt clean: local branch deleted" git -C "$WT_CLONE" show-ref --verify --quiet refs/heads/feat/x +chk_not "wt clean: origin branch deleted" git -C "$WT_BARE" show-ref --verify --quiet refs/heads/feat/x + +# A10: failed git status --ignored=matching -> refuses +REAL_GIT="$(command -v git)" +GIT_FAIL_BIN="$SANDBOX/git-fail-bin" +mkdir -p "$GIT_FAIL_BIN" +cat > "$GIT_FAIL_BIN/git" < refuses (status changed before removal) +GIT_RACE_BIN="$SANDBOX/git-race-bin" +mkdir -p "$GIT_RACE_BIN" +cat > "$GIT_RACE_BIN/git" < "\$RACE_CNT" + "$REAL_GIT" "\$@"; rc=\$? + if [ "\$n" -eq 1 ] && [ -n "\${RACE_WT:-}" ]; then + printf 'LATE=1\n' > "\$RACE_WT/.env" + fi + exit "\$rc" +fi +exec "$REAL_GIT" "\$@" +EOF +chmod +x "$GIT_RACE_BIN/git" + +mk_wt_case race +RACE_CNT="$SANDBOX/wt-race.cnt"; rm -f "$RACE_CNT" +out="$(PATH="$GIT_RACE_BIN:$PATH" RACE_CNT="$RACE_CNT" RACE_WT="$WT_DIR" run_wt_close)"; rc=$? +chk_cmd "wt race: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wt race: says status changed before removal" "$out" "status changed before removal" +wt_kept "wt race" "$WT_DIR/.env" + +# A12: failed git worktree remove keeps the registry claim, worktree, and branches +GIT_RMFAIL_BIN="$SANDBOX/git-rmfail-bin" +mkdir -p "$GIT_RMFAIL_BIN" +cat > "$GIT_RMFAIL_BIN/git" <&2 + exit 1 +fi +exec "$REAL_GIT" "\$@" +EOF +chmod +x "$GIT_RMFAIL_BIN/git" + +mk_wt_case rmfail +REG_RMFAIL="$SANDBOX/reg-rmfail"; mkdir -p "$REG_RMFAIL" +( cd "$WT_CLONE" && GOAL_REGISTRY_DIR="$REG_RMFAIL" bash "$KIT_DIR/lib/goal/goal-registry.sh" claim x normal 'lib/**' >/dev/null 2>&1 ) +chk_cmd "wt rmfail: setup claim exists" test -f "$REG_RMFAIL/x.goal" +out="$(PATH="$GIT_RMFAIL_BIN:$PATH" GOAL_REGISTRY_DIR="$REG_RMFAIL" run_wt_close)"; rc=$? +chk_cmd "wt rmfail: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wt rmfail: says worktree remove failed" "$out" "worktree remove failed" +chk_cmd "wt rmfail: registry claim survives" test -f "$REG_RMFAIL/x.goal" +wt_kept "wt rmfail" "$WT_DIR/a.txt" + +# =========================================================================== +echo "=== B. lib/queue/orchestrate.sh (_wave_worktree) ===" +# =========================================================================== +mk_wave_case() { # mk_wave_case [cur_branch] [with_submod] + local name="$1" cur_br="${2:-other/branch}" with_sub="${3:-0}" + local repo="$SANDBOX/wave-repo-$name" + mkdir -p "$repo" + git -C "$repo" init -q + git -C "$repo" symbolic-ref HEAD refs/heads/master + printf '.env\nnotes/\nsubrepo/\nnode_modules/\n.claude/rules/\n' > "$repo/.gitignore" + printf 'base\n' > "$repo/a.txt" + git -C "$repo" add -A + git -C "$repo" commit -q -m "chore: base" + git -C "$repo" checkout -q -b "$cur_br" + if [ "$with_sub" = 1 ]; then + git -C "$repo" -c protocol.file.allow=always submodule add -q "$SUB_BARE" sub >/dev/null 2>&1 + git -C "$repo" commit -q -m "feat: sub" + fi + git -C "$repo" checkout -q master + mkdir -p "$repo/.claude/worktrees" + git -C "$repo" worktree add -q "$repo/.claude/worktrees/SG-01" "$cur_br" >/dev/null 2>&1 + if [ "$with_sub" = 1 ]; then + git -C "$repo/.claude/worktrees/SG-01" -c protocol.file.allow=always submodule update --init -q >/dev/null 2>&1 + fi + WAVE_REPO="$repo" + WAVE_WT="$repo/.claude/worktrees/SG-01" +} +run_wave_wt() { + bash -c 'source "$1"; _wave_worktree "$2" "$3" "$4"' _ "$ORCH_SH" "$WAVE_REPO" "SG-01" "feat/sg-01" 2>&1 +} + +# B1: wrong branch + ignored .env -> refuses, keeps worktree and .env +mk_wave_case env +printf 'KEY=1\n' > "$WAVE_WT/.env" +out="$(run_wave_wt)"; rc=$? +chk_cmd "wave env: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wave env: says why (.env)" "$out" "1 ignored paths would be lost, first .env" +chk_cmd "wave env: .env kept" test -f "$WAVE_WT/.env" +chk_cmd "wave env: still on original branch" test "$(git -C "$WAVE_WT" rev-parse --abbrev-ref HEAD)" = "other/branch" + +# B2: wrong branch + ignored directory -> refuses +mk_wave_case dir +mkdir -p "$WAVE_WT/notes" +printf 'keep\n' > "$WAVE_WT/notes/memo.txt" +out="$(run_wave_wt)"; rc=$? +chk_cmd "wave dir: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wave dir: says why (notes)" "$out" "1 ignored paths would be lost, first notes" +chk_cmd "wave dir: memo.txt kept" test -f "$WAVE_WT/notes/memo.txt" + +# B3: wrong branch + differing .claude copy -> refuses +mk_wave_case cldiff +mkdir -p "$WAVE_REPO/.claude/rules" "$WAVE_WT/.claude/rules" +printf 'main\n' > "$WAVE_REPO/.claude/rules/r.md" +printf 'diff\n' > "$WAVE_WT/.claude/rules/r.md" +out="$(run_wave_wt)"; rc=$? +chk_cmd "wave claude-diff: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wave claude-diff: says why" "$out" "1 ignored paths would be lost, first .claude/rules" +chk_cmd "wave claude-diff: differing file kept" grep -qx 'diff' "$WAVE_WT/.claude/rules/r.md" + +# B4: same branch + dirty file -> refuses (does not wipe uncommitted work) +mk_wave_case dirty feat/sg-01 +printf 'wip\n' > "$WAVE_WT/wip.txt" +out="$(run_wave_wt)"; rc=$? +chk_cmd "wave dirty: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wave dirty: says why (dirty)" "$out" "dirty (uncommitted changes)" +chk_cmd "wave dirty: wip.txt kept" test -f "$WAVE_WT/wip.txt" + +# B5: wrong branch + hidden edit (skip-worktree) -> refuses +mk_wave_case skipwt +git -C "$WAVE_WT" update-index --skip-worktree a.txt +printf 'hidden\n' >> "$WAVE_WT/a.txt" +out="$(run_wave_wt)"; rc=$? +chk_cmd "wave skip-worktree: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wave skip-worktree: says why" "$out" "skip-worktree or assume-unchanged" +chk_cmd "wave skip-worktree: edited file kept" grep -qx 'hidden' "$WAVE_WT/a.txt" + +# B6: wrong branch + initialized submodule -> refuses +mk_wave_case submod other/branch 1 +out="$(run_wave_wt)"; rc=$? +chk_cmd "wave submodule: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wave submodule: says why" "$out" "holds an initialized submodule (sub)" +chk_cmd "wave submodule: sub/.git kept" test -e "$WAVE_WT/sub/.git" + +# B7: wrong branch + regenerable node_modules only -> recreates on target branch +mk_wave_case nm +mkdir -p "$WAVE_WT/node_modules/pkg" +printf 'x\n' > "$WAVE_WT/node_modules/pkg/index.js" +out="$(run_wave_wt)"; rc=$? +chk "wave node_modules: recreates cleanly (rc 0)" "$rc" +chk_cmd "wave node_modules: now on target branch" test "$(git -C "$WAVE_WT" rev-parse --abbrev-ref HEAD)" = "feat/sg-01" + +# B8: wrong branch + identical .claude copy -> recreates on target branch +mk_wave_case clsame +mkdir -p "$WAVE_REPO/.claude/rules" "$WAVE_WT/.claude/rules" +printf 'shared\n' > "$WAVE_REPO/.claude/rules/r.md" +printf 'shared\n' > "$WAVE_WT/.claude/rules/r.md" +out="$(run_wave_wt)"; rc=$? +chk "wave claude-same: recreates cleanly (rc 0)" "$rc" +chk_cmd "wave claude-same: now on target branch" test "$(git -C "$WAVE_WT" rev-parse --abbrev-ref HEAD)" = "feat/sg-01" + +# B9: same branch + clean + ignored .env -> reuses without removing, keeps .env +mk_wave_case reuse feat/sg-01 +printf 'KEEP=1\n' > "$WAVE_WT/.env" +out="$(run_wave_wt)"; rc=$? +chk "wave reuse: exits 0" "$rc" +chk_cmd "wave reuse: .env kept" test -f "$WAVE_WT/.env" + +# B10: failed git status on wrong branch -> refuses +mk_wave_case stfail +out="$(PATH="$GIT_FAIL_BIN:$PATH" run_wave_wt)"; rc=$? +chk_cmd "wave status-fail: refuses (nonzero)" test "$rc" -ne 0 +chk_has "wave status-fail: says git status failed" "$out" "git status failed" +chk_cmd "wave status-fail: worktree kept on old branch" test "$(git -C "$WAVE_WT" rev-parse --abbrev-ref HEAD)" = "other/branch" + +# =========================================================================== +echo "=== C. Shared helper reuse (one copy in lib/wrap/wt-guard.sh) ===" +# =========================================================================== +chk_cmd "shared helper file exists" test -f "$KIT_DIR/lib/wrap/wt-guard.sh" +def_count="$(grep -rl '^_wt_ignored_guard()' "$KIT_DIR/lib/" 2>/dev/null | wc -l | tr -d ' ')" +chk_cmd "exactly one _wt_ignored_guard definition in lib/" test "$def_count" = 1 +for caller in lib/wrap/wrap-common.sh lib/goal/wt.sh lib/queue/orchestrate.sh; do + chk_cmd "$caller references wt-guard.sh" grep -q 'wt-guard\.sh' "$KIT_DIR/$caller" +done + +echo +if [ "$FAIL" -gt 0 ]; then + echo "test-worktree-removers-ignored: $PASS passed, $FAIL FAILED of $TOTAL" >&2 + exit 1 +fi +echo "test-worktree-removers-ignored: all $PASS passed"