From 81639ccef625edc337a5a6eeb7488611b3f65af4 Mon Sep 17 00:00:00 2001 From: Han Ngo Date: Wed, 2 Dec 2026 15:22:56 +0700 Subject: [PATCH 1/5] fix(wrap): harden busy check, leased delete, and sweep lock --- docs/reference/wrap.md | 6 +- lib/config/module-registry.md | 1 - lib/wrap/wrap-apply.sh | 95 +++++--- lib/wrap/wrap-common.sh | 4 + lib/wrap/wrap-land.sh | 4 +- lib/wrap/wrap-sweep.sh | 192 ++++++++++++++--- lib/wrap/wrap.sh | 11 +- tests/test-wrap-apply-ignored.sh | 100 ++++----- tests/test-wrap-apply.sh | 9 +- tests/test-wrap-busy-no-switch.sh | 260 ++++++++++++++++++++++ tests/test-wrap-sweep-lock.sh | 346 ++++++++++++++++++++++++++++++ tests/test-wrap-sweep.sh | 42 ++-- 12 files changed, 933 insertions(+), 137 deletions(-) create mode 100755 tests/test-wrap-busy-no-switch.sh create mode 100755 tests/test-wrap-sweep-lock.sh diff --git a/docs/reference/wrap.md b/docs/reference/wrap.md index ab11ccaea..cc2891ca3 100644 --- a/docs/reference/wrap.md +++ b/docs/reference/wrap.md @@ -40,7 +40,7 @@ Each row below was read from the verb's source in `lib/wrap/`. | Re-check whether another writer is active | `wrap session --writers --check-mark STATE [--self WT]... [--text] ` | Prints one `wrap-writers/1` document: one row per worktree other than the session's own, except the main checkout, which is never excluded. Each row carries that worktree's `index.lock` state and HEAD-reflog identity compared with the mark. `wrap session --writers --mark STATE [--self WT]... ` records the mark in scratch state. `--since EPOCH` remains the stateless fallback. `--text` prints the same facts as text. | | Tidy a repo, preview first | `wrap apply ` | Dry run by default. Prints `WOULD ...` lines. Add `--apply` to write. | | Remove merged worktrees, all sessions | `wrap apply --apply --worktrees ` | Removes every clean, non-detached worktree whose branch is proven merged, then deletes the branch. Other sessions' worktrees qualify too. A worktree holding uncommitted work (including untracked files when `status.showUntrackedFiles=no`), skip-worktree or assume-unchanged entries (including sparse checkouts), an initialized submodule, a gitlink with a `.git` on disk, or a non-empty git-dir `modules/` directory, a non-regenerable ignored path (anything outside the build-cache list or an identical `.claude/` copy under non-symlinked directories in the main checkout), an odd path, a status that fails or changes right before removal, or an unreadable check is kept with its branch. | -| Sweep every repo under one or more roots | `wrap sweep [--apply] [--worktrees] [--json] [--no-fetch] [...]` | Discovers every repo at the root or depth 1 to 2 (`/*/` and `/*/*/`), or reads `wrap.sweep_roots` when no root is given, locks each repo (`${XDG_STATE_HOME:-$HOME/.local/state}/wrap/locks/`), and runs the apply cleanup logic in parallel. Dry run by default; `--json` emits `wrap-sweep/1` on stdout and human lines on stderr. Runs `wrap.workspace_rm` (` `) after each worktree removal under `--apply`. `--no-fetch` (dry run only) skips the fetch and reads the refs on disk, for read-only callers such as `wrap session`. Exit 0 ok, 1 usage error, 2 repo error, 3 all locked. | +| Sweep every repo under one or more roots | `wrap sweep [--apply] [--worktrees] [--json] [--no-fetch] [...]` | Discovers every repo at the root or depth 1 to 2 (`/*/` and `/*/*/`), or reads `wrap.sweep_roots` when no root is given, locks each repo (`${XDG_STATE_HOME:-$HOME/.local/state}/wrap/locks/`), and runs the apply cleanup logic in parallel. Dry run by default; `--json` emits `wrap-sweep/1` on stdout and human lines on stderr, with `deleted_tip` carrying the full SHA of each deleted branch tip on `removed` rows (`null` otherwise). Runs `wrap.workspace_rm` (` `) after each worktree removal under `--apply`. `--no-fetch` (dry run only) skips the fetch and reads the refs on disk, for read-only callers such as `wrap session`. Exit 0 ok, 1 usage error, 2 repo error, 3 all locked. | | Remove only my own worktrees | `wrap apply --apply --own ` | `--own` is repeatable and implies the worktree opt-in, so `--worktrees` is not needed. Unnamed worktrees are skipped. The local all-branches sweep and `--archive-unmerged` are skipped. The origin merged-branch sweep is scoped to the branches the named worktrees held (`-- origin branches (own scope: N named branches):`); plain `apply` and `--worktrees` sweep origin repo-wide. Stray carry and pull still run. | | Tidy without pulling the shared checkout | `wrap apply --apply --no-pull --own ` | `--no-pull` without `--own` skips both the worktree sweep and the branch sweep. | | Pull the default branch and nothing else | `wrap apply --apply --pull-only ` | Cannot combine with `--worktrees`, `--own`, `--archive-unmerged`, `--archive-worktrees`, `--tips-file`, or `--no-pull`. | @@ -230,7 +230,7 @@ Re-run the step 0 check first. Then, in this order: remove the session's own wor - `--worktrees` sweeps every proven-merged worktree in the repo, including other sessions'. That is why `--own ` per worktree is the default (`bin/wrap apply --own [--own ...] `), naming only the worktrees this session created; `--own` implies the worktree opt-in for the named set, reports a named path that is no registered worktree, skips the all-branches sweep, and scopes the origin sweep to the named worktrees' branches, so nothing outside the session's own set is a candidate. Every refusal `--worktrees` applies still applies to a named worktree. `wrap.sh` refuses (exit 64) a single argument that packs flags, such as ` --own ` from an unsplit shell variable, so pass each flag and path as its own word. - `bin/wrap apply` without `--apply` changes nothing; always read its dry-run SKIP lines before adding `--apply`. - `--archive-unmerged` is opt-in and never runs as part of this step's own default flow (it is never passed alongside `--own`). When the operator asks to clear out real, unmerged work a branch sweep would otherwise leave forever, `bin/wrap apply --archive-unmerged ` previews it: every local branch that is not current, default, or worktree-held, and carries at least one commit `git cherry origin/ ` shows as a `+` (origin lacks its patch), prints `WOULD archive -> origin refs/archive/- ( unique commits)`. `--apply` pushes it there (no force; an existing archive ref refuses the push and reports `FAILED archive : `, branch kept) and deletes the local branch only once that push lands, printing `archived -> `. A branch with no unique commit is left alone for the merged-branch sweep above. -- `--archive-worktrees` is opt-in and never part of this step's default flow (it is never passed alongside `--own` or `--no-pull`, and each prints a section SKIP). It runs only when the operator names it, to clear out stale worktrees `--worktrees` never removes: a branch-held one whose branch is unmerged, a detached one with a commit origin lacks, or a dirty one. `bin/wrap apply --archive-worktrees ` previews each with `WOULD archive worktree [|detached, unique commits, uncommitted paths, idle h] -> origin refs/archive/-, then remove it`. A worktree qualifies only when it is stale (idle at least `wrap.archive_worktree_min_age_hours`, root-only, default 72, read from the newest reflog entry, the admin `HEAD`, `commondir` and `locked` mtimes, and every uncommitted path), not locked by a live pid, not busy in `lsof`, and holds no embedded repository, initialized submodule, secret-shaped uncommitted path, unmerged index, unborn HEAD, in-progress merge or rebase, or ignored path a removal would lose (build output and `.claude/` copies identical to the main checkout's are regenerable; anything else, `.env` included, blocks). The sweep needs the busy check: with no `lsof` or `KIT_WRAP_SKIP_BUSY_CHECK=1` the whole section skips. `--apply` snapshots uncommitted files into a commit built from a temporary index (the worktree's own index, HEAD and files are never written), pushes the tip with a create-only lease (`--force-with-lease=refs/heads/:`, never forced; an existing ref is `FAILED ... already exists`), reads the ref back, re-reads the worktree, and only then removes it and deletes its branch, leased to the HEAD it read: `archived worktree -> (); removed[, deleted]`. A change during the push prints `kept : ...` and keeps it. Origin receives every uncommitted, non-ignored byte of an archived worktree, so the operator names the flag knowing that. Restore one with `git fetch origin refs/archive/-:refs/heads/-` then `git worktree add -`: uncommitted work returns as one or two commits on top, the branch returns under the archive name, and regenerable ignored paths do not return. +- `--archive-worktrees` is opt-in and never part of this step's default flow (it is never passed alongside `--own` or `--no-pull`, and each prints a section SKIP). It runs only when the operator names it, to clear out stale worktrees `--worktrees` never removes: a branch-held one whose branch is unmerged, a detached one with a commit origin lacks, or a dirty one. `bin/wrap apply --archive-worktrees ` previews each with `WOULD archive worktree [|detached, unique commits, uncommitted paths, idle h] -> origin refs/archive/-, then remove it`. A worktree qualifies only when it is stale (idle at least `wrap.archive_worktree_min_age_hours`, root-only, default 72, read from the newest reflog entry, the admin `HEAD`, `commondir` and `locked` mtimes, and every uncommitted path), not locked by a live pid, not busy in `lsof`, and holds no embedded repository, initialized submodule, secret-shaped uncommitted path, unmerged index, unborn HEAD, in-progress merge or rebase, or ignored path a removal would lose (build output and `.claude/` copies identical to the main checkout's are regenerable; anything else, `.env` included, blocks). The sweep needs the busy check: with no `lsof` the whole section skips. `--apply` snapshots uncommitted files into a commit built from a temporary index (the worktree's own index, HEAD and files are never written), pushes the tip with a create-only lease (`--force-with-lease=refs/heads/:`, never forced; an existing ref is `FAILED ... already exists`), reads the ref back, re-reads the worktree, and only then removes it and deletes its branch, leased to the HEAD it read: `archived worktree -> (); removed[, deleted]`. A change during the push prints `kept : ...` and keeps it. Origin receives every uncommitted, non-ignored byte of an archived worktree, so the operator names the flag knowing that. Restore one with `git fetch origin refs/archive/-:refs/heads/-` then `git worktree add -`: uncommitted work returns as one or two commits on top, the branch returns under the archive name, and regenerable ignored paths do not return. - Pull on the default branch is `--ff-only`; off the default branch, `apply` fetches the default branch into itself instead and reports a refusal as `FAILED`, never forced. That fetch refuses outright when the default branch is checked out in another worktree, which is the second way a repo stays behind; the main-checkout rule above is what avoids both. - `wrap.pull_past_dirty` (default `false`) governs the third way a repo stays behind: a sibling session's dirty TRACKED file that git refuses to overwrite. `false` reports `FAILED` and leaves the checkout behind. `true` stashes only the blocking files under a run-named stash, pulls, and pops that stash by ref; a pop conflict prints `PULLED, POP CONFLICT: , stash kept` and exits 2, leaving the markers and the stash for the operator. Whether a dirty file reaches that conflict at all is the repo's own call: a file `.gitattributes` declares `merge=union` never blocks the pull in the first place (its local lines are carried across, below the `---` anchor, or by git's union driver when the file has no anchor), and one that rides in the stash resolves during the pop. This repo declares its board and its implementation notes union for exactly that reason. Untracked files, a dirty index, and pre-existing stashes are out of its reach at either setting. Name the knob in `FYI`, as a `STATE` row, whenever it changed what the pull did. If a run is interrupted between the stash and the pop, the blocking files are still in the stash: `git -C stash list | grep wrap-pull-past-dirty` names it and `git stash pop ` finishes the restore. - `apply` reports STRAY LINES on the main checkout, whatever branch it has checked out: for each dirty `merge=union` file, the lines neither origin/ nor HEAD holds. A session that ran `board set` or `wrap log` in the shared checkout leaves exactly these, and the pull carry keeps them local forever. The dry run prints `WOULD carry N stray lines in onto a branch`. `--apply` commits origin's version plus those lines (on a kanban board a flipped row replaces origin's row of that id in place, then `dedupe-all` runs) to a new `wrap/stray--` branch in a scratch worktree, pushes it, and prints `gh pr create --head `; it opens no PR and never touches the working copy. Relay that command under `Needs you`. An origin `wrap/stray--*` branch that already exists skips the file. `wrap.autoland_carry` (default `false`, and off whenever `wrap.merge_own_prs` is `false`) true replaces the printed command: `apply` opens the branch's PR (or adopts its one open own non-draft PR), waits up to `KIT_WRAP_CARRY_CHECKS_SECS` (300) for pending checks, and merges it through `wrap merge --apply --pr `, the same gate, re-merge and tree verify step 3 uses; the merge lines print indented under the carry. An existing carry branch is landed the same way, but only when its name is the exact `wrap/stray--`, its diff touches that file alone, and every line it adds is in the working copy; otherwise `SKIP land : not a carry of alone, or adds lines this checkout lacks` and the file skips as before. Once every existing branch lands, the lines origin still lacks carry and land too, or `: the landed carry held every stray line` prints. A gate refusal prints `PR # left open; wrap merge --apply --pr merges it once green` (step 3 picks it up; exit unchanged); a failed merge or `TREE MISMATCH` exits 2. Nothing goes under `Needs you` for a landed carry. `wrap.carry_stray_lines` (default `true`) false reports the count and carries nothing; name it in `FYI` as a `STATE` row. Under `--no-pull` (a step 0 stop) the carry also pushes nothing, whatever the knobs say: it prints `SKIP stray lines: --no-pull (N lines in stay local)`. @@ -238,7 +238,7 @@ Re-run the step 0 check first. Then, in this order: remove the session's own wor - When the operator wants the pull alone, for example right after merging one PR while other sessions still own the other open branches in a shared checkout, `bin/wrap apply --pull-only [--apply] ` runs exactly `fetch --prune`, default-branch resolution, and the pull section above (the union carry and `wrap.pull_past_dirty` both still apply); it skips every worktree, branch, archive, origin-branch, stray-line, and stray-commit step and prints no section for any of them. It refuses to combine with `--worktrees`, `--archive-unmerged`, `--own`, or `--tips-file` (exit 64, naming the flag). It skips the stray-commits step, so it names what it leaves: a default branch ahead of origin prints `NOTE: is N commits ahead of origin/; --pull-only never carries them, plain apply --apply does` in the pull section. Merely AHEAD (origin's own tip unmoved), the pull is a no-op, exit 0. DIVERGED (origin's tip also moved), the pull still fails, `FAILED pull --ff-only`, exit 2. Either way, plain `apply --apply` (no `--pull-only`) is what carries stray commits onto a branch and moves the default branch back so a diverged pull can land. The pull is the whole job here, so a repo whose default branch does not resolve exits 2, dry run or not, and a pull skipped because `index.lock` stays held exits 2 under `--apply` (a dry run still exits 0). Plain `apply` exits 0 on both. It also skips the tip snapshot and the `gh auth status` probe, since only the skipped sweeps read them. Relay a `NOTE: ... ahead` line under `FYI`. `--no-pull` is its opposite and refuses `--pull-only` (exit 64, naming `--no-pull`). - The session's own `EnterWorktree` worktree goes FIRST, before `wrap apply` runs, so the harness records the removal instead of finding the directory gone. It writes no main-checkout state, so it runs under a step 0 stop too. Once `wrap scan` proves its branch squash-merged (tip matches the PR head) and the worktree is clean, remove it: `ExitWorktree remove` with `discard_changes: true` (the squashed commits are not ancestors of the default branch, so the tool asks; the proof is the confirmation), then `git branch -D `. The operator gave that confirmation once, as a standing rule, and a worktree whose PR merged this session is finished work, never something to keep. `ExitWorktree keep` only when the worktree is dirty, the branch is not proven merged, or the proof is unavailable (no `gh`); say which in `Left alone`. A plain secondary worktree of this session routes through `wrap apply --own `, which skips it when dirty, detached, held by the checked-out branch, or on a branch no merge proof covers, and otherwise removes it and deletes that branch. A merge proof is one of three: the branch is an ancestor of `origin/` and not a never-used branch created off that default line, its content is ABSORBED (every path it changed since its merge base is byte-identical on `origin/`, the shape of a subagent branch whose lead re-committed the work under its own PR; a tree comparison, so no merge driver can fake it), or gh shows a squash merge whose head is the branch tip. A LOCK is not a skip reason there: the Agent tool locks every worktree it creates, so `apply` overrides the lock once the merge proof holds, then confirms the path is gone and reports `FAILED` when it is not. - Never remove a dirty or foreign worktree, under `--worktrees` or otherwise. The one exception is `--archive-worktrees`, which the operator names: it removes a stale dirty worktree only after a snapshot of its uncommitted files is on origin and read back. -- Never remove a worktree a live process still holds: `apply` (`--worktrees`, `--own` and `--archive-worktrees`) and `land` check, right before the removal, for any process outside the wrap run whose cwd or open file sits inside it (a background subagent's headless browser, a blocked `cp -i`, a test loop). A holder prints `SKIP : busy, held by pid ()` (plus `and N more`), keeps the worktree and its branch, and the rest of the pass continues; `land` still reports its merge as done and says the worktree stayed. The `| tail` reader of `wrap land | tail -6` (stdin a pipe, in wrap's process group or its shell's, so `timeout 120 wrap land | tail` too) is the caller's own and never counts. Relay the line under `Left alone`, and re-run once the holder exits. `KIT_WRAP_SKIP_BUSY_CHECK=1` skips the check; without `lsof` one `NOTE: busy check unavailable (no lsof)` prints and removal proceeds as before. +- Never remove a worktree a live process still holds: `apply` (`--worktrees`, `--own` and `--archive-worktrees`) and `land` check, right before the removal, for any process outside the wrap run whose cwd or open file sits inside it (a background subagent's headless browser, a blocked `cp -i`, a test loop). A holder prints `SKIP : busy, held by pid ()` (plus `and N more`), keeps the worktree and its branch, and the rest of the pass continues; `land` still reports its merge as done and says the worktree stayed. The `| tail` reader of `wrap land | tail -6` (stdin a pipe, in wrap's process group or its shell's, so `timeout 120 wrap land | tail` too) is the caller's own and never counts. Relay the line under `Left alone`, and re-run once the holder exits. Without `lsof` one `NOTE: busy check unavailable (no lsof)` prints and removal proceeds as before. Local branch deletes after a merge proof are leased to the tip wrap verified (refused if the branch moved). - Never force-push and never rewrite history to make a delete or a pull succeed. The stray-commit move is the one local ref `apply` moves, and only after origin holds every commit it moves away from. `bin/wrap merge --apply --pr --rebase-stacked ` is the one opt-in rewrite, for a child PR whose parent squash-merged: it is never part of a default flow and runs only when the operator names the flag. ### Step 6: activity line diff --git a/lib/config/module-registry.md b/lib/config/module-registry.md index 534a8dde9..4ec1f3118 100644 --- a/lib/config/module-registry.md +++ b/lib/config/module-registry.md @@ -440,7 +440,6 @@ never turns the step off. | KIT_WRAP_LAND_GRACE_SECS | env-only | `30` | [impl] | wrap | `wrap land`, before the first merge, on a repo with a `pull_request` workflow: seconds, one read every 10s, to hold while no check has registered on the PR yet, for a workflow with a `paths` or `labeled` filter (it may start nothing). Pending checks then wait to `KIT_WRAP_CARRY_CHECKS_SECS`. A non-numeric value falls back to 30. | | KIT_WRAP_LAND_REGISTER_SECS | env-only | `300` | [impl] | wrap | `wrap land`, before the first merge: the same hold, for a repo whose `pull_request` workflow carries no `paths` or `labeled` filter and so must start a run on every PR. GitHub has queued such a run 190s after the PR opened. The hold ends at the first check that appears. When none registers it prints `no checks registered on # after s; merging with none`. A non-numeric value falls back to 300. | | KIT_WRAP_LAND_GRACE_SECS | env-only | `30` | [impl] | wrap | `wrap land`, before the first merge, on a repo with a `pull_request` workflow: seconds, one read every 10s, to hold while no check has registered on the PR yet. Pending checks then wait to `KIT_WRAP_CARRY_CHECKS_SECS`. A non-numeric value falls back to 30. | -| KIT_WRAP_SKIP_BUSY_CHECK | env-only | `0` | [impl] | wrap | `1` skips the busy check `land`, `apply --worktrees` and `apply --own` run before removing a worktree. The check refuses a worktree a live process outside the wrap run still holds (cwd or an open file inside it): `SKIP : busy, held by pid ()`, worktree and branch kept. The caller's own pipeline reader (stdin a pipe, in wrap's process group or its shell's, e.g. `timeout 120 wrap land | tail`) never counts. Without `lsof` the check prints one NOTE and removal proceeds. `apply --archive-worktrees` fails closed instead: with this set to `1`, or with no `lsof`, its whole section prints `SKIP archive worktrees: busy check unavailable` and archives nothing, because it pushes and removes unmerged work. | | KIT_SKILL_DIRS | env-only | `$HOME/.claude/skills` plus `${CLAUDE_PLUGIN_ROOT:-}/skills` when set | [consumer] | wrap | Colon-separated list of skill directories `config seams` searches for a `skill` kind row's `SKILL.md` (e.g. `wrap.before`). Entries whose realpath does not sit under `$HOME` are dropped, because a repo `.envrc` can set this. Not read by any code yet; `config seams` is the first consumer. | ### test (dev-loop host-load warning and suite timing history, no install module) diff --git a/lib/wrap/wrap-apply.sh b/lib/wrap/wrap-apply.sh index ac1913b3e..a3e062044 100644 --- a/lib/wrap/wrap-apply.sh +++ b/lib/wrap/wrap-apply.sh @@ -41,6 +41,28 @@ _wt_cleared() { return 0 } +# _delete_branch_leased -- atomically deletes refs/heads/ +# only when it still points at , is not a symbolic ref, and is checked out in +# neither HEAD nor any worktree. Removes branch. config on success. +_delete_branch_leased() { + local repo="$1" b="$2" expected="$3" wl + [ -n "$b" ] && [ -n "$expected" ] || return 1 + if git -C "$repo" symbolic-ref -q "refs/heads/${b}" >/dev/null 2>&1; then + return 1 + fi + if [ "$(git -C "$repo" symbolic-ref -q HEAD 2>/dev/null)" = "refs/heads/${b}" ]; then + return 1 + fi + # Capture before matching: an early grep exit under pipefail can SIGPIPE git. + if ! wl="$(git -C "$repo" worktree list --porcelain 2>/dev/null)" \ + || case $'\n'"${wl}"$'\n' in *$'\n'"branch refs/heads/${b}"$'\n'*) true ;; *) false ;; esac; then + return 1 + fi + git -C "$repo" update-ref --no-deref -d "refs/heads/${b}" "$expected" || return $? + git -C "$repo" config --remove-section "branch.${b}" >/dev/null 2>&1 || true + return 0 +} + # _wt_busy -- 0 when a live process outside this wrap run holds the worktree: # its current directory or an open file or mapping sits at or under the path. Sets BUSY_MSG to # the one-line `SKIP : busy, held by pid ()` (plus `and N more`). A @@ -55,8 +77,7 @@ _wt_cleared() { # inside the worktree, lives only until wrap exits, and would otherwise read as a holder that # never leaves. A background job (stdin not a pipe) or one from an earlier call (another # group) still counts. -# KIT_WRAP_SKIP_BUSY_CHECK=1 turns the check off. Without lsof it prints one NOTE per run and -# answers "not busy", today's behavior. +# Without lsof it prints one NOTE per run and answers "not busy", today's behavior. BUSY_MSG="" BUSY_PID="" _WT_BUSY_NOTED=0 @@ -81,7 +102,6 @@ _wt_busy() { local wt="$1" mode="${2:-snap}" canon holders psnap pid cmd n BUSY_MSG="" BUSY_PID="" - [ "${KIT_WRAP_SKIP_BUSY_CHECK:-0}" = 1 ] && return 1 if ! command -v lsof >/dev/null 2>&1; then if [ "$_WT_BUSY_NOTED" = 0 ]; then echo " NOTE: busy check unavailable (no lsof)"; _WT_BUSY_NOTED=1 @@ -310,11 +330,12 @@ _sweep_wt_holder() { esac } -# _emit_sweep_row +# _emit_sweep_row [] _emit_sweep_row() { [ -n "${_SWEEP_ROWS_FILE:-}" ] || return 0 local kind="$1" path="$2" branch="$3" verdict="$4" reason="$5" local pr="$6" pr_state="$7" dirty="$8" holder="$9" own_commits="${10}" workspace_rm="${11}" + local deleted_tip="${12:-}" jq -cn \ --arg kind "$kind" \ --arg path "$path" \ @@ -326,7 +347,8 @@ _emit_sweep_row() { --arg dirty "$dirty" \ --arg holder "$holder" \ --arg own_commits "$own_commits" \ - --arg workspace_rm "$workspace_rm" ' + --arg workspace_rm "$workspace_rm" \ + --arg deleted_tip "$deleted_tip" ' { kind: $kind, path: (if $path == "" then null else $path end), @@ -338,7 +360,8 @@ _emit_sweep_row() { dirty: (if $dirty == "true" then true elif $dirty == "false" then false else null end), holder: (if ($holder | test("^[0-9]+$")) then ($holder | tonumber) else null end), own_commits: (if ($own_commits | test("^[0-9]+$")) then ($own_commits | tonumber) else null end), - workspace_rm: (if ($workspace_rm == "" or $workspace_rm == "null") then null else $workspace_rm end) + workspace_rm: (if ($workspace_rm == "" or $workspace_rm == "null") then null else $workspace_rm end), + deleted_tip: (if ($deleted_tip == "" or $deleted_tip == "null") then null else $deleted_tip end) }' >> "$_SWEEP_ROWS_FILE" } @@ -450,7 +473,8 @@ _apply_worktrees() { fi continue fi - read -r lcode lreason proof <<< "$(_apply_branch_merged "$repo" "$def" "$ghs" "$wtb")" + tip="$(git -C "$repo" rev-parse --verify --quiet "refs/heads/${wtb}" 2>/dev/null)" + read -r lcode lreason proof <<< "$(_apply_branch_merged --tip "$tip" "$repo" "$def" "$ghs" "$wtb")" if [ "$lcode" != SAFE ]; then local skip_reason if [ "${lcode} ${lreason}" = "LEAVE fresh" ]; then @@ -469,8 +493,8 @@ _apply_worktrees() { continue fi # The proof above can cost a network round trip, so both destructive inputs are re-read right - # before the force: `-f -f` overrides a worktree that went dirty, and `-D` discards a commit - # made since the run's own tip snapshot. + # before the force: `-f -f` overrides a worktree that went dirty, and a leased delete refuses + # a branch whose tip moved since the proof read. if [ -n "$(git -C "$wt" status --short 2>/dev/null)" ]; then echo " SKIP ${wt}: went dirty while the proof was read" if [ -n "${_SWEEP_ROWS_FILE:-}" ]; then @@ -482,19 +506,32 @@ _apply_worktrees() { fi continue fi - tip="$(git -C "$repo" rev-parse --verify --quiet "refs/heads/${wtb}" 2>/dev/null)" + local tip_now + tip_now="$(git -C "$repo" rev-parse --verify --quiet "refs/heads/${wtb}" 2>/dev/null)" scanned="$(_scanned_tip "$wtb")" - if [ -n "$scanned" ] && [ "$tip" != "$scanned" ]; then - local moved_msg="${wtb} tip moved during this run ($(_short "$scanned") -> $(_short "$tip"))" + if [ -n "$scanned" ] && [ "$tip_now" != "$scanned" ]; then + local moved_msg="${wtb} tip moved during this run ($(_short "$scanned") -> $(_short "$tip_now"))" echo " SKIP ${wt}: ${moved_msg}" if [ -n "${_SWEEP_ROWS_FILE:-}" ]; then - IFS=$'\t' read -r pr_n pr_st <<< "$(_sweep_row_pr_info "$repo" "$def" "$ghs" "$wtb" "$tip")" + IFS=$'\t' read -r pr_n pr_st <<< "$(_sweep_row_pr_info "$repo" "$def" "$ghs" "$wtb" "$tip_now")" + own_c="$(_branch_own_commits "$repo" "$def" "$wtb")" + hpid="$(_sweep_wt_holder "$wt")" + _emit_sweep_row worktree "$wt" "$wtb" keep "$moved_msg" "$pr_n" "$pr_st" false "$hpid" "$own_c" null + fi + continue + fi + if [ -n "$tip" ] && [ "$tip_now" != "$tip" ]; then + local moved_msg="${wtb} tip moved while the proof was read ($(_short "$tip") -> $(_short "$tip_now"))" + echo " SKIP ${wt}: ${moved_msg}" + if [ -n "${_SWEEP_ROWS_FILE:-}" ]; then + IFS=$'\t' read -r pr_n pr_st <<< "$(_sweep_row_pr_info "$repo" "$def" "$ghs" "$wtb" "$tip_now")" own_c="$(_branch_own_commits "$repo" "$def" "$wtb")" hpid="$(_sweep_wt_holder "$wt")" _emit_sweep_row worktree "$wt" "$wtb" keep "$moved_msg" "$pr_n" "$pr_st" false "$hpid" "$own_c" null fi continue fi + tip="$tip_now" lock="unlocked"; _wt_locked "$wt" && lock="locked" if [ "$lock" = "locked" ] && _wt_lock_live "$wt"; then local lpid; lpid="$(_wt_lock_pid "$wt")" @@ -570,6 +607,7 @@ _apply_worktrees() { elif ! _write_guard "$repo"; then WT_IGN_MSG="index.lock held by another writer" 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" + elif [ "$(git -C "$repo" rev-parse --verify --quiet "refs/heads/${wtb}" 2>/dev/null)" != "$tip" ]; then WT_IGN_MSG="${wtb} tip moved before removal" fi if [ -n "$WT_IGN_MSG" ]; then [ -n "$raw1$raw2" ] && rm -f ${raw1:+"$raw1"} ${raw2:+"$raw2"}; echo " SKIP $(_san "$wt"): ${WT_IGN_MSG}" @@ -583,9 +621,13 @@ _apply_worktrees() { if _wt_cleared "$repo" "$wt"; then wrm_res="$(_run_seam_workspace_rm "$_APPLY_WORKSPACE_RM" "$wt" "$repo")" run "$repo" "delete ${wtb} (${proof}, its ${lock} worktree is gone)" \ - git -C "$repo" branch -D "$wtb" + _delete_branch_leased "$repo" "$wtb" "$tip" if [ -n "${_SWEEP_ROWS_FILE:-}" ]; then - _emit_sweep_row worktree "$wt" "$wtb" removed "${proof}" "$pr_n" "$pr_st" false null "$own_c" "$wrm_res" + if [ "$_RUN_LAST_RC" -eq 0 ] && ! _ref_exists "$repo" "refs/heads/${wtb}"; then + _emit_sweep_row worktree "$wt" "$wtb" removed "${proof}" "$pr_n" "$pr_st" false null "$own_c" "$wrm_res" "$tip" + else + _emit_sweep_row worktree "$wt" "$wtb" error "${wt} removed, ${wtb} not deleted" "$pr_n" "$pr_st" false null "$own_c" "$wrm_res" null + fi fi else echo " FAILED ${verdict}: ${wt} survived the removal, ${wtb} not deleted" @@ -657,20 +699,19 @@ _apply_branches() { IFS=$'\t' read -r pr_n pr_st <<< "$(_sweep_row_pr_info "$repo" "$def" "$ghs" "$b" "$tip")" own_c="$(_branch_own_commits "$repo" "$def" "$b")" fi - # -D, not -d: the proof is wrap's own, against origin/. `branch -d` judges against the - # branch's OWN upstream (or HEAD when it has none), so it refused a branch that tracks - # another ref or nothing even though origin/ already holds its tip. The proof judges the - # sha read above, see branch_merged. + # Leased ref delete, not branch -d/-D: the proof is wrap's own against origin/ on the + # exact tip read above, so a commit added in the window before delete refuses instead of + # being lost. read -r lcode lreason ldetail <<< "$(_apply_branch_merged --tip "$tip" "$repo" "$def" "$ghs" "$b")" local b_verdict="keep" b_reason="" case "${lcode} ${lreason}" in "SAFE ancestor"|"SAFE absorbed") b_reason="${ldetail}" - run "$repo" "delete ${b} (${ldetail})" git -C "$repo" branch -D "$b" ;; + run "$repo" "delete ${b} (${ldetail})" _delete_branch_leased "$repo" "$b" "$tip" ;; "SAFE squash") b_reason="squash-merged into ${def}, tip matches the PR head" run "$repo" "delete ${b} (${b_reason})" \ - git -C "$repo" branch -D "$b" ;; + _delete_branch_leased "$repo" "$b" "$tip" ;; "LEAVE fresh") b_reason="${ldetail}" echo " SKIP ${b}: ${ldetail}" ;; @@ -688,16 +729,18 @@ _apply_branches() { echo " SKIP ${b}: ${b_reason}" ;; esac if [ -n "${_SWEEP_ROWS_FILE:-}" ]; then + local b_dtip="" if [ "$lcode" = SAFE ]; then if [ "$APPLY" != 1 ]; then b_verdict="would_remove" - elif ! _ref_exists "$repo" "refs/heads/${b}"; then + elif [ "$_RUN_LAST_RC" -eq 0 ] && ! _ref_exists "$repo" "refs/heads/${b}"; then b_verdict="removed" + b_dtip="$tip" else b_verdict="error" fi fi - _emit_sweep_row branch "" "$b" "$b_verdict" "$b_reason" "$pr_n" "$pr_st" null null "$own_c" null + _emit_sweep_row branch "" "$b" "$b_verdict" "$b_reason" "$pr_n" "$pr_st" null null "$own_c" null "$b_dtip" fi done } @@ -958,8 +1001,8 @@ _apply_archive_worktrees() { esac # Fail closed: --worktrees removes only proven-merged work and proceeds without lsof; this # sweep pushes and removes unmerged work, so it needs the busy check. - if [ "${KIT_WRAP_SKIP_BUSY_CHECK:-0}" = 1 ] || ! command -v lsof >/dev/null 2>&1; then - echo " SKIP archive worktrees: busy check unavailable (no lsof, or KIT_WRAP_SKIP_BUSY_CHECK=1)"; return 0 + if ! command -v lsof >/dev/null 2>&1; then + echo " SKIP archive worktrees: busy check unavailable (no lsof)"; return 0 fi # lsof always lists its caller: empty output means it failed (denied, broken), and # _wt_busy would then read every worktree as idle. @@ -1440,7 +1483,7 @@ _apply_origin_branches() { if printf '%s\n' "$rem_names" | grep -qxF "${b_arr[$j]}"; then _emit_sweep_row origin_branch "" "${b_arr[$j]}" error "failed to delete merged branch on origin" "$pr_n" "$pr_st" null null null null else - _emit_sweep_row origin_branch "" "${b_arr[$j]}" removed "merged branch on origin" "$pr_n" "$pr_st" null null null null + _emit_sweep_row origin_branch "" "${b_arr[$j]}" removed "merged branch on origin" "$pr_n" "$pr_st" null null null null "${t_arr[$j]}" fi j=$(( j + 1 )) done diff --git a/lib/wrap/wrap-common.sh b/lib/wrap/wrap-common.sh index 7da30a3b0..0069b19d7 100644 --- a/lib/wrap/wrap-common.sh +++ b/lib/wrap/wrap-common.sh @@ -315,10 +315,13 @@ _write_guard() { # run -- print the verdict, execute only under --apply. # A failed write is reported once and turns the run's exit code into 2. Nothing is retried. +_RUN_LAST_RC=0 run() { + _RUN_LAST_RC=0 local repo="$1" verdict="$2"; shift 2 if ! _write_guard "$repo"; then echo " SKIP ${verdict}: index.lock held by another writer" + _RUN_LAST_RC=1 # Under --pull-only the pull is the whole job, so a skipped write is a failed call. [ "$PULL_ONLY" = 1 ] && [ "$APPLY" = 1 ] && FAILURES=1 return 0 @@ -327,6 +330,7 @@ run() { [ "$APPLY" = 1 ] || return 0 "$@" local rc=$? + _RUN_LAST_RC=$rc if [ "$rc" -ne 0 ]; then echo " FAILED ${verdict}: exit ${rc}" FAILURES=1 diff --git a/lib/wrap/wrap-land.sh b/lib/wrap/wrap-land.sh index a35c06e2e..19c109adf 100644 --- a/lib/wrap/wrap-land.sh +++ b/lib/wrap/wrap-land.sh @@ -1169,7 +1169,7 @@ _land_tidy() { echo " ${branch} changed since it was checked; branch left in place" >&2 return 2 fi - if git -C "$repo" branch -D "$branch" >/dev/null 2>&1; then + if _delete_branch_leased "$repo" "$branch" "$tip" >/dev/null 2>&1; then echo " deleted ${branch}" else echo " FAILED delete ${branch}" >&2 @@ -1213,7 +1213,7 @@ _land_tidy() { echo " removed worktree ${wt}" _LAND_WT=removed _run_seam_workspace_rm "$(kit_config_get_root wrap.workspace_rm "")" "$wt" "$repo" >/dev/null - if git -C "$repo" branch -D "$branch" >/dev/null 2>&1; then + if _delete_branch_leased "$repo" "$branch" "$tip" >/dev/null 2>&1; then echo " deleted ${branch}" else echo " FAILED delete ${branch}" >&2 diff --git a/lib/wrap/wrap-sweep.sh b/lib/wrap/wrap-sweep.sh index 8beda8dd7..8dc962b81 100644 --- a/lib/wrap/wrap-sweep.sh +++ b/lib/wrap/wrap-sweep.sh @@ -115,42 +115,180 @@ _sweep_lock_alive() { return 1 } +_sweep_pid_lstart() { + LC_ALL=C ps -p "$1" -o lstart= 2>/dev/null | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' +} + +# _sweep_pid_etime -- elapsed runtime of in whole seconds (POSIX ps -o etime=). +_sweep_pid_etime() { + local p="$1" raw + raw="$(LC_ALL=C ps -p "$p" -o etime= 2>/dev/null)" || return 1 + raw="$(printf '%s' "$raw" | tr -d '[:space:]')" + [ -n "$raw" ] || return 1 + awk -v s="$raw" 'BEGIN { + d = 0 + if (index(s, "-") > 0) { + split(s, a, "-") + d = a[1] + 0 + s = a[2] + } + n = split(s, t, ":") + if (n == 2) print d * 86400 + t[1] * 60 + t[2] + else if (n == 3) print d * 86400 + t[1] * 3600 + t[2] * 60 + t[3] + else exit 1 + }' +} + +# _sweep_lock_pid_recycled -- 0 when started after the lock was created +# (recycled pid) or its start timestamp differs from /start. +_sweep_lock_pid_recycled() { + local p="$1" ldir="$2" saved_start="" cur_start="" pid_etime="" lock_mtime="" pmtime="" now_s="" lock_age="" + if [ -r "$ldir/start" ]; then + saved_start="$(cat "$ldir/start" 2>/dev/null || true)" + if [ -n "$saved_start" ]; then + cur_start="$(_sweep_pid_lstart "$p")" + [ -n "$cur_start" ] && [ "$saved_start" != "$cur_start" ] && return 0 + fi + fi + pid_etime="$(_sweep_pid_etime "$p")" || return 1 + lock_mtime="$(_sweep_lock_mtime "$ldir")" + if [ -e "$ldir/pid" ]; then + pmtime="$(_sweep_lock_mtime "$ldir/pid")" + if [ -n "$pmtime" ] && { [ -z "$lock_mtime" ] || [ "$pmtime" -lt "$lock_mtime" ]; }; then + lock_mtime="$pmtime" + fi + fi + [ -n "$lock_mtime" ] || return 1 + now_s="$(date +%s)" + lock_age=$(( now_s - lock_mtime )) + # A genuine holder started before or when it created the lock (pid_etime >= lock_age modulo + # integer-second truncation, 2s slack). Strictly newer start means the pid was recycled. + [ $(( lock_age - pid_etime )) -gt 2 ] && return 0 + return 1 +} + +# _sweep_lock_gate_enter [timeout_secs] -- kernel flock(2) on fd 9 to serialize +# lock acquisition and stale reclaim so two reclaimers can never evict a live holder. +# The gate file stays in place; fd 9 is closed as soon as the handshake finishes. +_sweep_lock_gate_enter() { + local gf="$1" limit="${2:-10}" rc=0 + [ -n "$gf" ] && [ ! -d "$gf" ] || return 1 + exec 9>>"$gf" 2>/dev/null || return 1 + if command -v flock >/dev/null 2>&1; then + flock -w "$limit" 9 2>/dev/null || rc=$? + elif command -v perl >/dev/null 2>&1; then + perl -MFcntl=:flock -MPOSIX=sigaction,SIGALRM,_exit -MErrno=EINTR -e ' + open(my $f, ">&=", 9) or exit 3; + my $lim = $ARGV[0]; + if ($lim <= 0) { exit(flock($f, LOCK_EX|LOCK_NB) ? 0 : 1); } + sigaction(SIGALRM, POSIX::SigAction->new(sub { _exit(1) })) or exit 3; + alarm($lim); + my $ok; + until ($ok = flock($f, LOCK_EX)) { last unless $! == EINTR; } + alarm(0); + exit($ok ? 0 : 1); + ' "$limit" 2>/dev/null || rc=$? + else + rc=1 + fi + if [ "$rc" -ne 0 ]; then + exec 9>&- 2>/dev/null || true + return 1 + fi + _SWEEP_IN_GATE=1 + return 0 +} + +_sweep_lock_gate_leave() { + [ "${_SWEEP_IN_GATE:-0}" = 1 ] || return 0 + exec 9>&- 2>/dev/null || true + _SWEEP_IN_GATE=0 +} + +_sweep_lock_write_meta() { + local ldir="$1" pid="$2" tok="$3" lstart="" + printf '%s\n' "$pid" > "$ldir/pid" 2>/dev/null || true + lstart="$(_sweep_pid_lstart "$pid")" + [ -n "$lstart" ] && printf '%s\n' "$lstart" > "$ldir/start" 2>/dev/null || true + printf '%s\n' "$tok" > "$ldir/token" 2>/dev/null || true +} + +_sweep_lock_release() { + local cur_tok="" took_gate=0 + [ -n "${_SWEEP_LOCK_DIR:-}" ] || return 0 + if [ "${_SWEEP_IN_GATE:-0}" != 1 ] && [ -n "${_SWEEP_LOCK_GATE:-}" ]; then + if _sweep_lock_gate_enter "$_SWEEP_LOCK_GATE" 2; then + took_gate=1 + fi + fi + if [ -n "${_SWEEP_LOCK_TOKEN:-}" ] && [ -r "${_SWEEP_LOCK_DIR}/token" ]; then + cur_tok="$(cat "${_SWEEP_LOCK_DIR}/token" 2>/dev/null || true)" + if [ "$cur_tok" = "$_SWEEP_LOCK_TOKEN" ]; then + rm -rf "$_SWEEP_LOCK_DIR" 2>/dev/null || true + fi + else + rm -rf "$_SWEEP_LOCK_DIR" 2>/dev/null || true + fi + _SWEEP_LOCK_DIR="" + [ "$took_gate" = 1 ] && _sweep_lock_gate_leave + return 0 +} + _sweep_one_repo() { local repo="$1" out_json="$2" out_human="$3" ghs="$4" local lock_base="${XDG_STATE_HOME:-$HOME/.local/state}/wrap/locks" mkdir -p "$lock_base" 2>/dev/null || true local mypid="${BASHPID:-}" [ -n "$mypid" ] || mypid="$(exec sh -c 'echo $PPID' 2>/dev/null)" - local stale_msg="" lock_acquired=0 - _SWEEP_LOCK_DIR="$lock_base/$(_sweep_path_sha1 "$repo")" - if mkdir "$_SWEEP_LOCK_DIR" 2>/dev/null; then - lock_acquired=1 - else - local holder_pid="" lock_mtime="" now_s="" age="" max_age="${WRAP_SWEEP_LOCK_MAX_AGE:-1800}" stale_reason="" - case "$max_age" in ''|*[!0-9]*|0) max_age=1800 ;; esac - holder_pid="$(cat "$_SWEEP_LOCK_DIR/pid" 2>/dev/null | tr -dc '0-9')" - if [ -n "$holder_pid" ]; then - if ! _sweep_lock_alive "$holder_pid"; then - stale_reason="reclaimed stale lock (dead pid ${holder_pid})" - fi + local stale_msg="" lock_acquired=0 lock_dir="" + lock_dir="$lock_base/$(_sweep_path_sha1 "$repo")" + _SWEEP_LOCK_DIR="" + _SWEEP_LOCK_GATE="${lock_dir}.gate" + _SWEEP_LOCK_TOKEN="${mypid}.${RANDOM}.$$" + _SWEEP_IN_GATE=0 + trap '_sweep_lock_release' EXIT + trap '_sweep_lock_release; exit 130' INT + trap '_sweep_lock_release; exit 143' TERM HUP + + if _sweep_lock_gate_enter "$_SWEEP_LOCK_GATE" 10; then + if mkdir "$lock_dir" 2>/dev/null; then + _SWEEP_LOCK_DIR="$lock_dir" + _sweep_lock_write_meta "$lock_dir" "$mypid" "$_SWEEP_LOCK_TOKEN" + lock_acquired=1 else - lock_mtime="$(_sweep_lock_mtime "$_SWEEP_LOCK_DIR")" - if [ -n "$lock_mtime" ]; then - now_s="$(date +%s)" - age=$(( now_s - lock_mtime )) - [ "$age" -ge "$max_age" ] && stale_reason="reclaimed stale lock (no live pid, age ${age}s)" + local holder_pid="" lock_mtime="" now_s="" age="" max_age="${WRAP_SWEEP_LOCK_MAX_AGE:-1800}" stale_reason="" + case "$max_age" in ''|*[!0-9]*|0) max_age=1800 ;; esac + holder_pid="$(tr -dc '0-9' < "$lock_dir/pid" 2>/dev/null || true)" + if [ -n "$holder_pid" ]; then + if ! _sweep_lock_alive "$holder_pid"; then + stale_reason="reclaimed stale lock (dead pid ${holder_pid})" + elif _sweep_lock_pid_recycled "$holder_pid" "$lock_dir"; then + stale_reason="reclaimed stale lock (recycled pid ${holder_pid})" + elif ! _sweep_lock_alive "$holder_pid"; then + stale_reason="reclaimed stale lock (dead pid ${holder_pid})" + fi + else + lock_mtime="$(_sweep_lock_mtime "$lock_dir")" + if [ -n "$lock_mtime" ]; then + now_s="$(date +%s)" + age=$(( now_s - lock_mtime )) + [ "$age" -ge "$max_age" ] && stale_reason="reclaimed stale lock (no live pid, age ${age}s)" + fi fi - fi - if [ -n "$stale_reason" ]; then - local stale_tmp="${_SWEEP_LOCK_DIR}.stale.${mypid}.${RANDOM}" - if mv "$_SWEEP_LOCK_DIR" "$stale_tmp" 2>/dev/null; then - rm -rf "$stale_tmp" 2>/dev/null || true - if mkdir "$_SWEEP_LOCK_DIR" 2>/dev/null; then - lock_acquired=1 - stale_msg="$stale_reason" + if [ -n "$stale_reason" ]; then + local stale_tmp="${lock_dir}.stale.${mypid}.${RANDOM}" + if mv "$lock_dir" "$stale_tmp" 2>/dev/null; then + rm -rf "$stale_tmp" 2>/dev/null || true + if mkdir "$lock_dir" 2>/dev/null; then + _SWEEP_LOCK_DIR="$lock_dir" + _sweep_lock_write_meta "$lock_dir" "$mypid" "$_SWEEP_LOCK_TOKEN" + lock_acquired=1 + stale_msg="$stale_reason" + fi fi fi fi + _sweep_lock_gate_leave fi if [ "$lock_acquired" != 1 ]; then _SWEEP_LOCK_DIR="" @@ -166,10 +304,6 @@ _sweep_one_repo() { }' > "$out_json" return 0 fi - printf '%s\n' "$mypid" > "$_SWEEP_LOCK_DIR/pid" 2>/dev/null || true - trap 'rm -rf "${_SWEEP_LOCK_DIR:-}"' EXIT - trap 'rm -rf "${_SWEEP_LOCK_DIR:-}"; exit 130' INT - trap 'rm -rf "${_SWEEP_LOCK_DIR:-}"; exit 143' TERM HUP local fetch_err first_err def cur rows_file rows_arr err_line="" : > "$out_human" diff --git a/lib/wrap/wrap.sh b/lib/wrap/wrap.sh index a38f302fa..3dd79f63f 100755 --- a/lib/wrap/wrap.sh +++ b/lib/wrap/wrap.sh @@ -31,8 +31,8 @@ # # land, apply --worktrees and apply --own refuse to remove a worktree a live process still # holds (its cwd or an open file inside it): `SKIP : busy, held by pid ()` -# (`and N more` when several), branch kept, the rest of the pass continues. Set -# KIT_WRAP_SKIP_BUSY_CHECK=1 to skip the check; without lsof it prints one NOTE and removes as before. +# (`and N more` when several), branch kept, the rest of the pass continues. Without lsof it +# prints one NOTE and removes as before. # # --under (scan and apply, repeatable) appends every immediate child of that # holds a .git file or directory, in sorted order, to the repo list. Other children are @@ -161,21 +161,27 @@ done unset _v _loc_vars # An index.lock at least this old belongs to a foreign writer, not to ordinary git traffic. +# shellcheck disable=SC2034 LOCK_STALE_SECS=5 # A routine activity line stays inside this many characters. Over it, `log` warns and writes. +# shellcheck disable=SC2034 LOG_LINE_BUDGET=300 SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" LIB_ROOT="$(cd "$SELF_DIR/.." && pwd)" # The one staging-block writer: `stage` shells out to it rather # than growing a second copy of the dedupe/render/append grammar in bash. +# shellcheck disable=SC2034 STAGING_FORMAT_PY="$LIB_ROOT/reflect/staging-format.py" +# shellcheck disable=SC2034 BACKLOG_SH="$LIB_ROOT/board/backlog.sh" # `land`'s ship-gate record shells out to this rather than reimplementing the # rid/ledger rules -- see cmd_land's use below. +# shellcheck disable=SC2034 GATE_LEDGER_SH="$LIB_ROOT/gate/gate-ledger.sh" # `land` reads the branch's proof of done through the gate's own verbs (proof-files, # captured-output, images), so the lookup the ship-gate judges is the one the PR shows. +# shellcheck disable=SC2034 PROOF_LEDGER_SH="$LIB_ROOT/gate/proof-ledger.sh" # shellcheck source=lib/config/kit-config.sh source "$LIB_ROOT/config/kit-config.sh" || { echo "FATAL: lib/config/kit-config.sh missing or unreadable" >&2; exit 1; } @@ -183,6 +189,7 @@ source "$LIB_ROOT/config/kit-config.sh" || { echo "FATAL: lib/config/kit-config. source "$LIB_ROOT/config/merge-command.sh" || { echo "FATAL: lib/config/merge-command.sh missing or unreadable" >&2; exit 1; } # shellcheck source=lib/gate/default-branch-warn.sh source "$LIB_ROOT/gate/default-branch-warn.sh" || { echo "FATAL: lib/gate/default-branch-warn.sh missing or unreadable" >&2; exit 1; } +# shellcheck source=/dev/null for _m in common scan session apply sweep pull carry ci merge land start ship log deploy rebase adopt flick; do source "$SELF_DIR/wrap-$_m.sh" || { echo "FATAL: lib/wrap/wrap-$_m.sh missing or unreadable" >&2; exit 1; }; done; unset _m _usage() { sed -n '2,55p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; } diff --git a/tests/test-wrap-apply-ignored.sh b/tests/test-wrap-apply-ignored.sh index 9ac079444..b6bc065dd 100755 --- a/tests/test-wrap-apply-ignored.sh +++ b/tests/test-wrap-apply-ignored.sh @@ -1,4 +1,5 @@ #!/usr/bin/env bash +# shellcheck disable=SC2319 # test-wrap-apply-ignored.sh -- worktree cleanup keeps a tree holding non-regenerable ignored paths. # modules under test: lib/wrap/wrap.sh lib/wrap/wrap-common.sh lib/wrap/wrap-apply.sh lib/wrap/wrap-sweep.sh set -uo pipefail @@ -17,7 +18,6 @@ chk_no() { chk "$1" "$({ trap '' PIPE; printf '%s' "$2" 2>/dev/null || :; } | g SANDBOX="$(mktemp -d "${TMPDIR:-/tmp}/dk-wrap-ign.XXXXXX")" || exit 1 SANDBOX="$(cd "$SANDBOX" && pwd)" -SANDBOX_P="$(cd "$SANDBOX" && pwd -P)" trap 'chmod -R u+w "$SANDBOX" 2>/dev/null; rm -rf "$SANDBOX"' EXIT export HOME="$SANDBOX/home" @@ -73,7 +73,7 @@ git clone -q --bare "$SEED" "$BARE" # mk_case -- creates clone and one merged worktree, prints "\t\t". mk_case() { - local name="$1" br="$2" clone="$SANDBOX/repo-$1" wt="$SANDBOX/wt-$1" wt_p + local br="$2" clone="$SANDBOX/repo-$1" wt="$SANDBOX/wt-$1" wt_p git -C "$BARE" branch -f "$br" refs/heads/feat/merged >/dev/null 2>&1 mkdir -p "$clone" git -C "$clone" init -q @@ -95,19 +95,19 @@ kept_all() { # kept_all