# gatekeep-pr: cleanup

Read from `menus.md` `## post` to resolve step guards and commands before numbering, and from `post-selection-loop.md` `### Post steps` to execute a picked cleanup, PR-named action or override. Input: the digest (`pr.url`, `pr.merge_commit`, `pr.state`, `pr.headRefOid`, `pr.baseRefName`, `issue.ref` or `issue: null`, `worktree`), the continuation record and merge-base overrides (`assessment.md` `## Configuration`). Return each result to the picked set's executor, not a menu.

**Landed** means `pr.state` is `MERGED`. **Primary** is the parent directory of `git -C <worktree.path> rev-parse --git-common-dir`; it is the checkout the session runs in. Never remove it and never change its branch. Run every git command as `git -C <primary>`; touch nothing under the removed worktree path after step 1.

Run only the picked step: cleanup executes steps 1-3 as one group, each override executes its own step-4 item, and a resolved PR-named action uses step 4's dispatcher. Keep guards in execution as well as row preparation. A failed sub-step prints its first error line and the loop continues; retry nothing. Before a picked PR-named action or `/skill:release` item, require step 3's synced result; run step 3 first when cleanup is not picked. A failed or skipped base pull yields `skipped - base not synced` for the dependent action.

1. **Worktree.** Eligible when `worktree.path` is not the primary, `git -C <worktree.path> status --porcelain --untracked-files=no` is empty (tracked-clean; untracked files never block removal), and - when landed - `git -C <worktree.path> log origin/<baseRefName>..HEAD` shows no commit outside the assessed head's history (`git -C <worktree.path> merge-base --is-ancestor HEAD <headRefOid>` succeeds). When the merge-base `## using-git-worktrees` section has at least one of `- home:`, `- create:`, `- destroy:` (the keyed contract), eligibility also requires the ownership match of `../../finishing-a-development-branch/SKILL.md` Step 6 (the recorded `worktree.destroy` already carries the recovered identifier): `home:` resolved against `$PRIMARY` (absent -> `.worktrees/<name>`), the `<name>` segment matched as `<prefix>*<suffix>` within one segment (`../acme-mono-<name>` against `/work/acme-mono-fix-x` recovers `fix-x`), `$WORKTREE` (the digest `worktree.path`) and the pattern both through `realpath`; an ambiguous match stops; no match -> `worktree: skipped - outside configured home, left at <path>` and the branch step reports it still checked out. Eligible and (`worktree.created` or landed) -> run `worktree.destroy` when recorded (from the primary; a non-zero exit prints `worktree: failed - <its output>`, keeps the branch (the branch step reports it still checked out), and never falls back to a forced removal), else `git worktree remove --force <worktree.path>` (the single `--force` removes a tree whose only dirt is untracked files; those files are deleted); then `git worktree prune`; print `worktree: done`. Reused and not landed -> `worktree: skipped - reused, left at <path>`. Dirty -> `worktree: skipped - uncommitted changes at <path>`. Commits beyond the assessed head -> `worktree: skipped - unmerged commits <shas> at <path>`. Under `approved` on a `rebased locally` head this step reports `unmerged commits` and leaves the tree, and `stop` leaves the rewritten local head in place and names it.
2. **Branch.** A non-zero `worktree.destroy` exit in step 1 -> `branch: skipped - worktree destroy failed`, whatever `git worktree list` shows. Landed, the branch exists locally, and no worktree holds it (`git worktree list --porcelain` lists no `branch refs/heads/<worktree.branch>`) -> `git branch -D <worktree.branch>`; print `branch: done`. Not landed -> `branch: skipped - PR not merged`. Still checked out -> `branch: skipped - checked out at <path>`. Never delete a remote branch.
3. **Base.** Landed, the primary is on `<baseRefName>`, and its tree is tracked-clean -> `git fetch origin` then `git pull --ff-only`; print `base: synced <sha>` when `git merge-base --is-ancestor <pr.merge_commit> HEAD` succeeds, else `base: failed - merge commit not on local <baseRefName>`. Primary on another branch -> `base: skipped - primary on <branch>`; dirty -> `base: skipped - uncommitted changes`; not landed -> `base: skipped - PR not merged`. Never switch the primary's branch.
4. **Override dispatcher**, invoked separately for each picked `## cleanup` item in list order. An item is `<label>: <text>`; any other shape -> `skipped - malformed item: <text>`.
   - Landed-change guard first: not landed and the text contains `<merge-sha>` or `/skill:release` -> `skipped - needs a landed change`. The guard decides before any placeholder is read, so an item it skips never prints a `no <name> resolved` line, whatever its placeholders hold. A `/skill:release` item when step 3 did not print `synced` -> `skipped - base not synced`.
   - Substitute: `<issue>` is `issue.ref` with a leading `#` stripped for the bare `#N` form (other forms verbatim); `<pr>` is `pr.url`; `<merge-sha>` is `pr.merge_commit`. A null `<merge-sha>` -> `skipped - needs a landed change` in both the cleanup row text and the result block. Other null values -> `skipped - no <name> resolved`: `skipped - no issue resolved`, `skipped - no pr resolved`. Any other `<...>` token -> `skipped - malformed item: <text>`. Insert each value as literal argument text: inside an existing quoted span verbatim; outside, single-quoted as one shell word.
   - Text starting with `/skill:` -> invoke that skill with the rest of the text as its arguments, gates intact: the step's line is `<label>: invoked /skill:<name> - <where it paused or what it returned>` (for example `release: invoked /skill:release - paused at its level pick`) - never a `skipped` or `failed` line about skill availability, because the gate itself runs as a skill and every `/skill:` item is invokable; `/skill:release` with no level runs the skill's propose-then-pick gate; a level written in the item (`patch`, `minor`, `major`) authorizes the release without a pause. Any other text -> run it as a non-interactive shell command with cwd the primary, bounded by the resolved `timeout minutes` (default 15) through the Safety contract ladder of `../verification-brief.md` Section B; a timeout prints `failed - timed out after <n> minutes` and later steps still run.

With no `## cleanup` section, offer no overrides. Build each row through `menus.md` `## post` with its resolved command and worktree removal's deletion of untracked files; keep overrides separate.

For [Teardown's closing message](post-selection-loop.md#teardown), include each unpicked, skipped or failed cleanup sub-step's command: recorded `worktree.destroy` or `git -C <primary> worktree remove --force <worktree.path>`, `git -C <primary> branch -D <worktree.branch>`, `git -C <primary> fetch origin` then `git -C <primary> pull --ff-only`, and each `## cleanup` item's resolved command; repeat the executable command literally in each closing sentence, never an alias, reference to earlier text or retained worktree path. List a skipped sub-step even when its group was picked and all other steps ran.

## Non-final stop

Follow the [shared layout](../../brainstorming/reference/menu-layout.md).

Finish the stop consequences below before the final message. Start the message with `gauntlet: stuck` followed on that line by the reason: use the obstacle's `stuck - ` text as the reason, or `stopped at <template id>` for initial, assess-terminal, contract-exception, and reject. For reject use `reject.md`'s settlement table: a failed picked note or close supplies its first failure reason; cleanup alone or stop uses `stopped at reject`. On a failed reset/assertion use the actual error instead. Print the PR row from `post-selection-loop.md` `### Settlement rows` with `stuck - <reason>` below the marker, then cleanup results. In set mode use `batch.md`'s per-PR retirement marker and retain the row for the final roster settlement.

Enter here for `stop` on the initial, assess-terminal, obstacle, contract-exception, or reject menu. When reject's cleanup `post_steps` result records that cleanup already ran, skip all worktree inspection and removal below, print the retained result and path as already handled (already removed when removal succeeded), and proceed directly to teardown. Never handle the same worktree twice. On a `rebased locally` head, run `git -C <worktree.path> reset --hard <pre_head>` first; assert `HEAD == <pre_head>` and a clean tree. Stop on a failed assertion.

Reuse step 1's primary and keyed ownership computation: resolve `home:` and the `<name>` pattern against `$PRIMARY`, and pass both the pattern and `worktree.path` through `realpath`. Keep the primary even when clean; print `worktree: kept - primary at <path>`.

For a path that is not the primary, apply these checks in order; created and reused trees are both eligible:

| Check | On failure |
|---|---|
| `git -C <worktree.path> status --porcelain --untracked-files=no` is empty | Keep: `uncommitted changes` |
| `git -C <worktree.path> merge-base --is-ancestor HEAD <last pushed head>` succeeds; use `repair.wave.pushed_head` when set, else the assessed `headRefOid` | Keep: `unpushed commits <shas>`; list commits from `<last pushed head>..HEAD` |
| Under a keyed `## using-git-worktrees` contract, step 1's ownership match is unique | Keep: `outside configured home` for no match, or `ambiguous home match` for multiple matches |

For a failed check print `worktree: kept - <reason> at <path>` and leave the tree. For `unpushed commits <shas>` also state that discarding those commits is a separate explicit human decision - never a consequence of `stop` - and that the run neither offers nor performs it. Untracked residue alone does not block removal and is deleted. For an eligible tree run recorded `worktree.destroy` from the primary; a failed custom destroy keeps the tree, prints `worktree: failed - <first error line>, left at <path>`, and must never fall back to forced removal. With no recorded destroy command, run `git -C <primary> worktree remove --force <worktree.path>`. After successful destruction run `git -C <primary> worktree prune` and print `worktree: done`. Touch nothing under the removed path.

Never run terminal steps 2-4 here: no branch deletion, base pull, or `## cleanup` overrides. Delegate record, helper-output, and temporary body-file deletion to `post-selection-loop.md` `### Teardown`.
