@caddis/cli 0.4.92 → 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/README.md +4 -0
- package/bundles/antigravity-plugin/agents/debug.md +2 -0
- 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_checkout_guard.py +1 -1
- package/bundles/antigravity-plugin/scripts/caddis_finished.py +537 -0
- package/bundles/antigravity-plugin/scripts/caddis_fleet.py +26 -9
- package/bundles/antigravity-plugin/scripts/caddis_guide.json +65 -12
- package/bundles/antigravity-plugin/scripts/caddis_own_cleanup.py +23 -248
- package/bundles/antigravity-plugin/scripts/caddis_preload_review.py +554 -0
- package/bundles/antigravity-plugin/scripts/caddis_repo_tidy.py +240 -0
- package/bundles/antigravity-plugin/scripts/caddis_roadmap_run.py +9 -3
- package/bundles/antigravity-plugin/scripts/caddis_run.py +160 -0
- package/bundles/antigravity-plugin/scripts/caddis_spawn.py +17 -1
- package/bundles/antigravity-plugin/scripts/caddis_tidy.py +12 -0
- package/bundles/antigravity-plugin/scripts/caddis_upstream_check.py +108 -10
- package/bundles/antigravity-plugin/scripts/caddis_worktree_root.py +111 -2
- package/bundles/antigravity-plugin/scripts/setup_project_ai.py +132 -11
- package/bundles/antigravity-plugin/skills/_registry.md +7 -5
- package/bundles/antigravity-plugin/skills/adopt-app/SKILL.md +2 -5
- package/bundles/antigravity-plugin/skills/brainstorming/SKILL.md +232 -40
- package/bundles/antigravity-plugin/skills/brainstorming/builder-check-prompt.md +25 -0
- 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/feature-plan/SKILL.md +7 -1
- package/bundles/antigravity-plugin/skills/fleet-close/SKILL.md +4 -1
- package/bundles/antigravity-plugin/skills/graph-email/SKILL.md +15 -0
- package/bundles/antigravity-plugin/skills/handoff/SKILL.md +9 -2
- package/bundles/antigravity-plugin/skills/implement/SKILL.md +7 -0
- package/bundles/antigravity-plugin/skills/particle-art/SKILL.md +1 -3
- 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/preload-review/SKILL.md +69 -0
- package/bundles/antigravity-plugin/skills/roadmap/SKILL.md +4 -0
- package/bundles/antigravity-plugin/skills/roadmap/assets/plan-resume-prompt.md +6 -5
- 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/spawn-session/SKILL.md +5 -0
- package/bundles/antigravity-plugin/skills/tdd/SKILL.md +2 -1
- package/bundles/antigravity-plugin/skills/tech-explainer/SKILL.md +2 -6
- package/bundles/antigravity-plugin/skills/usage-review/SKILL.md +2 -0
- 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 +3 -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/graph-email/SKILL.md +53 -0
- package/bundles/antigravity-plugin-extras/skills/graph-email/email.toml.example +44 -0
- package/bundles/antigravity-plugin-extras/skills/graph-email/scripts/send_email.py +432 -0
- 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/codex/.codex/skills/media/particle-art/SKILL.md +1 -3
- package/bundles/codex/.codex/skills/workflow/brainstorming/SKILL.md +232 -40
- package/bundles/codex/.codex/skills/workflow/brainstorming/builder-check-prompt.md +25 -0
- package/bundles/codex/.codex/skills/workflow/roadmap/SKILL.md +4 -0
- package/bundles/codex/.codex/skills/workflow/roadmap/assets/plan-resume-prompt.md +6 -5
- package/bundles/manifest.json +3 -3
- package/dist/export/assets/export-CMtV-slT.css +1 -0
- package/dist/export/index.html +2 -2
- package/dist/ui/assets/{Activity-DZKPMOeV.js → Activity-BDjet2xd.js} +1 -1
- package/dist/ui/assets/Guide-Czn5sK0f.js +9 -0
- package/dist/ui/assets/Guide-D-Zy4cUT.css +1 -0
- package/dist/ui/assets/{RoadmapTab-DPsiSmIF.js → RoadmapTab-Bd8geyQx.js} +1 -1
- package/dist/ui/assets/index-Bd0Z4jR8.css +1 -0
- package/dist/ui/assets/{index-xl156OCN.js → index-CmngQ8Mk.js} +12 -12
- package/dist/ui/index.html +2 -2
- package/package.json +1 -1
- package/dist/export/assets/export-HxTgj3z2.css +0 -1
- package/dist/ui/assets/Guide-5ZFfL6sl.js +0 -9
- package/dist/ui/assets/Guide-Dnsb-TRd.css +0 -1
- package/dist/ui/assets/index-DGlNAmeA.css +0 -1
- /package/dist/export/assets/{export-B7BBDg5I.js → export-DtlDFN4L.js} +0 -0
|
@@ -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
|
|
@@ -145,6 +145,7 @@ import caddis_created # noqa: E402
|
|
|
145
145
|
import caddis_notify # noqa: E402
|
|
146
146
|
import caddis_redact # noqa: E402
|
|
147
147
|
import caddis_review # noqa: E402
|
|
148
|
+
import caddis_run # noqa: E402
|
|
148
149
|
import caddis_roadmap # noqa: E402
|
|
149
150
|
import caddis_spend # noqa: E402
|
|
150
151
|
import caddis_worktree_root # noqa: E402
|
|
@@ -339,12 +340,13 @@ def resolve_target(repo: Path, plan: str | None) -> Target:
|
|
|
339
340
|
|
|
340
341
|
|
|
341
342
|
def render_prompt(template: Path, slug: str, phase: int | None = None) -> str:
|
|
342
|
-
"""The template body with `{{slug}}`, `{{phase}}` (empty when None) and `{{
|
|
343
|
-
app repo has no caddis `scripts
|
|
343
|
+
"""The template body with `{{slug}}`, `{{phase}}` (empty when None) and `{{run}}` (`python "<home>/.caddis/bin/
|
|
344
|
+
caddis_run.py"`, the stable launcher: an app repo has no caddis `scripts/`, and a versioned plugin path is gone
|
|
345
|
+
after the next update, while a runner session can outlive it) filled in."""
|
|
344
346
|
text = template.read_text(encoding="utf-8")
|
|
345
347
|
_meta, body = caddis_workstreams.split_document(text)
|
|
346
348
|
for key, value in (("{{slug}}", slug), ("{{phase}}", "" if phase is None else str(phase)),
|
|
347
|
-
("{{
|
|
349
|
+
("{{run}}", caddis_run.stable_prefix())):
|
|
348
350
|
body = body.replace(key, value)
|
|
349
351
|
return body.strip() + "\n"
|
|
350
352
|
|
|
@@ -1245,6 +1247,10 @@ def run(*, repo: Path, plan: str | None = None, roadmap: str | None = None, caps
|
|
|
1245
1247
|
print(f"caddis_roadmap_run: resume prompt template {target.prompt_name} not found", file=sys.stderr)
|
|
1246
1248
|
return caddis_exit.ERROR
|
|
1247
1249
|
template = Path(template)
|
|
1250
|
+
try: # the prompt names ~/.caddis/bin/caddis_run.py; the SessionStart hook keeps it there, this covers a first run
|
|
1251
|
+
caddis_run.install_launcher(_HERE / "caddis_run.py")
|
|
1252
|
+
except OSError as exc:
|
|
1253
|
+
print(f"caddis_roadmap_run: cannot install the caddis_run.py launcher: {exc}", file=sys.stderr)
|
|
1248
1254
|
if governor is None:
|
|
1249
1255
|
governor = default_governor()
|
|
1250
1256
|
if governor is None:
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""caddis_run.py: run a caddis script by its bare name, from the plugin that is installed NOW.
|
|
3
|
+
|
|
4
|
+
Usage: python "<home>/.caddis/bin/caddis_run.py" <script.py> [args...]
|
|
5
|
+
|
|
6
|
+
Why it exists: Claude Code expands `${CLAUDE_PLUGIN_ROOT}` to a folder with the plugin version in its name
|
|
7
|
+
(`~/.claude/plugins/cache/caddis/caddis/1.3.165/`). A restart prompt, relay or restart sheet that copies that
|
|
8
|
+
expanded path fails after the next update, because the old version folder is gone. Text that a LATER session reads
|
|
9
|
+
names this launcher instead. The SessionStart hook keeps the copy in `~/.caddis/bin/` fresh (`install_launcher`).
|
|
10
|
+
|
|
11
|
+
The launcher finds the install in `~/.claude/plugins/installed_plugins.json` (key `caddis@caddis`), else the highest
|
|
12
|
+
version folder under `~/.claude/plugins/cache/caddis/caddis/`. It runs `<install>/scripts/<script.py>` with the
|
|
13
|
+
same Python, and passes stdout, stderr and the exit code through.
|
|
14
|
+
|
|
15
|
+
Exit codes: the script's own; 2 = bad usage or a script name that is not a bare `.py` file name; 3 = no caddis
|
|
16
|
+
install found, or the script is not in it.
|
|
17
|
+
|
|
18
|
+
Standard library only. This file is copied alone to `~/.caddis/bin/`: it imports no sibling script.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import subprocess
|
|
26
|
+
import sys
|
|
27
|
+
import tempfile
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
EXIT_USAGE, EXIT_NOT_FOUND = 2, 3
|
|
31
|
+
PLUGIN_KEY = "caddis@caddis"
|
|
32
|
+
LAUNCHER_NAME = "caddis_run.py"
|
|
33
|
+
|
|
34
|
+
# A path into the versioned plugin cache: `.../plugins/cache/caddis/caddis/1.3.165/...`. Gone after the next update.
|
|
35
|
+
VERSIONED_PATH = re.compile(r"[/\\]caddis[/\\]caddis[/\\]\d")
|
|
36
|
+
VERSIONED_PATH_HELP = ("it names a versioned plugin path (.../caddis/caddis/<version>/...), which breaks at the next "
|
|
37
|
+
f'update: write python "<home>/.caddis/bin/{LAUNCHER_NAME}" <script> ... instead')
|
|
38
|
+
|
|
39
|
+
_BARE_PY = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]*\.py")
|
|
40
|
+
_VERSION = re.compile(r"\d+(\.\d+)*")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def valid_script_name(name: str) -> bool:
|
|
44
|
+
"""A bare file name ending `.py`: no folder part, no `..`, no drive, no space."""
|
|
45
|
+
return bool(_BARE_PY.fullmatch(name)) and ".." not in name
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _install_paths(home: Path) -> list[Path]:
|
|
49
|
+
"""The `installPath` values of `caddis@caddis` in installed_plugins.json: a list of entries or one object."""
|
|
50
|
+
try:
|
|
51
|
+
data = json.loads((home / ".claude" / "plugins" / "installed_plugins.json").read_text(encoding="utf-8"))
|
|
52
|
+
except (OSError, ValueError):
|
|
53
|
+
return []
|
|
54
|
+
if not isinstance(data, dict):
|
|
55
|
+
return []
|
|
56
|
+
plugins = data.get("plugins", data)
|
|
57
|
+
entry = plugins.get(PLUGIN_KEY) if isinstance(plugins, dict) else None
|
|
58
|
+
entries = entry if isinstance(entry, list) else [entry]
|
|
59
|
+
return [Path(e["installPath"]) for e in entries if isinstance(e, dict) and isinstance(e.get("installPath"), str)]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _cache_dir(home: Path) -> Path:
|
|
63
|
+
return home / ".claude" / "plugins" / "cache" / "caddis" / "caddis"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _newest_cached(home: Path) -> Path | None:
|
|
67
|
+
"""The version folder with the highest version, compared as tuples of ints (1.3.99 < 1.3.172)."""
|
|
68
|
+
try:
|
|
69
|
+
found = [(tuple(int(p) for p in d.name.split(".")), d) for d in _cache_dir(home).iterdir()
|
|
70
|
+
if d.is_dir() and _VERSION.fullmatch(d.name) and (d / "scripts").is_dir()]
|
|
71
|
+
except OSError:
|
|
72
|
+
return None
|
|
73
|
+
return max(found, key=lambda pair: pair[0])[1] if found else None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def find_install(home: Path) -> Path | None:
|
|
77
|
+
"""The installed caddis plugin folder, or None."""
|
|
78
|
+
for path in _install_paths(home):
|
|
79
|
+
if (path / "scripts").is_dir():
|
|
80
|
+
return path
|
|
81
|
+
return _newest_cached(home)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def main(argv: list[str], home: Path | None = None) -> int:
|
|
85
|
+
home = home or Path.home()
|
|
86
|
+
if not argv:
|
|
87
|
+
sys.stderr.write(f'usage: python "<home>/.caddis/bin/{LAUNCHER_NAME}" <script.py> [args...]\n')
|
|
88
|
+
return EXIT_USAGE
|
|
89
|
+
name, rest = argv[0], argv[1:]
|
|
90
|
+
if not valid_script_name(name):
|
|
91
|
+
sys.stderr.write(f"{LAUNCHER_NAME}: the script must be a bare file name that ends .py (no folder, no ..): {name!r}\n")
|
|
92
|
+
return EXIT_USAGE
|
|
93
|
+
install = find_install(home)
|
|
94
|
+
if install is None:
|
|
95
|
+
sys.stderr.write(f"{LAUNCHER_NAME}: no caddis plugin found: looked for key {PLUGIN_KEY} in "
|
|
96
|
+
f"{home / '.claude' / 'plugins' / 'installed_plugins.json'} and for a version folder in "
|
|
97
|
+
f"{_cache_dir(home)}\n")
|
|
98
|
+
return EXIT_NOT_FOUND
|
|
99
|
+
script = install / "scripts" / name
|
|
100
|
+
if not script.is_file():
|
|
101
|
+
sys.stderr.write(f"{LAUNCHER_NAME}: {name} is not in {install / 'scripts'}\n")
|
|
102
|
+
return EXIT_NOT_FOUND
|
|
103
|
+
return subprocess.call([sys.executable, str(script), *rest])
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# -- the stable text, and the copy that keeps the launcher fresh -------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _base(home: Path | None) -> Path:
|
|
110
|
+
"""`~` for the launcher copy: the `home` argument beats CADDIS_HOME, which beats the user's home folder
|
|
111
|
+
(the rule of caddis_created.py and setup_project_ai.py: a test or sandbox points CADDIS_HOME at a temp folder)."""
|
|
112
|
+
return Path(home) if home else Path(os.environ.get("CADDIS_HOME") or Path.home())
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def launcher_path(home: Path | None = None) -> Path:
|
|
116
|
+
return _base(home) / ".caddis" / "bin" / LAUNCHER_NAME
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def stable_prefix(home: Path | None = None) -> str:
|
|
120
|
+
"""`python "<home>/.caddis/bin/caddis_run.py"`: put a bare script name and its arguments after it."""
|
|
121
|
+
return f'python "{launcher_path(home).as_posix()}"'
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def stable_command(script: str, home: Path | None = None) -> str:
|
|
125
|
+
"""`python "<home>/.caddis/bin/caddis_run.py" <script>`: the form for TEXT THAT A LATER SESSION READS.
|
|
126
|
+
Forward slashes, so the same text works in bash and PowerShell. Machine-local on purpose."""
|
|
127
|
+
if not valid_script_name(script):
|
|
128
|
+
raise ValueError(f"not a bare .py file name: {script!r}")
|
|
129
|
+
return f"{stable_prefix(home)} {script}"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def install_launcher(src: str | os.PathLike, home: Path | None = None) -> bool:
|
|
133
|
+
"""Copy `src` to `~/.caddis/bin/caddis_run.py` when the content differs. True when it wrote.
|
|
134
|
+
|
|
135
|
+
A temp file in the same folder, then os.replace: a reader never sees a half-written launcher. Raises on error;
|
|
136
|
+
the SessionStart hook catches it, because a launcher that cannot be refreshed must never stop a session."""
|
|
137
|
+
data = Path(src).read_bytes()
|
|
138
|
+
dest = launcher_path(home)
|
|
139
|
+
try:
|
|
140
|
+
if dest.read_bytes() == data:
|
|
141
|
+
return False
|
|
142
|
+
except OSError:
|
|
143
|
+
pass
|
|
144
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
145
|
+
fd, tmp = tempfile.mkstemp(dir=dest.parent, prefix=".caddis_run-", suffix=".tmp")
|
|
146
|
+
try:
|
|
147
|
+
with os.fdopen(fd, "wb") as fh:
|
|
148
|
+
fh.write(data)
|
|
149
|
+
os.replace(tmp, dest)
|
|
150
|
+
except BaseException:
|
|
151
|
+
try:
|
|
152
|
+
os.unlink(tmp)
|
|
153
|
+
except OSError:
|
|
154
|
+
pass
|
|
155
|
+
raise
|
|
156
|
+
return True
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
if __name__ == "__main__":
|
|
160
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -39,6 +39,14 @@ import time
|
|
|
39
39
|
from dataclasses import dataclass, field
|
|
40
40
|
from pathlib import Path
|
|
41
41
|
|
|
42
|
+
try:
|
|
43
|
+
import caddis_run # VERSIONED_PATH: a handover never names a versioned plugin path
|
|
44
|
+
except ModuleNotFoundError as _exc:
|
|
45
|
+
if _exc.name != "caddis_run":
|
|
46
|
+
raise
|
|
47
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
48
|
+
import caddis_run
|
|
49
|
+
|
|
42
50
|
if hasattr(sys.stdout, "reconfigure"):
|
|
43
51
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
44
52
|
|
|
@@ -110,9 +118,13 @@ class DocFindings:
|
|
|
110
118
|
# different. A stale hash is an accident the successor will notice; a stored answer key
|
|
111
119
|
# defeats the exercise SILENTLY — it certifies a reader who understood nothing.
|
|
112
120
|
answer_key: list[tuple[int, str]] = field(default_factory=list)
|
|
121
|
+
# A path into the versioned plugin cache. The successor reads the handover after an update, when that
|
|
122
|
+
# folder is gone: the command fails with "can't open file". Refusing, so the author fixes it now.
|
|
123
|
+
versioned_paths: list[tuple[int, str]] = field(default_factory=list)
|
|
113
124
|
|
|
114
125
|
def ok(self) -> bool:
|
|
115
|
-
return not self.stale_prone and not self.missing_paths and not self.answer_key
|
|
126
|
+
return (not self.stale_prone and not self.missing_paths and not self.answer_key
|
|
127
|
+
and not self.versioned_paths)
|
|
116
128
|
|
|
117
129
|
|
|
118
130
|
# ── answer-key detection ────────────────────────────────────────────────────────────────────
|
|
@@ -184,6 +196,8 @@ def check_document(text: str, repo_root: Path | None = None) -> DocFindings:
|
|
|
184
196
|
if _INLINE_ANSWER.search(line):
|
|
185
197
|
out.answer_key.append((n, "a question and its answer on one line. The questions may "
|
|
186
198
|
"ship; the answers may not"))
|
|
199
|
+
if caddis_run.VERSIONED_PATH.search(line): # a fence does not exempt it: a command in a fence is the case
|
|
200
|
+
out.versioned_paths.append((n, caddis_run.VERSIONED_PATH_HELP))
|
|
187
201
|
if _is_exempt(line, in_fence):
|
|
188
202
|
continue
|
|
189
203
|
for m in _HASH.finditer(line):
|
|
@@ -915,6 +929,8 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
915
929
|
sys.stderr.write(f"[spawn] {doc.name} FAILS round 0:\n")
|
|
916
930
|
for n, msg in f.answer_key:
|
|
917
931
|
sys.stderr.write(f" line {n}: ANSWER KEY — {msg}" + chr(10))
|
|
932
|
+
for n, msg in f.versioned_paths:
|
|
933
|
+
sys.stderr.write(f" line {n}: {msg}\n")
|
|
918
934
|
for n, msg in f.stale_prone:
|
|
919
935
|
sys.stderr.write(f" line {n}: {msg}\n")
|
|
920
936
|
for p_ in f.missing_paths:
|
|
@@ -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:
|