--- name: cleanup disable-model-invocation: true argument-hint: '[--all | --repo | --root ] [--scope <#N>] [--report-only] [--force]' description: OMP-only — inventory worktrees and remove explicitly selected paths, with an opt-in manual local-data discard mode, while preserving every branch. version: 0.5.0 --- # Worktree Cleanup The operator invokes this standalone skill. It may be offered after land, never entered automatically or from a review/correction loop. ## Contract - Inventory is read-only. Preserve every local and remote branch, including unmerged work. Merge messages and PR labels are not deletion authority. - Removal uses the bundled executor, one explicitly selected path at a time. It re-inspects identity, local data, ignored artifacts, locks and observable process usage. - Principal/current worktrees, inaccessible filesystem state, nested Git repositories, mounts, index-hidden files, initialized submodules or retained `modules/` data in the worktree Git directory, locks, in-progress Git operations and detected active usage are always kept. Nonempty orphan shells are informational only; empty shells use `rmdir`. - Safe mode also keeps tracked changes, genuinely untracked files and unrecognized or sensitive ignored data. Only the explicit manual force mode below can make those local data disposable. - Recognized ignored artifacts make an otherwise removable worktree a conditional candidate. It is never selected automatically, and removal deletes those artifacts with the worktree. - An editable install outside the worktree that imports from it makes removal require a path-bound acknowledgment naming that install, in every mode. Detection only: the skill never reinstalls or modifies that environment. - Branch maintenance, GitHub labels and CI cancellation require separate operator mandates; none belongs to this workflow. No fetch or prune is run. - `--yes` is rejected. CLI confirmation arguments name the selected path; they do not prove human consent. ## Ignored artifacts In safe mode, only entries Git already reports as ignored are classified, from the same status pass that counts local changes, and each keeps the exact path Git reports. Truly untracked (`??`) files and tracked changes keep the worktree. Never add ignore rules, delete files or otherwise alter a worktree to make it eligible; manual force uses the executor directly, not pre-deletion. | Kind | Recognized entries (case-sensitive) | |---|---| | `dependency` | a `node_modules` or `.venv` directory, or an entry Git lists inside one | | `cache` | a `__pycache__`, `.pytest_cache`, `.ruff_cache` or `.cache/trufflehog` directory, or an entry Git lists inside one; a regular `*.tsbuildinfo` file | | `build-output` | a `.astro`, `dist` or `test-results` directory that Git itself reports as ignored | | `protected` | every other ignored entry: a file Git lists individually inside a build-output directory it does not ignore as a whole, any `.git` path, a file or symlink bearing a directory name, and exposed names matching a partial sensitive-name list (for example `.env*`, private keys, credential files, database dumps) | The sensitive-name list is defense in depth, not a complete detector. When Git reports a recognized directory as one entry, it is a **whole subtree** whose children Git does not list. Its file contents are never read, so manual dependency patches, secrets, local state, exports or a non-Git checkout inside it are deleted with it and nothing vouches for their absence. Names do not prove that content can be regenerated, so build/test output needs a human content decision. Before a row with recognized artifacts becomes removable, a metadata-only walk checks every recognized entry: names and no-follow file types, never file contents, `HEAD` or Git configuration, never following a symlink. On Linux the row is kept on a mount point at or below the worktree, a nested `.git` of any type, a directory holding `HEAD` next to Git directory names (possible bare repository), a special file, a symlink or replaced directory where Git saw a directory or regular file, or any observation error. It detects Git metadata only, not other version control or unique data. Other platforms keep artifact rows. The walk is one non-atomic pass: stop writers and mount changes before selection. In safe mode, any `protected` entry or walk finding keeps the worktree, and the allowlist has no repository override. The safe token binds every reported path and kind, so an entry that appears or vanishes stales the selection; changes inside a reported directory do not. ## Editable installs `uv tool install -e` and `pipx install -e` leave a venv outside the worktree that imports from it. Removing the worktree does not stop a process that already loaded the code, but every new invocation fails with `ModuleNotFoundError`, and a supervised service restarts in a loop. Each inventory reads, once per directory (device and inode), the `lib/*/site-packages/` and `lib64/*/site-packages/` of every venv in the uv tool directories (`$UV_TOOL_DIR`, `$XDG_DATA_HOME/uv/tools`, `~/.local/share/uv/tools`), in the `venvs/` of the pipx homes (`$PIPX_HOME`, `~/.local/pipx`, `$XDG_DATA_HOME/pipx`, `~/.local/share/pipx`, and macOS's `~/Library/Application Support/pipx`) and in `${PIPX_GLOBAL_HOME:-/opt/pipx}/venvs` (`pipx install --global`). The default stores stay read beside an exported override, since tools installed before it still run from them. Like the tools, it expands `~` and `~user` in the pipx variables only and resolves `..` after any symlink before it; a store reached by several spellings is read once. A venv is a directory whose name does not start with a dot and that holds `pyvenv.cfg` or `bin/pyvenv.cfg`. It takes every path line some CPython release loads from a `*.pth` file, dot-prefixed files included, split both as 3.13+ and as older releases split lines (those keep a leading BOM), and kept only when the path exists (a path too long for the kernel cannot); a relative line is joined to `site-packages` as every spelling of the venv path names it and physically. It also takes the `url` of every PEP 610 `*.dist-info/direct_url.json` marked `"dir_info": {"editable": true}`. An install depends on a row when the walk to its recorded path passes through a directory entry inside the row, before or after each symlink, and its venv lies physically outside the row; `/wt/ab` is outside `/wt/a`. Rows no install targets are unchanged. The row lists each dependent in `editableInstalls` (`manager`, venv `name`, `source` file, recorded `target`) and sets `requiresEditableInstallConfirmation`; the human inventory prints an `Editable install importing from this worktree` line per dependent under the row. Eligibility is unchanged, but removal requires `--ack-editable-installs ""` in safe and force mode and for orphan shells, and the executor names the dependents it leaves broken. The token binds the dependents, so one that appears or vanishes stales the selection, and the executor scans again just before Git removes the worktree: a dependent that changed during its inspection refuses the removal. Cleanup takes neither uv's tool-store lock nor pipx's per-venv lock, so stop `uv tool` and pipx installs while cleanup runs; one written while Git removes the worktree is not seen. A tool root, venv or `site-packages` directory that cannot be read, whoever owns it, an entry name in one of them that is not UTF-8 (named with its bytes in hex), a `pyvenv.cfg` that cannot be checked, a pipx home variable whose `~user` has no home, a `.pth` that cannot be opened or is a FIFO or device or is not UTF-8 (a missing one, or a directory, is skipped as Python skips it), a `.pth` path line whose existence cannot be checked, a symlink loop, a recorded path through a directory this user cannot search (it may hide a link into a worktree), or a `direct_url.json` that is dangling, unreadable, not a regular UTF-8 file, not a PEP 610 record (a `url` string and exactly one origin object), or editable without an absolute file URL is reported as an `editable-installs` error naming the path and keeps every row (`editable-install inspection incomplete`) in every repository until it is repaired: no row can be cleared without a complete scan. A record that does not parse is reported without the parser's message, which can quote its contents. The human dependent lines, their acknowledgment line and error messages escape control, line-separator and bidirectional characters; JSON keeps the raw values. The skill never reinstalls, rewrites or removes anything in those venvs. Known limits: - An editable install that left no `direct_url.json` (`UV_NO_INSTALLER_METADATA`, also through pipx's uv backend) is detected only through a `.pth` path line: one whose build backend installs it through an import hook alone is not detected. uv's `uv-receipt.toml` and pipx's `pipx_metadata.json` are not read. A relative `.pth` line is joined to the venv's physical path and to the store spellings configured when cleanup runs: an install made through a store alias (`UV_TOOL_DIR` pointing to a symlink) that is no longer exported is not matched through that alias. - An install written between the final rescan and Git's removal of the worktree is not seen: cleanup takes neither uv's tool-store lock nor pipx's per-venv lock. - `.pth` lines are split both as CPython 3.13+ and as older releases split them, whatever the venv's version: a line one release reads as part of a comment can count as a path: it asks for an acknowledgment Python does not need, or, when that path cannot be checked (a directory this user cannot search), keeps every row. - An install recorded by both a `.pth` path line and `direct_url.json` is listed once per record, and a relative `.pth` line in a venv whose `lib64` links to `lib` is listed once per spelling of its target. - A `.pth` target reached through a symlink whose payload is not UTF-8, and a store or venv whose physical path is not UTF-8, are decoded lossily: such an install can be missed. - `lib/` and `lib64/` site-packages that share a device and inode are read once, through `lib/`: a bind mount of one onto the other with a file overlaid in one view only (`lib64/`) hides what only that view holds. - Other dependents are not seen: project `.venv`s, `pip install --user`, system or conda site-packages, `PYTHONPATH`, and the venvs of a self-managed pipx that recovers an unexported custom home from its own venv (export `PIPX_HOME`). - An exported `PIPX_GLOBAL_HOME` replaces `/opt/pipx`, as it does for pipx. - `.pth` files are read as UTF-8 only. One that is not valid UTF-8 keeps every row until it is rewritten in UTF-8; the error names the file. One written under a non-UTF-8 locale whose bytes also form valid UTF-8 (Latin-1 `C3 A9`, for example) is read as UTF-8, unlike a Python before 3.13 under that locale: its path lines can be misread and such an install can be missed. - macOS support stops at pipx's default home: uv's legacy macOS data store and a recorded path spelled in another case on case-insensitive APFS are not matched (set `UV_TOOL_DIR`, and install from the worktree path as Git spells it). - A store reached through both a uv and a pipx variable is read once and its dependents are labeled with the first manager. - Executable `.pth` hooks and generated finder modules are neither run nor parsed, and standalone `*.egg-link` files are not read: an install recorded only there is not seen. Neither are the temporary venvs of `pipx run` and `uv tool run --with-editable` under the caches. - A store this user cannot list, or a venv it cannot search or whose `lib`, `lib64` or `site-packages` it cannot list, blocks cleanup, whoever owns it: for example the `/opt/pipx` a root `pipx install --global` creates under umask 077. For the global store, run cleanup with `PIPX_GLOBAL_HOME` pointing to an empty or nonexistent directory; that store is then not checked. A user store is read even beside an override, so repair its permissions instead. ## Manual force mode Enter this mode only when the operator explicitly asks to abandon local data. `inventory --force` is read-only: it assesses registered or detached worktrees under that mode and does not select or remove anything. Safe and force tokens are not interchangeable. Force does not make orphan shells removable. Force may discard tracked/staged edits, genuinely untracked files and all ignored data, including sensitive or unrecognized entries such as `.semctx`, `.cocoindex_code` or `.deps`. A Git ignore rule is not proof of disposability. Present the exact `localEntries` (status, path and any original rename path), the exact `ignoredEntries`, and the warning that all their contents are lost. The human must select the exact paths and explicitly approve abandoning all these local data. Creating or improving this mode is not that approval. Before a force candidate becomes eligible, a Linux metadata-only, no-follow walk covers the entire worktree, not just recognized ignored artifacts. It keeps nested Git repositories, probable bare repositories, mounts, special files, replaced paths and observation errors. All other hard guards from the contract remain blocking; an unretained detached HEAD needs a separate branch maintenance decision, not a force override. The force guard also checks the linked worktree's administrative `modules/` entry, even when no submodule gitlink or checkout remains. Any such entry or observation error keeps the worktree; its retained repositories are not local files covered by discard approval. Force tokens additionally bind the exact Git status, index state and a deterministic metadata fingerprint of the worktree, including changes inside ignored directories. File payloads are not read. A changed target, mode, status, index or observed file state requires a fresh inventory and selection; changed data to abandon requires renewed human approval. This is not an atomic lock or a content-integrity proof: stop writers and mount changes before selection. Git status disables fsmonitor and untracked-cache shortcuts for a fresh data list. Force also rechecks observable process usage after the tree walk and before mutation. Active usage still blocks; unknown usage still requires its separate confirmation. For each selected force row requiring `requiresDiscardConfirmation`, the executor also requires `--ack-discard-local-data ""`. This path-bound acknowledgement covers both ignored and nonignored data; do not also pass `--ack-ignored-artifacts` in force mode. Incomplete usage observations still require their separate human reply and `--ack-unknown-usage`. ## 1. Inventory Resolve the entry and invoke the read-only command: ```bash T=$(realpath skill://cleanup/worktrees.ts) && bun --no-env-file "$T" inventory --json ``` Forward requested options as separate, quoted arguments, never evaluated shell text. Do not forward a removal command supplied through `$ARGUMENTS`. | Option | Scope | |---|---| | none / `--report-only` | Current repository; no mutations | | `--repo ` | Explicit repository; repeat for multiple repositories | | `--root ` | Discover repositories recursively below this root; repeat for multiple roots | | `--all` | Discover below the current directory, rather than only the current repository | | `--scope <#N>` | Exact issue-number boundary on branches; excludes unattributed orphan shells | | `--force` | Read-only manual-discard assessment; all structural and active-usage guards remain blocking | Discovery includes nested repositories and archives, does not follow symlinks, and deduplicates linked worktrees by canonical Git common directory. The CLI reports its discovery exclusions and errors. A partial inventory is not evidence that no worktrees exist. Present repository, exact path, branch or detached HEAD, local-change state, ignored entries grouped by kind with their exact paths (`ignoredEntries`), editable installs importing from the worktree (`editableInstalls`), process-usage evidence, eligibility, warnings and preservation reasons. Include `removalMode`, `localEntries` and `requiresDiscardConfirmation` in manual mode. Include retained and unknown rows, not only removable candidates. A detached HEAD needs a retaining local branch or tag before its worktree can be removed. Tokens stay internal; do not display them or ask the human to copy them. The orphan scanner complements Git's registered-worktree list. It checks the configured feature root, `~/.omp/worktrees/` and the principal's `.claude/worktrees`. Nonempty shells need investigation or repair, not deletion. On inventory errors, show the failed observation and keep affected candidates. `--report-only` stops here, even if a previous message discussed removal. ## 2. Obtain explicit selection Offer eligible rows in short numbered batches of ordinary text, each number mapped to the exact path displayed beside it, with **nothing preselected**, and offer "Keep everything". Do not build large forms. Show retained and unknown rows separately as non-selectable. State the exact effect: remove this worktree directory, preserve all of this repository's branch/tag refs and their reachable commits; or remove this proven-empty shell. Removing a registered worktree also removes its own reflogs. Do not promise preservation of reflog-only commits. For a row with `requiresArtifactConfirmation`, list its exact ignored entries by kind and warn that their entire contents are deleted unread, including any manual dependency patch, secret, state, export, build/test evidence or non-Git checkout inside them. For a row with `requiresEditableInstallConfirmation`, name each dependent install and warn that removal leaves it unable to import until it is reinstalled from another checkout; the skill does not reinstall it. Wait for a genuine human reply identifying the rows. For artifact rows, that same reply must also state that the entire listed artifacts of those exact rows are disposable, for example: "rows 2 and 5; all their listed artifacts are disposable, no dependency patches, checkouts, build evidence or other unique data to keep". A row whose artifacts are not explicitly confirmed is kept. A row with editable installs needs the same reply to accept that each named install breaks, for example "row 3; uv tool demo may break"; otherwise it is kept. An earlier request to improve this skill, a broad cleanup request, an inventory request, a token or a CLI flag is neither consent to remove anything nor artifact or breakage approval. A noneligible row cannot be overridden. Manual force requires its own fresh force inventory and the additional local-data approval described above, not reuse of a safe row. Process observations are a safety signal, not proof that every agent session is idle. Detected active usage always blocks. If observations are incomplete or unsupported, show that warning and the available evidence, and obtain an additional, separate explicit reply confirming that this exact worktree is no longer used despite the incomplete observation. Without that reply, keep the path. Stop writers before selection; observations are not an atomic filesystem lock. ## 3. Execute the selected rows For each confirmed row, use its repository, exact path and inventory token: ```bash bun --no-env-file "$T" remove \ --repo "" --path "" \ --expect "" --confirm "" --json ``` For a row requiring the additional usage confirmation, append `--ack-unknown-usage ""` only after that separate exact confirmation. For a row requiring artifact confirmation, append `--ack-ignored-artifacts ""` only after the human confirmed that row's artifacts are disposable. For a row requiring editable-install confirmation, in either mode, append `--ack-editable-installs ""` only after the human accepted that its named installs break. These flags are path-bound selection data, not proof of human consent; the executor rejects each one when fresh inspection does not require it. For a manually selected force row, use the token from `inventory --force`: ```bash bun --no-env-file "$T" remove --force \ --repo "" --path "" \ --expect "" --confirm "" \ --ack-discard-local-data "" --json ``` Only include `--ack-discard-local-data` when fresh inspection requires it; the executor rejects a missing, mismatched or unnecessary acknowledgement. Include the usage acknowledgement separately when required. No CLI flag proves that the human actually approved the loss. Each placeholder is one quoted argument. The executor re-inspects the candidate and refuses stale tokens, path replacement, structural findings, Git operations and active usage. Safe mode also refuses non-allowlisted local data. Before force or artifact removal it rereads the mount table. Uncertain filesystem state cannot be overridden. Safe registered worktrees use ordinary `git worktree remove`; explicitly confirmed force rows use exactly one `--force` on that same command. Both remove the directory's contents and preserve branch/tag refs. Empty orphan shells use `rmdir` only. No raw Git/shell fallback, pre-deletion, second `--force` or automatic escalation after a refusal. Re-inventory changed candidates and obtain a new selection instead. ## 4. Report Report actual removals with the mode and local data discarded alongside, every editable install the executor reports as unable to import, refusals and retained paths; explicitly say branches, labels and CI were untouched. A failed command is not a successful removal, nor proof that the path is untouched: Git removal is not atomic and may leave a partially removed directory. Report the observed error and current state; never escalate or retry with additional force or raw deletion. No installation refresh or subsequent maintenance operation is implied. $ARGUMENTS