@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.
Files changed (55) hide show
  1. package/bundles/antigravity-plugin/guard_agy.py +6 -2
  2. package/bundles/antigravity-plugin/plugin.json +1 -1
  3. package/bundles/antigravity-plugin/repo_freshness.py +71 -6
  4. package/bundles/antigravity-plugin/repo_hygiene.py +516 -0
  5. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
  6. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
  7. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
  8. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
  9. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
  10. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
  11. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
  12. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
  13. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
  14. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
  15. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
  16. package/bundles/antigravity-plugin/scripts/caddis_finished.py +537 -0
  17. package/bundles/antigravity-plugin/scripts/caddis_guide.json +9 -8
  18. package/bundles/antigravity-plugin/scripts/caddis_own_cleanup.py +23 -248
  19. package/bundles/antigravity-plugin/scripts/caddis_repo_tidy.py +240 -0
  20. package/bundles/antigravity-plugin/scripts/caddis_tidy.py +12 -0
  21. package/bundles/antigravity-plugin/scripts/caddis_worktree_root.py +111 -2
  22. package/bundles/antigravity-plugin/scripts/setup_project_ai.py +67 -10
  23. package/bundles/antigravity-plugin/skills/_registry.md +4 -4
  24. package/bundles/antigravity-plugin/skills/adopt-app/SKILL.md +2 -5
  25. package/bundles/antigravity-plugin/skills/cloud-phases/SKILL.md +1 -1
  26. package/bundles/antigravity-plugin/skills/dashboard-perf-sweep/SKILL.md +1 -1
  27. package/bundles/antigravity-plugin/skills/db-diagram/SKILL.md +1 -1
  28. package/bundles/antigravity-plugin/skills/explainer-doc/SKILL.md +1 -1
  29. package/bundles/antigravity-plugin/skills/implement/SKILL.md +4 -0
  30. package/bundles/antigravity-plugin/skills/port-to-github/SKILL.md +2 -5
  31. package/bundles/antigravity-plugin/skills/pr-merge/SKILL.md +1 -1
  32. package/bundles/antigravity-plugin/skills/ship-merge/SKILL.md +1 -1
  33. package/bundles/antigravity-plugin/skills/ship-pr/SKILL.md +1 -1
  34. package/bundles/antigravity-plugin/skills/tech-explainer/SKILL.md +2 -6
  35. package/bundles/antigravity-plugin/skills/using-git-worktrees/SKILL.md +19 -2
  36. package/bundles/antigravity-plugin/skills/warm-editorial-ui/SKILL.md +1 -1
  37. package/bundles/antigravity-plugin-extras/plugin.json +1 -1
  38. package/bundles/antigravity-plugin-extras/skills/_registry.md +2 -2
  39. package/bundles/antigravity-plugin-extras/skills/building-ai-agent-on-cloudflare/SKILL.md +1 -2
  40. package/bundles/antigravity-plugin-extras/skills/building-mcp-server-on-cloudflare/SKILL.md +1 -2
  41. package/bundles/antigravity-plugin-extras/skills/data-contract-pipeline/SKILL.md +1 -1
  42. package/bundles/antigravity-plugin-extras/skills/responsive-mobile-native/SKILL.md +2 -4
  43. package/bundles/antigravity-plugin-extras/skills/runner-move/SKILL.md +2 -4
  44. package/bundles/antigravity-plugin-extras/skills/setup-project-ai/SKILL.md +1 -1
  45. package/bundles/antigravity-plugin-extras/skills/understand-anything/SKILL.md +2 -5
  46. package/bundles/codex/.codex/skills/coding/dashboard-perf-sweep/SKILL.md +1 -1
  47. package/bundles/codex/.codex/skills/data/db-diagram/SKILL.md +1 -1
  48. package/bundles/codex/.codex/skills/devops/adopt-app/SKILL.md +2 -5
  49. package/bundles/codex/.codex/skills/devops/port-to-github/SKILL.md +2 -5
  50. package/bundles/codex/.codex/skills/devops/using-git-worktrees/SKILL.md +19 -2
  51. package/bundles/codex/.codex/skills/docs/explainer-doc/SKILL.md +1 -1
  52. package/bundles/codex/.codex/skills/docs/tech-explainer/SKILL.md +2 -6
  53. package/bundles/codex/.codex/skills/frontend/warm-editorial-ui/SKILL.md +1 -1
  54. package/bundles/manifest.json +3 -3
  55. package/package.json +1 -1
@@ -0,0 +1,537 @@
1
+ """Is this worktree or branch finished? One definition, shared by the session-start report and tidy.
2
+
3
+ Phase 1 of `.caddis/plans/repo-hygiene-report.md`: the pure core, ported 1:1 from the fleet's PowerShell report
4
+ `bootstrap/report-stale-worktrees.ps1` (`Get-SessionIdFromPath`, `Get-SessionIdleMinutes`, `Get-WorktreeState`,
5
+ `Test-HasLinkedWorktrees`, the porcelain reader and the single-repo Group-Object fix), plus the report-grade branch
6
+ state. Stdlib only. Importing this module starts no process and scans nothing.
7
+
8
+ session_id_from_path(path) -> the owning session id of a scratchpad worktree, or None
9
+ session_idle_minutes(id, root, now) -> minutes since that session wrote its transcript; -1 = UNKNOWN
10
+ worktree_state(exists, dirty, owned, ..) -> "orphan-registration" | "DIRTY" | "removable" | "IN USE" |
11
+ "idle-session"
12
+ has_linked_worktrees(git_dir) -> False proves there is nothing to report (no git spawn needed)
13
+ parse_worktree_porcelain(text) -> [{"path", "branch", "locked"}], main working tree first
14
+ count_by_repo(findings) -> [(repo, count)], count descending, then name
15
+ branch_report_state(tip, prs, is_anc) -> (state, reason) from the cheap PR list; report-grade, never deletes
16
+
17
+ Phase 2: the DELETION-grade proofs, moved from `caddis_own_cleanup.py` (which keeps its old private names as
18
+ aliases), so "finished" has one definition for `/handoff` own-cleanup and `caddis_tidy.py --hygiene`:
19
+
20
+ prove_worktree_finished(entry, path, cwd, pr_lookup) -> ("REMOVE", reason, facts) | ("KEPT"/"GONE", reason, {})
21
+ prove_branch_finished(repo, branch, pr_lookup) -> ("REMOVE", reason, facts) | ("KEPT"/"TRIAGE", reason, {})
22
+ remove_finished(path | None, facts) -> ("REMOVED" | "FAILED", notes); path None = branches only
23
+
24
+ `pr_lookup(main_repo, branch, pr) -> list[{number, state, headRefOid, headRefName}]` (newest first) is the gh seam;
25
+ it raises PrLookupError. `gh_pr_lookup` calls plain `gh` with the inherited environment (never `gh auth switch`).
26
+ Anything in doubt is KEPT. TRIAGE (no PR, or a CLOSED unmerged PR) is never removed. These functions run git and gh
27
+ when CALLED; `caddis_worktree_safety` is imported inside them only, so the pure functions above need nothing else.
28
+
29
+ The invariant (measured 2026-09-11: of 19 worktrees the old logic called removable, 15 belonged to a session that was
30
+ running at that moment): evidence that a session is ALIVE never produces `removable`. The converse keeps the report
31
+ useful: the absence of that evidence is not proof the session ended, so it yields the weaker `idle-session`.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import json
37
+ import os
38
+ import re
39
+ import subprocess
40
+ import time
41
+ from collections import Counter
42
+ from collections.abc import Callable
43
+ from pathlib import Path
44
+
45
+ ACTIVE_WITHIN_MINUTES: int = 60
46
+
47
+ _UUID = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
48
+
49
+
50
+ def session_id_from_path(path: str | None) -> str | None:
51
+ """The owning session id of a scratchpad worktree, or None.
52
+
53
+ A scratchpad worktree lives at `<temp>/claude/<encoded-project>/<session-id>/scratchpad/<name>`, so the owning
54
+ session id is the segment before `scratchpad`. A session id is a uuid: matching the SHAPE keeps a folder that
55
+ merely sits above a scratchpad from being read as one. Any other path has no owning session.
56
+ """
57
+ if not path:
58
+ return None
59
+ parts = path.replace("\\", "/").split("/")
60
+ for i in range(1, len(parts)):
61
+ if parts[i] == "scratchpad" and _UUID.match(parts[i - 1]):
62
+ return parts[i - 1]
63
+ return None
64
+
65
+
66
+ def session_idle_minutes(session_id: str | None, projects_root: Path | None = None, now: float | None = None) -> int:
67
+ """Minutes since the owning session last wrote `<session_id>.jsonl` under `projects_root`, or -1.
68
+
69
+ -1 means UNKNOWN (no id, no root, no transcript), never "0 minutes ago": conflating the two is how a guard
70
+ inverts itself. A transcript dated in the future (clock skew) reads as 0, never as -1, because -1 is the
71
+ reading that can lead to `removable`.
72
+ """
73
+ if not session_id:
74
+ return -1
75
+ root = projects_root if projects_root is not None else Path.home() / ".claude" / "projects"
76
+ if not root.is_dir():
77
+ return -1
78
+ name = f"{session_id}.jsonl"
79
+ for dirpath, _dirs, files in os.walk(root):
80
+ if name in files:
81
+ try:
82
+ mtime = os.stat(os.path.join(dirpath, name)).st_mtime
83
+ except OSError:
84
+ return -1
85
+ current = time.time() if now is None else now
86
+ return max(0, int((current - mtime) // 60))
87
+ return -1
88
+
89
+
90
+ def worktree_state(exists: bool, dirty: bool, has_owning_session: bool, session_idle_minutes: int = -1,
91
+ active_within_minutes: int = ACTIVE_WITHIN_MINUTES) -> str:
92
+ """PURE classification of one linked worktree, in the order of `Get-WorktreeState`.
93
+
94
+ orphan (folder gone) > DIRTY > no owning session = removable > written within the window = IN USE >
95
+ any other reading = idle-session > -1 (session id in the path but no transcript at all) = removable.
96
+
97
+ The idle minutes default to -1, an ordinary int that cannot be confused with a real reading. (The PowerShell
98
+ original avoided [Nullable[int]] because PowerShell unwraps it to 0 at binding, so "unknown" became "active 0
99
+ minutes ago".) A recent write PROVES live. No write proves nothing, so it never earns `removable`.
100
+ `removable` here means "nothing uncommitted would be lost and nobody is using it"; tidy still requires a merged
101
+ proof before it removes anything.
102
+ """
103
+ if not exists:
104
+ return "orphan-registration"
105
+ if dirty:
106
+ return "DIRTY"
107
+ if not has_owning_session:
108
+ return "removable"
109
+ if 0 <= session_idle_minutes <= active_within_minutes:
110
+ return "IN USE"
111
+ if session_idle_minutes >= 0:
112
+ return "idle-session"
113
+ return "removable" # a session id in the path but no transcript at all: the session is gone
114
+
115
+
116
+ def has_linked_worktrees(git_dir: Path) -> bool:
117
+ """True when `<git_dir>/worktrees` holds at least one registration, a stale one too.
118
+
119
+ Git records every linked worktree there, so a missing or empty folder proves there is nothing to report and the
120
+ repo needs no `git worktree list` spawn (measured 2026-09-26: those spawns were 1.1 s of a 2.1 s hook).
121
+ """
122
+ wt_dir = Path(git_dir) / "worktrees"
123
+ try:
124
+ with os.scandir(wt_dir) as entries:
125
+ return any(e.is_dir() for e in entries)
126
+ except OSError:
127
+ return False
128
+
129
+
130
+ def parse_worktree_porcelain(text: str) -> list[dict]:
131
+ """`git worktree list --porcelain` -> one dict per block: {"path", "branch", "locked"}.
132
+
133
+ `branch` is the name after `refs/heads/`, or "(detached)". The first dict is the main working tree.
134
+ """
135
+ records: list[dict] = []
136
+ current: dict | None = None
137
+ for line in text.splitlines():
138
+ if line.startswith("worktree "):
139
+ if current is not None:
140
+ records.append(current)
141
+ current = {"path": line[len("worktree "):], "branch": "(detached)", "locked": False}
142
+ elif current is None:
143
+ continue
144
+ elif line.startswith("branch refs/heads/"):
145
+ current["branch"] = line[len("branch refs/heads/"):]
146
+ elif line == "locked" or line.startswith("locked "):
147
+ current["locked"] = True
148
+ if current is not None:
149
+ records.append(current)
150
+ return records
151
+
152
+
153
+ def count_by_repo(findings: list[dict]) -> list[tuple[str, int]]:
154
+ """Group findings on `finding["repo"]`: [(repo, count)], count descending, then name.
155
+
156
+ Always a list of groups. The PowerShell original needed `@()` around Group-Object: with a SINGLE repo it
157
+ returned one group, and `.Count` then read that group's member count ("3 repos" for one repo).
158
+ """
159
+ counts = Counter(f["repo"] for f in findings)
160
+ return sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
161
+
162
+
163
+ def branch_report_state(tip: str, prs: list[dict], is_ancestor: Callable[[str, str], bool]) -> tuple[str, str]:
164
+ """REPORT-grade state of one local branch, from the cheap PR list. It never decides a deletion.
165
+
166
+ `prs` are the PRs whose `headRefName` equals the branch, newest first. Any OPEN PR wins. Otherwise the newest
167
+ PR decides: MERGED counts as merged-not-deleted only when the tip IS the merged head or an ancestor of it.
168
+ A tip with commits after the merged head (a reused name), a CLOSED PR, or no PR is needs-triage.
169
+ """
170
+ for pr in prs:
171
+ if pr.get("state") == "OPEN":
172
+ return "open-pr", f"PR #{pr.get('number')} open"
173
+ if not prs:
174
+ return "needs-triage", "no PR"
175
+ newest = prs[0]
176
+ number = newest.get("number")
177
+ if newest.get("state") == "MERGED":
178
+ head = newest.get("headRefOid") or ""
179
+ if head and (tip == head or is_ancestor(tip, head)):
180
+ return "merged-not-deleted", f"PR #{number} merged"
181
+ return "needs-triage", f"commits after merged PR #{number}"
182
+ return "needs-triage", f"PR #{number} closed unmerged"
183
+
184
+
185
+ # ================================================================ Phase 2: the deletion-grade proofs (run git and gh)
186
+ # Moved from caddis_own_cleanup.py with the same bodies; the old private names stay there as aliases.
187
+
188
+ GIT_TIMEOUT = 60
189
+ NET_TIMEOUT = 120
190
+ _GH_FIELDS = "number,state,headRefOid,mergedAt,headRefName"
191
+
192
+
193
+ class PrLookupError(Exception):
194
+ """gh is missing, failed, or the repo cannot be named."""
195
+
196
+
197
+ def _env() -> dict[str, str]:
198
+ env = dict(os.environ)
199
+ env["GIT_TERMINAL_PROMPT"] = "0" # a credential prompt must fail, not hang the handoff
200
+ return env
201
+
202
+
203
+ def _run(cmd: list[str], cwd: Path | None = None, timeout: int = GIT_TIMEOUT) -> subprocess.CompletedProcess:
204
+ """Never raises: a missing program or a timeout comes back as returncode -1 with the problem in stderr."""
205
+ try:
206
+ return subprocess.run(cmd, cwd=str(cwd) if cwd else None, capture_output=True, text=True, encoding="utf-8",
207
+ errors="replace", stdin=subprocess.DEVNULL, timeout=timeout, check=False, env=_env())
208
+ except FileNotFoundError:
209
+ return subprocess.CompletedProcess(cmd, -1, "", f"{cmd[0]} is not installed")
210
+ except subprocess.TimeoutExpired:
211
+ return subprocess.CompletedProcess(cmd, -1, "", f"{cmd[0]} timed out after {timeout} s")
212
+ except OSError as exc:
213
+ return subprocess.CompletedProcess(cmd, -1, "", str(exc))
214
+
215
+
216
+ def _git(path: Path, *args: str, timeout: int = GIT_TIMEOUT) -> subprocess.CompletedProcess:
217
+ return _run(["git", "-c", "core.quotepath=off", "-C", str(path), *args], timeout=timeout)
218
+
219
+
220
+ def _err(proc: subprocess.CompletedProcess) -> str:
221
+ text = (proc.stderr or proc.stdout or "").strip()
222
+ return text.splitlines()[-1] if text else f"exit {proc.returncode}"
223
+
224
+
225
+ def _same(a: str | Path, b: str | Path) -> bool:
226
+ return os.path.normcase(os.path.realpath(a)) == os.path.normcase(os.path.realpath(b))
227
+
228
+
229
+ def _inside(child: str | Path, parent: str | Path) -> bool:
230
+ """`child` is `parent` or under it (both resolved, case-folded on Windows)."""
231
+ c = os.path.normcase(os.path.realpath(child))
232
+ p = os.path.normcase(os.path.realpath(parent))
233
+ return c == p or c.startswith(p.rstrip("\\/") + os.sep)
234
+
235
+
236
+ # -- gh ---------------------------------------------------------------------------------------------------------
237
+
238
+ def repo_slug(main_repo: Path) -> str | None:
239
+ """`owner/name` from the origin URL (https, ssh or scp form), else None."""
240
+ proc = _git(main_repo, "remote", "get-url", "origin")
241
+ return slug_from_url(proc.stdout.strip() if proc.returncode == 0 else "")
242
+
243
+
244
+ def slug_from_url(url: str) -> str | None:
245
+ """PURE: `owner/name` from an origin URL (https, ssh or scp form), else None. The session-start hook reads the
246
+ URL through its own no-console-window seam and parses it here, so the rule stays in one place."""
247
+ if "://" not in url and "@" not in url:
248
+ return None # a local path origin has no GitHub name
249
+ match = re.search(r"[:/]([^/:]+)/([^/]+?)(?:\.git)?/?$", url)
250
+ return f"{match.group(1)}/{match.group(2)}" if match else None
251
+
252
+
253
+ def gh_pr_lookup(main_repo: Path, branch: str | None, pr: str | None) -> list[dict]:
254
+ slug = repo_slug(main_repo)
255
+ if not slug:
256
+ raise PrLookupError("cannot read owner/name from the origin URL")
257
+ if pr:
258
+ proc = _run(["gh", "pr", "view", pr, "--repo", slug, "--json", _GH_FIELDS], timeout=NET_TIMEOUT)
259
+ elif branch:
260
+ proc = _run(["gh", "pr", "list", "--repo", slug, "--head", branch, "--state", "all", "--limit", "20",
261
+ "--json", _GH_FIELDS], timeout=NET_TIMEOUT)
262
+ else:
263
+ return []
264
+ if proc.returncode != 0:
265
+ raise PrLookupError(f"gh failed: {_err(proc)}")
266
+ try:
267
+ data = json.loads(proc.stdout or "null")
268
+ except ValueError as exc:
269
+ raise PrLookupError(f"gh printed bad JSON: {exc}") from exc
270
+ data = [data] if isinstance(data, dict) else data
271
+ if not isinstance(data, list):
272
+ raise PrLookupError("gh printed an unexpected shape")
273
+ return [d for d in data if isinstance(d, dict)]
274
+
275
+
276
+ def pr_number(value: str | None) -> str | None:
277
+ match = re.search(r"(\d+)\s*$", str(value or ""))
278
+ return match.group(1) if match else None
279
+
280
+
281
+ def pick_pr(prs: list[dict], branch: str | None, by_number: bool) -> tuple[dict | None, str]:
282
+ """(the merged PR, "") or (None, why the worktree is kept)."""
283
+ if not prs:
284
+ return None, f"no merged PR found: no PR for branch {branch}" if branch else "no merged PR found: no PR"
285
+ open_pr = next((p for p in prs if str(p.get("state", "")).upper() == "OPEN"), None)
286
+ pick = open_pr or prs[0]
287
+ state = str(pick.get("state", "")).upper() or "UNKNOWN"
288
+ if state != "MERGED":
289
+ return None, f"PR #{pick.get('number')} is {state}"
290
+ head_name = pick.get("headRefName")
291
+ if by_number and branch and head_name and head_name != branch:
292
+ return None, f"PR #{pick.get('number')} is for branch {head_name}, not {branch}"
293
+ return pick, ""
294
+
295
+
296
+ # -- git facts --------------------------------------------------------------------------------------------------
297
+
298
+ def main_repo(entry: dict, path: Path) -> Path | None:
299
+ """The repo to list worktrees from: the entry's `repo` when it is a git checkout, else from the path's common dir."""
300
+ for start in (entry.get("repo"), str(path)):
301
+ if not start or not os.path.isdir(start):
302
+ continue
303
+ proc = _git(Path(start), "rev-parse", "--path-format=absolute", "--git-common-dir")
304
+ if proc.returncode == 0 and proc.stdout.strip():
305
+ common = Path(proc.stdout.strip())
306
+ return common.parent if common.name == ".git" else Path(start)
307
+ return None
308
+
309
+
310
+ def default_branch(wt: Path) -> str:
311
+ proc = _git(wt, "symbolic-ref", "--short", "-q", "refs/remotes/origin/HEAD")
312
+ name = proc.stdout.strip() if proc.returncode == 0 else ""
313
+ return name.split("/", 1)[1] if name.startswith("origin/") else "main"
314
+
315
+
316
+ def ref(wt: Path, rev: str) -> str | None:
317
+ proc = _git(wt, "rev-parse", "-q", "--verify", f"{rev}^{{commit}}")
318
+ return proc.stdout.strip() if proc.returncode == 0 and proc.stdout.strip() else None
319
+
320
+
321
+ def changed_names(wt: Path, a: str, b: str) -> set[str] | None:
322
+ proc = _git(wt, "diff", "--name-only", "-z", "--no-renames", "--no-ext-diff", a, b)
323
+ return None if proc.returncode != 0 else {n for n in proc.stdout.split("\0") if n}
324
+
325
+
326
+ def branch_tip(repo: Path, branch: str) -> str | None:
327
+ proc = _git(repo, "rev-parse", "-q", "--verify", f"refs/heads/{branch}")
328
+ return proc.stdout.strip() if proc.returncode == 0 and proc.stdout.strip() else None
329
+
330
+
331
+ def _landed(where: Path, rev: str, number: str, pr_head: str, default: str) -> str | None:
332
+ """None when `rev` has no commit after the merged PR head and every file it changed equals origin/<default>.
333
+
334
+ Else why not. The squash-merge proof: fetch origin/<default> first, then compare only the files `rev` changed
335
+ since the merge base (a later commit on the default branch to another file does not block it). Shared by both
336
+ proofs, with `rev` = HEAD (worktree) or `refs/heads/<branch>` (branch), so the check is written once.
337
+ """
338
+ after = _git(where, "rev-list", "--max-count=1", f"{pr_head}..{rev}")
339
+ if after.returncode != 0:
340
+ return f"git rev-list failed: {_err(after)}"
341
+ if after.stdout.strip():
342
+ return f"commits after the merged PR #{number}"
343
+ fetch = _git(where, "fetch", "--quiet", "--no-tags", "origin",
344
+ f"+refs/heads/{default}:refs/remotes/origin/{default}", timeout=NET_TIMEOUT)
345
+ if fetch.returncode != 0:
346
+ return f"cannot fetch origin/{default}: {_err(fetch)}"
347
+ target = f"refs/remotes/origin/{default}"
348
+ base = _git(where, "merge-base", target, rev)
349
+ if base.returncode != 0 or not base.stdout.strip():
350
+ return f"no merge base with origin/{default}"
351
+ changed = changed_names(where, base.stdout.strip(), rev)
352
+ differ_all = changed_names(where, target, rev)
353
+ if changed is None or differ_all is None:
354
+ return f"git diff against origin/{default} failed"
355
+ differ = sorted(changed & differ_all)
356
+ if differ:
357
+ return f"{len(differ)} file(s) differ from origin/{default}: {', '.join(differ[:3])}"
358
+ return None
359
+
360
+
361
+ # -- the proofs -------------------------------------------------------------------------------------------------
362
+
363
+ def prove_worktree_finished(entry: dict, path: Path, cwd: str, pr_lookup: Callable) -> tuple[str, str, dict]:
364
+ """("REMOVE", reason, facts) or ("KEPT"/"GONE", reason, {}). An owner-specific KEPT is the caller's, first."""
365
+ import caddis_worktree_safety as safety
366
+
367
+ if not os.path.lexists(path):
368
+ return "GONE", "", {}
369
+ try:
370
+ if safety.is_link(os.lstat(path)):
371
+ return "KEPT", "the folder is a junction or symlink", {}
372
+ except OSError as exc:
373
+ return "KEPT", f"cannot inspect it: {exc}", {}
374
+ repo = main_repo(entry, path)
375
+ if repo is None:
376
+ return "KEPT", "not a registered linked worktree (no git repo found)", {}
377
+ listing = _git(repo, "worktree", "list", "--porcelain")
378
+ if listing.returncode != 0:
379
+ return "KEPT", f"git worktree list failed: {_err(listing)}", {}
380
+ blocks = safety._worktree_blocks(listing.stdout)
381
+ if not blocks:
382
+ return "KEPT", "git listed no worktrees", {}
383
+ main = Path(blocks[0][0][len("worktree "):])
384
+ if _same(path, main):
385
+ return "KEPT", "it is the main checkout", {}
386
+ block = next((b for b in blocks[1:] if _same(path, b[0][len("worktree "):])), None)
387
+ if block is None:
388
+ return "KEPT", f"not a registered linked worktree of {main}", {}
389
+ if _inside(cwd, path):
390
+ return "KEPT", "this session is working in it", {}
391
+ status = _git(path, "status", "--porcelain", "--untracked-files=normal")
392
+ if status.returncode != 0:
393
+ return "KEPT", f"git status failed: {_err(status)}", {}
394
+ if status.stdout.strip():
395
+ return "KEPT", "uncommitted changes", {}
396
+ if any(line == "locked" or line.startswith("locked ") for line in block):
397
+ return "KEPT", "it is locked", {}
398
+ sym = _git(path, "symbolic-ref", "--short", "-q", "HEAD")
399
+ branch = sym.stdout.strip() if sym.returncode == 0 and sym.stdout.strip() else (entry.get("branch") or None)
400
+ default = default_branch(path)
401
+ if branch and branch == default:
402
+ return "KEPT", f"it is on the default branch {default}", {}
403
+ pr = pr_number(entry.get("pr"))
404
+ if not branch and not pr:
405
+ return "KEPT", "no merged PR found: no branch and no PR in the record", {}
406
+ try:
407
+ prs = pr_lookup(main, branch, pr)
408
+ except PrLookupError as exc:
409
+ return "KEPT", f"no merged PR found: {exc}", {}
410
+ except Exception as exc: # noqa: BLE001 - any lookup failure keeps the worktree
411
+ return "KEPT", f"no merged PR found: lookup failed: {exc}", {}
412
+ merged, why = pick_pr(prs, branch, by_number=bool(pr))
413
+ if merged is None:
414
+ return "KEPT", why, {}
415
+ number = str(merged.get("number") or pr or "?")
416
+ head = ref(path, "HEAD")
417
+ if not head:
418
+ return "KEPT", "cannot read HEAD", {}
419
+ pr_head = str(merged.get("headRefOid") or "").strip().lower()
420
+ if not pr_head or not ref(path, pr_head): # a reused branch name: without the PR head, nothing proves HEAD landed
421
+ return "KEPT", f"PR #{number} head commit is not in the local repo", {}
422
+ problem = _landed(path, "HEAD", number, pr_head, default)
423
+ if problem:
424
+ return "KEPT", problem, {}
425
+ facts = {"repo": main, "branch": branch, "pr": number, "pr_head": pr_head, "head": head}
426
+ return "REMOVE", f"PR #{number} merged, clean, tree equals origin/{default}", facts
427
+
428
+
429
+ def _triage(repo: Path, branch: str, default: str, why: str) -> tuple[str, str, dict]:
430
+ """TRIAGE is never removed. The reason carries the branch's age (last commit date) and its own-commit count."""
431
+ ct = _git(repo, "log", "-1", "--format=%ct", f"refs/heads/{branch}")
432
+ try:
433
+ age = f"{max(0, int(time.time() - int(ct.stdout.strip())) // 86400)}d"
434
+ except ValueError:
435
+ age = "?d"
436
+ count = _git(repo, "rev-list", "--count", f"refs/remotes/origin/{default}..refs/heads/{branch}")
437
+ own = count.stdout.strip() if count.returncode == 0 and count.stdout.strip().isdigit() else "?"
438
+ return "TRIAGE", f"{why}, {age} old, {own} own commits", {}
439
+
440
+
441
+ def prove_branch_finished(repo: Path, branch: str, pr_lookup: Callable) -> tuple[str, str, dict]:
442
+ """A local branch: ("REMOVE", reason, facts), ("KEPT", reason, {}) or ("TRIAGE", reason, {}).
443
+
444
+ The same merged-PR, head and squash checks as `prove_worktree_finished`, against `refs/heads/<branch>` instead
445
+ of HEAD. No PR, or a CLOSED unmerged newest PR, is TRIAGE. The default branch, a branch checked out in any
446
+ worktree, an OPEN PR, a lookup failure or any other doubt is KEPT.
447
+ """
448
+ default = default_branch(repo)
449
+ if branch == default:
450
+ return "KEPT", f"it is the default branch {default}", {}
451
+ tip = branch_tip(repo, branch)
452
+ if not tip:
453
+ return "KEPT", f"no local branch {branch}", {}
454
+ listing = _git(repo, "worktree", "list", "--porcelain")
455
+ if listing.returncode != 0:
456
+ return "KEPT", f"git worktree list failed: {_err(listing)}", {}
457
+ holder = next((w for w in parse_worktree_porcelain(listing.stdout) if w["branch"] == branch), None)
458
+ if holder is not None:
459
+ return "KEPT", f"checked out in {holder['path']}", {}
460
+ try:
461
+ prs = pr_lookup(repo, branch, None)
462
+ except PrLookupError as exc:
463
+ return "KEPT", f"no merged PR found: {exc}", {}
464
+ except Exception as exc: # noqa: BLE001 - any lookup failure keeps the branch
465
+ return "KEPT", f"no merged PR found: lookup failed: {exc}", {}
466
+ if not prs:
467
+ return _triage(repo, branch, default, "no PR")
468
+ open_pr = next((p for p in prs if str(p.get("state", "")).upper() == "OPEN"), None)
469
+ if open_pr is not None:
470
+ return "KEPT", f"PR #{open_pr.get('number')} is open", {}
471
+ newest = prs[0]
472
+ number = str(newest.get("number") or "?")
473
+ state = str(newest.get("state", "")).upper() or "UNKNOWN"
474
+ if state == "CLOSED":
475
+ return _triage(repo, branch, default, f"PR #{number} closed unmerged")
476
+ if state != "MERGED":
477
+ return "KEPT", f"PR #{number} is {state}", {}
478
+ head_name = newest.get("headRefName")
479
+ if head_name and head_name != branch:
480
+ return "KEPT", f"PR #{number} is for branch {head_name}, not {branch}", {}
481
+ pr_head = str(newest.get("headRefOid") or "").strip().lower()
482
+ if not pr_head or not ref(repo, pr_head): # a reused branch name: without the PR head, nothing proves it landed
483
+ return "KEPT", f"PR #{number} head commit is not in the local repo", {}
484
+ problem = _landed(repo, f"refs/heads/{branch}", number, pr_head, default)
485
+ if problem:
486
+ return "KEPT", problem, {}
487
+ facts = {"repo": repo, "branch": branch, "pr": number, "pr_head": pr_head, "head": tip}
488
+ return "REMOVE", f"PR #{number} merged, tree equals origin/{default}", facts
489
+
490
+
491
+ def remove_finished(path: Path | None, facts: dict) -> tuple[str, str]:
492
+ """Remove what a proof returned REMOVE for: ("REMOVED", notes) or ("FAILED", problem).
493
+
494
+ `path` None skips the worktree step and removes only the branches; then any kept branch is "FAILED", so a
495
+ caller that reads only the outcome never reports a kept branch as removed. Worktree: `safe_remove_worktree(...,
496
+ force=False)` (links first, never --force). Local branch: only while its tip is HEAD or the PR head and no
497
+ worktree has it checked out. Remote branch: only while its tip is the PR head or HEAD, as one compare-and-delete
498
+ push.
499
+ """
500
+ import caddis_worktree_safety as safety
501
+
502
+ repo, branch, head, pr_head = facts["repo"], facts["branch"], facts["head"], facts["pr_head"]
503
+ local_tip = branch_tip(repo, branch) if branch else None
504
+ landed = {pr_head, head.lower()} - {""} # only tips this proof showed landed
505
+ if path is not None:
506
+ problem = safety.safe_remove_worktree(repo, path, force=False, env=_env())
507
+ if problem:
508
+ return "FAILED", problem
509
+ notes: list[str] = []
510
+ if branch and local_tip:
511
+ listing = _git(repo, "worktree", "list", "--porcelain")
512
+ if listing.returncode != 0 or f"branch refs/heads/{branch}" in listing.stdout.splitlines():
513
+ notes.append("local branch kept: another worktree has it checked out")
514
+ elif local_tip.lower() not in landed:
515
+ notes.append("local branch kept: its tip is not the removed HEAD or the PR head")
516
+ else:
517
+ gone = _git(repo, "branch", "-D", "--", branch)
518
+ notes.append("local branch deleted" if gone.returncode == 0 else f"local branch kept: {_err(gone)}")
519
+ if branch:
520
+ ls = _git(repo, "ls-remote", "--heads", "origin", f"refs/heads/{branch}", timeout=NET_TIMEOUT)
521
+ tips = [ln.split()[0] for ln in ls.stdout.splitlines() if ln.strip()] if ls.returncode == 0 else []
522
+ if ls.returncode != 0:
523
+ notes.append(f"remote branch kept: ls-remote failed: {_err(ls)}")
524
+ elif tips:
525
+ tip = tips[0].lower()
526
+ if tip in landed:
527
+ try:
528
+ push = _git(repo, *safety.remote_delete_args(branch, tip), timeout=NET_TIMEOUT)
529
+ notes.append("remote branch deleted" if push.returncode == 0
530
+ else f"remote branch kept: {_err(push)}")
531
+ except ValueError as exc:
532
+ notes.append(f"remote branch kept: {exc}")
533
+ else:
534
+ notes.append("remote branch kept: its tip moved past the PR head")
535
+ if path is None and any(" branch kept:" in n for n in notes):
536
+ return "FAILED", "; ".join(notes)
537
+ return "REMOVED", "; ".join(notes)
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "version": "1.3.176",
4
- "generated": "2026-11-03 23:28 UTC",
3
+ "version": "1.3.177",
4
+ "generated": "2026-11-04 23:23 UTC",
5
5
  "commands": [
6
6
  {
7
7
  "name": "add-rules",
@@ -630,6 +630,7 @@
630
630
  "caddis_gate.py",
631
631
  "caddis_lanes.py",
632
632
  "caddis_routing.py",
633
+ "caddis_silence_watch.py",
633
634
  "caddis_spend.py",
634
635
  "caddis_status.py",
635
636
  "caddis_tidy.py",
@@ -1664,7 +1665,7 @@
1664
1665
  {
1665
1666
  "name": "dashboard-perf-sweep",
1666
1667
  "category": "coding",
1667
- "description": "Re-measure dashboard/API endpoints for load-time regressions and decide by checklist if a slow one needs the rs-kit refresher, an index, keyset paging, gzip, or nothing. Use when the user says \"sweep dashboard performance\", \"check if this app needs rs-kit\", \"re-measure the perf tracker\", \"is this endpoint a refresher candidate\", or dashboard-performance-tracker.md is stale. Read-only.",
1668
+ "description": "Re-measure dashboard/API endpoints for load-time regressions. Use when the user says \"sweep dashboard performance\", \"check if this app needs rs-kit\", or \"re-measure the perf tracker\".",
1668
1669
  "core": true
1669
1670
  },
1670
1671
  {
@@ -1760,7 +1761,7 @@
1760
1761
  {
1761
1762
  "name": "db-diagram",
1762
1763
  "category": "data",
1763
- "description": "Diagram a SQL artifact (stored proc, view, query, .sql file, table) as Mermaid or Excalidraw. Use when the user says \"diagram this query/proc/view/schema\", \"explain this SQL visually\", \"draw the ER diagram\", \"show me the data flow of this stored proc\", \"/mermaid-db\", or \"/excalidraw-db\". Read-only.",
1764
+ "description": "Diagram SQL artifacts (procs, views, queries, tables) as Mermaid or Excalidraw. Use when the user says \"diagram this SQL\", \"draw the ER diagram\", \"/mermaid-db\", or \"/excalidraw-db\".",
1764
1765
  "core": true
1765
1766
  },
1766
1767
  {
@@ -1892,7 +1893,7 @@
1892
1893
  {
1893
1894
  "name": "explainer-doc",
1894
1895
  "category": "docs",
1895
- "description": "Hand-off doc for a team that did NOT do the investigation (vendor, contractor, another team) — the \"stranger must follow it alone\" case. Use when the user says \"write a spec for the X team\", \"document this for someone outside the team\", \"explainer doc\", \"implementation spec for a vendor\", or \"hand this off to Y\". Not for readers with full context.",
1896
+ "description": "Write a self-contained hand-off spec for an external team or vendor. Use when the user says \"write a spec for the X team\", \"explainer doc\", \"spec for a vendor\", or \"hand this off to Y\".",
1896
1897
  "core": true
1897
1898
  },
1898
1899
  {
@@ -2114,7 +2115,7 @@
2114
2115
  {
2115
2116
  "name": "warm-editorial-ui",
2116
2117
  "category": "frontend",
2117
- "description": "Apply the \"Warm Editorial Refinement\" design system (warm cream/charcoal surfaces, Bahnschrift + Plus Jakarta Sans, layered shadows), the canonical template for new frontend builds. Use for apps, dashboards or UI in the abc-project style, or on \"use our design system\", \"apply our template\", \"make it look like abc-project\", \"use the warm editorial style\", \"use our brand template\", \"add dark mode\", or a new tool for XYZ Brand.",
2118
+ "description": "Apply the Warm Editorial Refinement design system. Use when the user says \"use our design system\", \"warm editorial style\", \"apply our template\", or \"make it look like abc-project\".",
2118
2119
  "core": true
2119
2120
  },
2120
2121
  {
@@ -2282,7 +2283,7 @@
2282
2283
  {
2283
2284
  "name": "data-contract-pipeline",
2284
2285
  "category": "workflow",
2285
- "description": "Build, audit and validate data-to-UI contracts. Use when the user mentions data mapping, UI lineage, DB-to-UI, DisplayDTOs, source-to-screen mapping, data contracts, schema drift, typed API responses, mockup grounding, or asks whether a UI is backed by real data.",
2286
+ "description": "Build, audit, and validate DB-to-UI data contracts. Use when the user mentions data mapping, UI lineage, DisplayDTOs, source-to-screen mapping, or asks if a UI is backed by real data.",
2286
2287
  "core": false
2287
2288
  },
2288
2289
  {
@@ -2336,7 +2337,7 @@
2336
2337
  {
2337
2338
  "name": "setup-project-ai",
2338
2339
  "category": "workflow",
2339
- "description": "Install or refresh the agent-agnostic harness in a project: AGENTS.md rules with CLAUDE.md shims, subagents, commands and settings. Use when setting up AI resources on a project, or the user says 'set up the harness', 'setup-project-ai', 'generate CLAUDE.md', 'onboard this project to Claude Code / Codex / agy', or runs /setup-project-ai.",
2340
+ "description": "Install or refresh the project AI harness: AGENTS.md, CLAUDE.md shims, agents, settings. Use when the user says 'set up the harness', 'generate CLAUDE.md', or runs /setup-project-ai.",
2340
2341
  "core": false
2341
2342
  },
2342
2343
  {