@caddis/cli 0.4.93 → 0.4.94
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundles/antigravity-plugin/guard_agy.py +6 -2
- package/bundles/antigravity-plugin/plugin.json +1 -1
- package/bundles/antigravity-plugin/repo_freshness.py +71 -6
- package/bundles/antigravity-plugin/repo_hygiene.py +516 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/caddis_finished.py +537 -0
- package/bundles/antigravity-plugin/scripts/caddis_guide.json +9 -8
- package/bundles/antigravity-plugin/scripts/caddis_own_cleanup.py +23 -248
- package/bundles/antigravity-plugin/scripts/caddis_repo_tidy.py +240 -0
- package/bundles/antigravity-plugin/scripts/caddis_tidy.py +12 -0
- package/bundles/antigravity-plugin/scripts/caddis_worktree_root.py +111 -2
- package/bundles/antigravity-plugin/scripts/setup_project_ai.py +67 -10
- package/bundles/antigravity-plugin/skills/_registry.md +4 -4
- package/bundles/antigravity-plugin/skills/adopt-app/SKILL.md +2 -5
- package/bundles/antigravity-plugin/skills/cloud-phases/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/dashboard-perf-sweep/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/db-diagram/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/explainer-doc/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/implement/SKILL.md +4 -0
- package/bundles/antigravity-plugin/skills/port-to-github/SKILL.md +2 -5
- package/bundles/antigravity-plugin/skills/pr-merge/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/ship-merge/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/ship-pr/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/tech-explainer/SKILL.md +2 -6
- package/bundles/antigravity-plugin/skills/using-git-worktrees/SKILL.md +19 -2
- package/bundles/antigravity-plugin/skills/warm-editorial-ui/SKILL.md +1 -1
- package/bundles/antigravity-plugin-extras/plugin.json +1 -1
- package/bundles/antigravity-plugin-extras/skills/_registry.md +2 -2
- package/bundles/antigravity-plugin-extras/skills/building-ai-agent-on-cloudflare/SKILL.md +1 -2
- package/bundles/antigravity-plugin-extras/skills/building-mcp-server-on-cloudflare/SKILL.md +1 -2
- package/bundles/antigravity-plugin-extras/skills/data-contract-pipeline/SKILL.md +1 -1
- package/bundles/antigravity-plugin-extras/skills/responsive-mobile-native/SKILL.md +2 -4
- package/bundles/antigravity-plugin-extras/skills/runner-move/SKILL.md +2 -4
- package/bundles/antigravity-plugin-extras/skills/setup-project-ai/SKILL.md +1 -1
- package/bundles/antigravity-plugin-extras/skills/understand-anything/SKILL.md +2 -5
- package/bundles/codex/.codex/skills/coding/dashboard-perf-sweep/SKILL.md +1 -1
- package/bundles/codex/.codex/skills/data/db-diagram/SKILL.md +1 -1
- package/bundles/codex/.codex/skills/devops/adopt-app/SKILL.md +2 -5
- package/bundles/codex/.codex/skills/devops/port-to-github/SKILL.md +2 -5
- package/bundles/codex/.codex/skills/devops/using-git-worktrees/SKILL.md +19 -2
- package/bundles/codex/.codex/skills/docs/explainer-doc/SKILL.md +1 -1
- package/bundles/codex/.codex/skills/docs/tech-explainer/SKILL.md +2 -6
- package/bundles/codex/.codex/skills/frontend/warm-editorial-ui/SKILL.md +1 -1
- package/bundles/manifest.json +3 -3
- package/package.json +1 -1
|
@@ -31,269 +31,44 @@ from __future__ import annotations
|
|
|
31
31
|
|
|
32
32
|
import json
|
|
33
33
|
import os
|
|
34
|
-
import re
|
|
35
|
-
import subprocess
|
|
36
34
|
import sys
|
|
37
35
|
from collections.abc import Callable
|
|
38
36
|
from pathlib import Path
|
|
39
37
|
|
|
40
38
|
import caddis_created
|
|
39
|
+
import caddis_finished
|
|
41
40
|
import caddis_worktree_safety as safety
|
|
42
41
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
return subprocess.CompletedProcess(cmd, -1, "", f"{cmd[0]} is not installed")
|
|
65
|
-
except subprocess.TimeoutExpired:
|
|
66
|
-
return subprocess.CompletedProcess(cmd, -1, "", f"{cmd[0]} timed out after {timeout} s")
|
|
67
|
-
except OSError as exc:
|
|
68
|
-
return subprocess.CompletedProcess(cmd, -1, "", str(exc))
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
def _git(path: Path, *args: str, timeout: int = GIT_TIMEOUT) -> subprocess.CompletedProcess:
|
|
72
|
-
return _run(["git", "-c", "core.quotepath=off", "-C", str(path), *args], timeout=timeout)
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
def _err(proc: subprocess.CompletedProcess) -> str:
|
|
76
|
-
text = (proc.stderr or proc.stdout or "").strip()
|
|
77
|
-
return text.splitlines()[-1] if text else f"exit {proc.returncode}"
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
def _same(a: str | Path, b: str | Path) -> bool:
|
|
81
|
-
return os.path.normcase(os.path.realpath(a)) == os.path.normcase(os.path.realpath(b))
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
def _inside(child: str | Path, parent: str | Path) -> bool:
|
|
85
|
-
"""`child` is `parent` or under it (both resolved, case-folded on Windows)."""
|
|
86
|
-
c = os.path.normcase(os.path.realpath(child))
|
|
87
|
-
p = os.path.normcase(os.path.realpath(parent))
|
|
88
|
-
return c == p or c.startswith(p.rstrip("\\/") + os.sep)
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
# -- gh ---------------------------------------------------------------------------------------------------------
|
|
92
|
-
|
|
93
|
-
def _slug(main_repo: Path) -> str | None:
|
|
94
|
-
"""`owner/name` from the origin URL (https, ssh or scp form), else None."""
|
|
95
|
-
proc = _git(main_repo, "remote", "get-url", "origin")
|
|
96
|
-
url = proc.stdout.strip() if proc.returncode == 0 else ""
|
|
97
|
-
if "://" not in url and "@" not in url:
|
|
98
|
-
return None # a local path origin has no GitHub name
|
|
99
|
-
match = re.search(r"[:/]([^/:]+)/([^/]+?)(?:\.git)?/?$", url)
|
|
100
|
-
return f"{match.group(1)}/{match.group(2)}" if match else None
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
def gh_pr_lookup(main_repo: Path, branch: str | None, pr: str | None) -> list[dict]:
|
|
104
|
-
slug = _slug(main_repo)
|
|
105
|
-
if not slug:
|
|
106
|
-
raise PrLookupError("cannot read owner/name from the origin URL")
|
|
107
|
-
if pr:
|
|
108
|
-
proc = _run(["gh", "pr", "view", pr, "--repo", slug, "--json", _GH_FIELDS], timeout=NET_TIMEOUT)
|
|
109
|
-
elif branch:
|
|
110
|
-
proc = _run(["gh", "pr", "list", "--repo", slug, "--head", branch, "--state", "all", "--limit", "20",
|
|
111
|
-
"--json", _GH_FIELDS], timeout=NET_TIMEOUT)
|
|
112
|
-
else:
|
|
113
|
-
return []
|
|
114
|
-
if proc.returncode != 0:
|
|
115
|
-
raise PrLookupError(f"gh failed: {_err(proc)}")
|
|
116
|
-
try:
|
|
117
|
-
data = json.loads(proc.stdout or "null")
|
|
118
|
-
except ValueError as exc:
|
|
119
|
-
raise PrLookupError(f"gh printed bad JSON: {exc}") from exc
|
|
120
|
-
data = [data] if isinstance(data, dict) else data
|
|
121
|
-
if not isinstance(data, list):
|
|
122
|
-
raise PrLookupError("gh printed an unexpected shape")
|
|
123
|
-
return [d for d in data if isinstance(d, dict)]
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
def _pr_number(value: str | None) -> str | None:
|
|
127
|
-
match = re.search(r"(\d+)\s*$", str(value or ""))
|
|
128
|
-
return match.group(1) if match else None
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
def _pick_pr(prs: list[dict], branch: str | None, by_number: bool) -> tuple[dict | None, str]:
|
|
132
|
-
"""(the merged PR, "") or (None, why the worktree is kept)."""
|
|
133
|
-
if not prs:
|
|
134
|
-
return None, f"no merged PR found: no PR for branch {branch}" if branch else "no merged PR found: no PR"
|
|
135
|
-
open_pr = next((p for p in prs if str(p.get("state", "")).upper() == "OPEN"), None)
|
|
136
|
-
pick = open_pr or prs[0]
|
|
137
|
-
state = str(pick.get("state", "")).upper() or "UNKNOWN"
|
|
138
|
-
if state != "MERGED":
|
|
139
|
-
return None, f"PR #{pick.get('number')} is {state}"
|
|
140
|
-
head_name = pick.get("headRefName")
|
|
141
|
-
if by_number and branch and head_name and head_name != branch:
|
|
142
|
-
return None, f"PR #{pick.get('number')} is for branch {head_name}, not {branch}"
|
|
143
|
-
return pick, ""
|
|
42
|
+
# The worktree proof, the gh seam and the removal live in caddis_finished (one definition of "finished", shared with
|
|
43
|
+
# `caddis_tidy.py --hygiene`). The old private names stay here as aliases: the tests and the scratch code use them.
|
|
44
|
+
GIT_TIMEOUT = caddis_finished.GIT_TIMEOUT
|
|
45
|
+
NET_TIMEOUT = caddis_finished.NET_TIMEOUT
|
|
46
|
+
PrLookupError = caddis_finished.PrLookupError
|
|
47
|
+
gh_pr_lookup = caddis_finished.gh_pr_lookup
|
|
48
|
+
_env = caddis_finished._env
|
|
49
|
+
_run = caddis_finished._run
|
|
50
|
+
_git = caddis_finished._git
|
|
51
|
+
_err = caddis_finished._err
|
|
52
|
+
_same = caddis_finished._same
|
|
53
|
+
_inside = caddis_finished._inside
|
|
54
|
+
_slug = caddis_finished.repo_slug
|
|
55
|
+
_pr_number = caddis_finished.pr_number
|
|
56
|
+
_pick_pr = caddis_finished.pick_pr
|
|
57
|
+
_main_repo = caddis_finished.main_repo
|
|
58
|
+
_default_branch = caddis_finished.default_branch
|
|
59
|
+
_ref = caddis_finished.ref
|
|
60
|
+
_names = caddis_finished.changed_names
|
|
61
|
+
_branch_tip = caddis_finished.branch_tip
|
|
62
|
+
_remove_worktree = caddis_finished.remove_finished
|
|
144
63
|
|
|
145
64
|
|
|
146
65
|
# -- worktree ---------------------------------------------------------------------------------------------------
|
|
147
66
|
|
|
148
|
-
def _main_repo(entry: dict, path: Path) -> Path | None:
|
|
149
|
-
"""The repo to list worktrees from: the entry's `repo` when it is a git checkout, else from the path's common dir."""
|
|
150
|
-
for start in (entry.get("repo"), str(path)):
|
|
151
|
-
if not start or not os.path.isdir(start):
|
|
152
|
-
continue
|
|
153
|
-
proc = _git(Path(start), "rev-parse", "--path-format=absolute", "--git-common-dir")
|
|
154
|
-
if proc.returncode == 0 and proc.stdout.strip():
|
|
155
|
-
common = Path(proc.stdout.strip())
|
|
156
|
-
return common.parent if common.name == ".git" else Path(start)
|
|
157
|
-
return None
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
def _default_branch(wt: Path) -> str:
|
|
161
|
-
proc = _git(wt, "symbolic-ref", "--short", "-q", "refs/remotes/origin/HEAD")
|
|
162
|
-
name = proc.stdout.strip() if proc.returncode == 0 else ""
|
|
163
|
-
return name.split("/", 1)[1] if name.startswith("origin/") else "main"
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
def _ref(wt: Path, rev: str) -> str | None:
|
|
167
|
-
proc = _git(wt, "rev-parse", "-q", "--verify", f"{rev}^{{commit}}")
|
|
168
|
-
return proc.stdout.strip() if proc.returncode == 0 and proc.stdout.strip() else None
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
def _names(wt: Path, a: str, b: str) -> set[str] | None:
|
|
172
|
-
proc = _git(wt, "diff", "--name-only", "-z", "--no-renames", "--no-ext-diff", a, b)
|
|
173
|
-
return None if proc.returncode != 0 else {n for n in proc.stdout.split("\0") if n}
|
|
174
|
-
|
|
175
|
-
|
|
176
67
|
def _check_worktree(entry: dict, path: Path, cwd: str, pr_lookup: Callable) -> tuple[str, str, dict]:
|
|
177
68
|
"""("REMOVE", reason, facts) or ("KEPT"/"GONE", reason, {})."""
|
|
178
69
|
if entry.get("by") == "roadmap-run":
|
|
179
70
|
return "KEPT", "owned by the roadmap runner", {}
|
|
180
|
-
|
|
181
|
-
return "GONE", "", {}
|
|
182
|
-
try:
|
|
183
|
-
if safety.is_link(os.lstat(path)):
|
|
184
|
-
return "KEPT", "the folder is a junction or symlink", {}
|
|
185
|
-
except OSError as exc:
|
|
186
|
-
return "KEPT", f"cannot inspect it: {exc}", {}
|
|
187
|
-
repo = _main_repo(entry, path)
|
|
188
|
-
if repo is None:
|
|
189
|
-
return "KEPT", "not a registered linked worktree (no git repo found)", {}
|
|
190
|
-
listing = _git(repo, "worktree", "list", "--porcelain")
|
|
191
|
-
if listing.returncode != 0:
|
|
192
|
-
return "KEPT", f"git worktree list failed: {_err(listing)}", {}
|
|
193
|
-
blocks = safety._worktree_blocks(listing.stdout)
|
|
194
|
-
if not blocks:
|
|
195
|
-
return "KEPT", "git listed no worktrees", {}
|
|
196
|
-
main = Path(blocks[0][0][len("worktree "):])
|
|
197
|
-
if _same(path, main):
|
|
198
|
-
return "KEPT", "it is the main checkout", {}
|
|
199
|
-
block = next((b for b in blocks[1:] if _same(path, b[0][len("worktree "):])), None)
|
|
200
|
-
if block is None:
|
|
201
|
-
return "KEPT", f"not a registered linked worktree of {main}", {}
|
|
202
|
-
if _inside(cwd, path):
|
|
203
|
-
return "KEPT", "this session is working in it", {}
|
|
204
|
-
status = _git(path, "status", "--porcelain", "--untracked-files=normal")
|
|
205
|
-
if status.returncode != 0:
|
|
206
|
-
return "KEPT", f"git status failed: {_err(status)}", {}
|
|
207
|
-
if status.stdout.strip():
|
|
208
|
-
return "KEPT", "uncommitted changes", {}
|
|
209
|
-
if any(line == "locked" or line.startswith("locked ") for line in block):
|
|
210
|
-
return "KEPT", "it is locked", {}
|
|
211
|
-
sym = _git(path, "symbolic-ref", "--short", "-q", "HEAD")
|
|
212
|
-
branch = sym.stdout.strip() if sym.returncode == 0 and sym.stdout.strip() else (entry.get("branch") or None)
|
|
213
|
-
default = _default_branch(path)
|
|
214
|
-
if branch and branch == default:
|
|
215
|
-
return "KEPT", f"it is on the default branch {default}", {}
|
|
216
|
-
pr = _pr_number(entry.get("pr"))
|
|
217
|
-
if not branch and not pr:
|
|
218
|
-
return "KEPT", "no merged PR found: no branch and no PR in the record", {}
|
|
219
|
-
try:
|
|
220
|
-
prs = pr_lookup(main, branch, pr)
|
|
221
|
-
except PrLookupError as exc:
|
|
222
|
-
return "KEPT", f"no merged PR found: {exc}", {}
|
|
223
|
-
except Exception as exc: # noqa: BLE001 - any lookup failure keeps the worktree
|
|
224
|
-
return "KEPT", f"no merged PR found: lookup failed: {exc}", {}
|
|
225
|
-
merged, why = _pick_pr(prs, branch, by_number=bool(pr))
|
|
226
|
-
if merged is None:
|
|
227
|
-
return "KEPT", why, {}
|
|
228
|
-
number = str(merged.get("number") or pr or "?")
|
|
229
|
-
head = _ref(path, "HEAD")
|
|
230
|
-
if not head:
|
|
231
|
-
return "KEPT", "cannot read HEAD", {}
|
|
232
|
-
pr_head = str(merged.get("headRefOid") or "").strip().lower()
|
|
233
|
-
if not pr_head or not _ref(path, pr_head): # a reused branch name: without the PR head, nothing proves HEAD landed
|
|
234
|
-
return "KEPT", f"PR #{number} head commit is not in the local repo", {}
|
|
235
|
-
after = _git(path, "rev-list", "--max-count=1", f"{pr_head}..HEAD")
|
|
236
|
-
if after.returncode != 0:
|
|
237
|
-
return "KEPT", f"git rev-list failed: {_err(after)}", {}
|
|
238
|
-
if after.stdout.strip():
|
|
239
|
-
return "KEPT", f"commits after the merged PR #{number}", {}
|
|
240
|
-
fetch = _git(path, "fetch", "--quiet", "--no-tags", "origin",
|
|
241
|
-
f"+refs/heads/{default}:refs/remotes/origin/{default}", timeout=NET_TIMEOUT)
|
|
242
|
-
if fetch.returncode != 0:
|
|
243
|
-
return "KEPT", f"cannot fetch origin/{default}: {_err(fetch)}", {}
|
|
244
|
-
target = f"refs/remotes/origin/{default}"
|
|
245
|
-
base = _git(path, "merge-base", target, "HEAD")
|
|
246
|
-
if base.returncode != 0 or not base.stdout.strip():
|
|
247
|
-
return "KEPT", f"no merge base with origin/{default}", {}
|
|
248
|
-
changed = _names(path, base.stdout.strip(), "HEAD")
|
|
249
|
-
differ_all = _names(path, target, "HEAD")
|
|
250
|
-
if changed is None or differ_all is None:
|
|
251
|
-
return "KEPT", f"git diff against origin/{default} failed", {}
|
|
252
|
-
differ = sorted(changed & differ_all)
|
|
253
|
-
if differ:
|
|
254
|
-
return "KEPT", f"{len(differ)} file(s) differ from origin/{default}: {', '.join(differ[:3])}", {}
|
|
255
|
-
facts = {"repo": main, "branch": branch, "pr": number, "pr_head": pr_head, "head": head}
|
|
256
|
-
return "REMOVE", f"PR #{number} merged, clean, tree equals origin/{default}", facts
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
def _branch_tip(repo: Path, branch: str) -> str | None:
|
|
260
|
-
proc = _git(repo, "rev-parse", "-q", "--verify", f"refs/heads/{branch}")
|
|
261
|
-
return proc.stdout.strip() if proc.returncode == 0 and proc.stdout.strip() else None
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
def _remove_worktree(path: Path, facts: dict) -> tuple[str, str]:
|
|
265
|
-
repo, branch, head, pr_head = facts["repo"], facts["branch"], facts["head"], facts["pr_head"]
|
|
266
|
-
local_tip = _branch_tip(repo, branch) if branch else None
|
|
267
|
-
problem = safety.safe_remove_worktree(repo, path, force=False, env=_env())
|
|
268
|
-
if problem:
|
|
269
|
-
return "FAILED", problem
|
|
270
|
-
notes: list[str] = []
|
|
271
|
-
if branch and local_tip:
|
|
272
|
-
listing = _git(repo, "worktree", "list", "--porcelain")
|
|
273
|
-
if listing.returncode != 0 or f"branch refs/heads/{branch}" in listing.stdout.splitlines():
|
|
274
|
-
notes.append("local branch kept: another worktree has it checked out")
|
|
275
|
-
elif local_tip not in {head, pr_head}:
|
|
276
|
-
notes.append("local branch kept: its tip is not the removed HEAD or the PR head")
|
|
277
|
-
else:
|
|
278
|
-
gone = _git(repo, "branch", "-D", "--", branch)
|
|
279
|
-
notes.append("local branch deleted" if gone.returncode == 0 else f"local branch kept: {_err(gone)}")
|
|
280
|
-
if branch:
|
|
281
|
-
ls = _git(repo, "ls-remote", "--heads", "origin", f"refs/heads/{branch}", timeout=NET_TIMEOUT)
|
|
282
|
-
tips = [ln.split()[0] for ln in ls.stdout.splitlines() if ln.strip()] if ls.returncode == 0 else []
|
|
283
|
-
if ls.returncode != 0:
|
|
284
|
-
notes.append(f"remote branch kept: ls-remote failed: {_err(ls)}")
|
|
285
|
-
elif tips:
|
|
286
|
-
tip = tips[0].lower()
|
|
287
|
-
if tip in {pr_head, head.lower()} - {""}: # only a tip this check proved landed
|
|
288
|
-
try:
|
|
289
|
-
push = _git(repo, *safety.remote_delete_args(branch, tip), timeout=NET_TIMEOUT)
|
|
290
|
-
notes.append("remote branch deleted" if push.returncode == 0
|
|
291
|
-
else f"remote branch kept: {_err(push)}")
|
|
292
|
-
except ValueError as exc:
|
|
293
|
-
notes.append(f"remote branch kept: {exc}")
|
|
294
|
-
else:
|
|
295
|
-
notes.append("remote branch kept: its tip moved past the PR head")
|
|
296
|
-
return "REMOVED", "; ".join(notes)
|
|
71
|
+
return caddis_finished.prove_worktree_finished(entry, path, cwd, pr_lookup)
|
|
297
72
|
|
|
298
73
|
|
|
299
74
|
# -- scratch ----------------------------------------------------------------------------------------------------
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""caddis_tidy.py --hygiene: list every worktree and local branch of one repo, and remove only what is proved finished.
|
|
3
|
+
|
|
4
|
+
Dry run is the default; only `apply=True` acts. Every row gets one action and a reason:
|
|
5
|
+
|
|
6
|
+
REMOVE proved finished (dry run) REMOVED removed (--apply)
|
|
7
|
+
KEPT a guard holds it, the reason says which TRIAGE no PR or a CLOSED unmerged PR: listed, never removed
|
|
8
|
+
GONE the folder vanished before removal FAILED removal was tried and did not complete
|
|
9
|
+
|
|
10
|
+
Order per linked worktree, first match wins: orphan registration (folder gone) -> a junction or symlink -> the
|
|
11
|
+
process cwd is inside it -> Orca-managed -> DIRTY (incl. untracked) -> IN USE -> idle-session -> locked -> the
|
|
12
|
+
deletion-grade proof `caddis_finished.prove_worktree_finished` (merged PR, no commit after its head, every changed
|
|
13
|
+
file equals origin/<default>). A branch with no worktree gets `caddis_finished.prove_branch_finished`.
|
|
14
|
+
|
|
15
|
+
The live-session rule is the PowerShell report's: a transcript written within 60 min PROVES a session is live;
|
|
16
|
+
an older one proves nothing (idle-session, KEPT). A session id with no transcript is "removable" to the classifier,
|
|
17
|
+
but tidy still needs the merged proof. Removal goes through `caddis_finished.remove_finished` (links first,
|
|
18
|
+
`force=False`, compare-and-delete push), so the rules live in one place.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import shutil
|
|
26
|
+
import subprocess
|
|
27
|
+
import sys
|
|
28
|
+
import time
|
|
29
|
+
from collections.abc import Callable
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
|
|
32
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
33
|
+
import caddis_finished as cf
|
|
34
|
+
|
|
35
|
+
ORCA_TIMEOUT_S = 10.0
|
|
36
|
+
_ACTIONS = ("REMOVE", "REMOVED", "KEPT", "TRIAGE", "GONE", "FAILED")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _key(path: str | Path) -> str:
|
|
40
|
+
return os.path.normcase(os.path.realpath(path))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def orca_lookup(run: Callable = subprocess.run, which: Callable = shutil.which,
|
|
44
|
+
timeout_s: float = ORCA_TIMEOUT_S) -> tuple[dict[str, str] | None, str]:
|
|
45
|
+
"""({normcase(realpath(path)): id}, "") from `orca worktree list`, or (None, why) when the list cannot be trusted.
|
|
46
|
+
|
|
47
|
+
None (not on PATH, non-zero exit, timeout, bad JSON, `ok` false, `truncated` true) means NO worktree counts as
|
|
48
|
+
Orca-managed; the caller prints the reason every run (plan decision 7).
|
|
49
|
+
"""
|
|
50
|
+
if not which("orca"):
|
|
51
|
+
return None, "orca not on PATH"
|
|
52
|
+
cmd = ["orca", "worktree", "list", "--limit", "10000", "--json"]
|
|
53
|
+
try:
|
|
54
|
+
proc = run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",
|
|
55
|
+
stdin=subprocess.DEVNULL, timeout=timeout_s, check=False)
|
|
56
|
+
except subprocess.TimeoutExpired:
|
|
57
|
+
return None, f"orca took longer than {timeout_s:g} s"
|
|
58
|
+
except OSError as exc:
|
|
59
|
+
return None, f"orca could not start: {exc}"
|
|
60
|
+
if proc.returncode != 0:
|
|
61
|
+
text = (proc.stderr or proc.stdout or "").strip()
|
|
62
|
+
return None, f"orca failed: {text.splitlines()[-1] if text else f'exit {proc.returncode}'}"
|
|
63
|
+
try:
|
|
64
|
+
data = json.loads(proc.stdout or "null")
|
|
65
|
+
except ValueError:
|
|
66
|
+
return None, "orca printed bad JSON"
|
|
67
|
+
if not isinstance(data, dict) or not data.get("ok"):
|
|
68
|
+
return None, "orca answered not ok"
|
|
69
|
+
result = data.get("result")
|
|
70
|
+
if not isinstance(result, dict) or not isinstance(result.get("worktrees"), list):
|
|
71
|
+
return None, "orca printed an unexpected shape"
|
|
72
|
+
if result.get("truncated"):
|
|
73
|
+
return None, "orca list is truncated"
|
|
74
|
+
ids: dict[str, str] = {}
|
|
75
|
+
for wt in result["worktrees"]:
|
|
76
|
+
if isinstance(wt, dict) and wt.get("path") and wt.get("id"):
|
|
77
|
+
ids[_key(str(wt["path"]))] = str(wt["id"])
|
|
78
|
+
return ids, ""
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _row(kind: str, name: str, path: str | None, action: str, reason: str) -> dict:
|
|
82
|
+
return {"kind": kind, "name": name, "path": path, "action": action, "reason": reason}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _triage_reason(reason: str) -> str | None:
|
|
86
|
+
"""The `why` for TRIAGE when a KEPT proof reason means "no PR" or "a CLOSED unmerged PR", else None."""
|
|
87
|
+
if reason.startswith("no merged PR found: no PR"):
|
|
88
|
+
return "no PR"
|
|
89
|
+
if reason.startswith("PR #") and reason.endswith(" is CLOSED"):
|
|
90
|
+
return f"{reason[:-len(' is CLOSED')]} closed unmerged"
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _listing(repo: Path) -> list[dict] | None:
|
|
95
|
+
proc = cf._git(repo, "worktree", "list", "--porcelain")
|
|
96
|
+
return cf.parse_worktree_porcelain(proc.stdout) if proc.returncode == 0 else None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _prune(repo: Path, path: str) -> tuple[str, str]:
|
|
100
|
+
proc = cf._git(repo, "worktree", "prune")
|
|
101
|
+
if proc.returncode != 0:
|
|
102
|
+
return "FAILED", f"git worktree prune failed: {cf._err(proc)}"
|
|
103
|
+
after = _listing(repo)
|
|
104
|
+
if after is None:
|
|
105
|
+
return "FAILED", "git worktree list failed after the prune"
|
|
106
|
+
if any(_key(w["path"]) == _key(path) for w in after):
|
|
107
|
+
return "FAILED", "git kept the registration"
|
|
108
|
+
return "REMOVED", "registration pruned"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _worktree_row(repo: Path, rec: dict, *, default: str, cwd: str, orca: dict[str, str] | None,
|
|
112
|
+
pr_lookup: Callable, projects_root: Path | None, now: float | None) -> tuple[dict, dict]:
|
|
113
|
+
"""(row, facts) for one linked worktree; facts is non-empty only for REMOVE from the merged proof."""
|
|
114
|
+
path, branch = rec["path"], rec["branch"]
|
|
115
|
+
name = branch
|
|
116
|
+
|
|
117
|
+
def row(action: str, reason: str) -> tuple[dict, dict]:
|
|
118
|
+
return _row("worktree", name, path, action, reason), {}
|
|
119
|
+
|
|
120
|
+
if not os.path.lexists(path):
|
|
121
|
+
if rec["locked"]:
|
|
122
|
+
return row("KEPT", "folder gone but locked; git worktree prune keeps it")
|
|
123
|
+
return _row("worktree", name, path, "REMOVE", "folder gone; git worktree prune"), {"orphan": True}
|
|
124
|
+
try:
|
|
125
|
+
import caddis_worktree_safety as safety
|
|
126
|
+
|
|
127
|
+
if safety.is_link(os.lstat(path)):
|
|
128
|
+
return row("KEPT", "the folder is a junction or symlink")
|
|
129
|
+
except OSError as exc:
|
|
130
|
+
return row("KEPT", f"cannot inspect it: {exc}")
|
|
131
|
+
if cf._inside(cwd, path):
|
|
132
|
+
return row("KEPT", "this session is working in it")
|
|
133
|
+
if orca is not None and _key(path) in orca:
|
|
134
|
+
return row("KEPT", f"Orca-managed: remove it in Orca (`orca worktree rm --worktree id:{orca[_key(path)]}`)")
|
|
135
|
+
status = cf._git(Path(path), "status", "--porcelain", "--untracked-files=normal")
|
|
136
|
+
if status.returncode != 0:
|
|
137
|
+
return row("KEPT", f"git status failed: {cf._err(status)}")
|
|
138
|
+
session = cf.session_id_from_path(path)
|
|
139
|
+
idle = cf.session_idle_minutes(session, projects_root, now) if session else -1
|
|
140
|
+
state = cf.worktree_state(True, bool(status.stdout.strip()), session is not None, idle)
|
|
141
|
+
if state == "DIRTY":
|
|
142
|
+
return row("KEPT", "DIRTY: uncommitted changes (incl. untracked)")
|
|
143
|
+
if state == "IN USE":
|
|
144
|
+
return row("KEPT", f"IN USE: session {session[:8]} wrote {idle} min ago")
|
|
145
|
+
if state == "idle-session":
|
|
146
|
+
return row("KEPT", f"owned by session {session[:8]}, idle {idle} min; not proof it ended")
|
|
147
|
+
if state != "removable":
|
|
148
|
+
return row("KEPT", f"unexpected state {state}")
|
|
149
|
+
if rec["locked"]:
|
|
150
|
+
return row("KEPT", "it is locked")
|
|
151
|
+
entry = {"repo": str(repo), "branch": None if branch == "(detached)" else branch}
|
|
152
|
+
action, reason, facts = cf.prove_worktree_finished(entry, Path(path), cwd, pr_lookup)
|
|
153
|
+
if action == "KEPT":
|
|
154
|
+
why = _triage_reason(reason)
|
|
155
|
+
if why and entry["branch"]:
|
|
156
|
+
action, reason, _ = cf._triage(repo, branch, default, why)
|
|
157
|
+
return _row("worktree", name, path, action, reason), facts
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _local_branches(repo: Path) -> list[str] | None:
|
|
161
|
+
proc = cf._git(repo, "for-each-ref", "--format=%(refname)", "refs/heads")
|
|
162
|
+
if proc.returncode != 0:
|
|
163
|
+
return None
|
|
164
|
+
return [ln[len("refs/heads/"):] for ln in proc.stdout.splitlines() if ln.startswith("refs/heads/")]
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def tidy_repo(repo_root: Path, *, apply: bool = False, cwd: str | None = None, pr_lookup: Callable | None = None,
|
|
168
|
+
orca_lookup: Callable | None = None, projects_root: Path | None = None,
|
|
169
|
+
now: float | None = None) -> tuple[list[dict], list[str]]:
|
|
170
|
+
"""(rows, notes) for every worktree and every local non-default branch with no worktree. `apply` acts on REMOVE."""
|
|
171
|
+
pr_lookup = pr_lookup or cf.gh_pr_lookup
|
|
172
|
+
ask_orca = orca_lookup or globals()["orca_lookup"]
|
|
173
|
+
cwd = cwd or os.getcwd()
|
|
174
|
+
now = time.time() if now is None else now
|
|
175
|
+
notes: list[str] = []
|
|
176
|
+
repo = cf.main_repo({"repo": str(repo_root)}, Path(repo_root))
|
|
177
|
+
if repo is None:
|
|
178
|
+
return [], [f"[TIDY] skipped: {repo_root} is not a git repository"]
|
|
179
|
+
records = _listing(repo)
|
|
180
|
+
if not records: # None (git failed) or empty (unparseable): never guess which is the main checkout
|
|
181
|
+
return [], ["[TIDY] skipped: git worktree list failed or was empty; nothing is listed or removed"]
|
|
182
|
+
default = cf.default_branch(repo)
|
|
183
|
+
rows: list[dict] = []
|
|
184
|
+
main, linked = records[0], records[1:]
|
|
185
|
+
rows.append(_row("worktree", main["branch"], main["path"], "KEPT", "it is the main checkout"))
|
|
186
|
+
orca: dict[str, str] | None = {}
|
|
187
|
+
if linked:
|
|
188
|
+
orca, why = ask_orca()
|
|
189
|
+
if orca is None:
|
|
190
|
+
notes.append(f"[TIDY] skipped: Orca check - {why}; no worktree is treated as Orca-managed")
|
|
191
|
+
for rec in linked:
|
|
192
|
+
row, facts = _worktree_row(repo, rec, default=default, cwd=cwd, orca=orca, pr_lookup=pr_lookup,
|
|
193
|
+
projects_root=projects_root, now=now)
|
|
194
|
+
if apply and row["action"] == "REMOVE":
|
|
195
|
+
if facts.get("orphan"): # no folder and no PR proof: only the registration goes, never a branch
|
|
196
|
+
row["action"], row["reason"] = _prune(repo, rec["path"])
|
|
197
|
+
elif not os.path.lexists(rec["path"]):
|
|
198
|
+
row["action"], row["reason"] = "GONE", "the folder vanished before removal"
|
|
199
|
+
else:
|
|
200
|
+
row["action"], row["reason"] = cf.remove_finished(Path(rec["path"]), facts)
|
|
201
|
+
rows.append(row)
|
|
202
|
+
branches = _local_branches(repo)
|
|
203
|
+
if branches is None:
|
|
204
|
+
notes.append("[TIDY] skipped: branches - git for-each-ref failed; no branch is listed or removed")
|
|
205
|
+
return rows, notes
|
|
206
|
+
checked_out = {rec["branch"] for rec in records}
|
|
207
|
+
for branch in branches:
|
|
208
|
+
if branch == default or branch in checked_out:
|
|
209
|
+
continue # the default branch is never a candidate; a checked-out branch is its worktree's row
|
|
210
|
+
action, reason, facts = cf.prove_branch_finished(repo, branch, pr_lookup)
|
|
211
|
+
if apply and action == "REMOVE":
|
|
212
|
+
action, reason = cf.remove_finished(None, facts)
|
|
213
|
+
rows.append(_row("branch", branch, None, action, reason))
|
|
214
|
+
return rows, notes
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def print_rows(rows: list[dict], notes: list[str], apply: bool) -> None:
|
|
218
|
+
"""The notes, one line per row, then `[TIDY] <would remove|removed> <n>, kept <n>, triage <n>, gone <n>, failed <n>`."""
|
|
219
|
+
for note in notes:
|
|
220
|
+
print(note)
|
|
221
|
+
for r in rows:
|
|
222
|
+
where = f" ({r['path']})" if r["path"] else ""
|
|
223
|
+
print(f"[TIDY] {r['action']:<7} {r['kind']:<8} {r['name']}{where}: {r['reason']}")
|
|
224
|
+
n = {a: sum(1 for r in rows if r["action"] == a) for a in _ACTIONS}
|
|
225
|
+
done = f"removed {n['REMOVED']}" if apply else f"would remove {n['REMOVE']}"
|
|
226
|
+
print(f"[TIDY] {done}, kept {n['KEPT']}, triage {n['TRIAGE']}, gone {n['GONE']}, failed {n['FAILED']}")
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def run_cli(repo_root: Path, *, apply: bool, as_json: bool) -> int:
|
|
230
|
+
"""`caddis_tidy.py --hygiene`: 0 when nothing failed, 1 when a removal FAILED, 2 when the repo cannot be read."""
|
|
231
|
+
rows, notes = tidy_repo(Path(repo_root), apply=apply)
|
|
232
|
+
if as_json:
|
|
233
|
+
print(json.dumps({"apply": apply, "rows": [dict(r, path=None if r["path"] is None else str(r["path"]))
|
|
234
|
+
for r in rows], "notes": notes}, indent=2))
|
|
235
|
+
else:
|
|
236
|
+
print(f"[TIDY] hygiene {'APPLY' if apply else 'DRY-RUN'} {repo_root}")
|
|
237
|
+
print_rows(rows, notes, apply)
|
|
238
|
+
if not rows:
|
|
239
|
+
return 2
|
|
240
|
+
return 1 if any(r["action"] == "FAILED" for r in rows) else 0
|
|
@@ -1273,6 +1273,10 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
1273
1273
|
ap.add_argument("--verbose", action="store_true",
|
|
1274
1274
|
help="with --temp: list every folder and note (default: totals, the 10 largest, "
|
|
1275
1275
|
"kept notes grouped by reason)")
|
|
1276
|
+
ap.add_argument("--hygiene", action="store_true",
|
|
1277
|
+
help="list every worktree and local branch of the repo with an action and a reason "
|
|
1278
|
+
"(with --apply: remove only the ones proved finished)")
|
|
1279
|
+
ap.add_argument("--json", action="store_true", help="with --hygiene: print the rows as JSON")
|
|
1276
1280
|
args = ap.parse_args(argv)
|
|
1277
1281
|
# A status or path the console cannot encode prints as `?`, never a crash (a cp1252 pipe).
|
|
1278
1282
|
for stream in (sys.stdout, sys.stderr):
|
|
@@ -1282,6 +1286,14 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
1282
1286
|
pass
|
|
1283
1287
|
|
|
1284
1288
|
repo_root = Path(args.repo_root).resolve()
|
|
1289
|
+
if args.json and not args.hygiene:
|
|
1290
|
+
ap.error("--json only works together with --hygiene")
|
|
1291
|
+
if args.hygiene:
|
|
1292
|
+
if args.check or args.commit_range or args.only or args.prune or args.temp or args.verbose:
|
|
1293
|
+
ap.error("--hygiene runs alone: not with --check, --commit-range, --only, --prune, --temp or --verbose")
|
|
1294
|
+
import caddis_repo_tidy # ships beside this file
|
|
1295
|
+
|
|
1296
|
+
return caddis_repo_tidy.run_cli(repo_root, apply=args.apply, as_json=args.json)
|
|
1285
1297
|
if args.temp and not args.prune:
|
|
1286
1298
|
ap.error("--temp only works together with --prune")
|
|
1287
1299
|
if args.verbose and not args.temp:
|