@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,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)
|
|
@@ -32,6 +32,14 @@ except ModuleNotFoundError as exc:
|
|
|
32
32
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "claude-harness" / "scripts"))
|
|
33
33
|
import caddis_routing
|
|
34
34
|
|
|
35
|
+
try:
|
|
36
|
+
import caddis_run # stable_command: text a later session reads never names a versioned plugin path
|
|
37
|
+
except ModuleNotFoundError as exc:
|
|
38
|
+
if exc.name != "caddis_run":
|
|
39
|
+
raise
|
|
40
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
41
|
+
import caddis_run
|
|
42
|
+
|
|
35
43
|
ACK_FIELDS = ("name", "role", "machine", "folder", "relay", "tasks", "mode", "owns-watchers", "worktrees")
|
|
36
44
|
NO_ACK = "no ack"
|
|
37
45
|
NO_NEW_SESSION = ("keeps-running", "nothing", NO_ACK)
|
|
@@ -136,6 +144,8 @@ def parse_ack(text: str) -> Ack:
|
|
|
136
144
|
after = rest[fence:]
|
|
137
145
|
body = after.split("\n", 1)[1] if "\n" in after else ""
|
|
138
146
|
prompt, inline = _split_prompt(body)
|
|
147
|
+
if caddis_run.VERSIONED_PATH.search(prompt):
|
|
148
|
+
raise AckError(f"the resume prompt: {caddis_run.VERSIONED_PATH_HELP}")
|
|
139
149
|
return Ack(
|
|
140
150
|
name=fields["name"], role=fields["role"], machine=fields["machine"], folder=fields["folder"],
|
|
141
151
|
relay=fields["relay"], tasks=fields["tasks"], mode=mode, owns_watchers=watchers == "yes",
|
|
@@ -309,6 +319,8 @@ def check_sheet(sheet_text: str, roster_text: str) -> list[str]:
|
|
|
309
319
|
errors.append(f"{role}: the resume prompt does not load {tasks}")
|
|
310
320
|
if "is now" not in prompt:
|
|
311
321
|
errors.append(f"{role}: the resume prompt does not greet peers with `is now`")
|
|
322
|
+
if caddis_run.VERSIONED_PATH.search(prompt):
|
|
323
|
+
errors.append(f"{role}: the resume prompt {caddis_run.VERSIONED_PATH_HELP}")
|
|
312
324
|
if _is_shared(r.get("Folder", ""), counts) and "origin/main" not in prompt:
|
|
313
325
|
errors.append(f"{role}: shared checkout, but the resume prompt does not say origin/main")
|
|
314
326
|
return errors
|
|
@@ -458,6 +470,8 @@ def resume_prompt(relay_text: str) -> str:
|
|
|
458
470
|
prompt = "\n".join(body).strip("\n")
|
|
459
471
|
if not prompt.strip():
|
|
460
472
|
raise ResumeError("## Resume prompt fenced block is empty")
|
|
473
|
+
if caddis_run.VERSIONED_PATH.search(prompt):
|
|
474
|
+
raise ResumeError(f"## Resume prompt: {caddis_run.VERSIONED_PATH_HELP}")
|
|
461
475
|
return prompt
|
|
462
476
|
|
|
463
477
|
|
|
@@ -471,12 +485,15 @@ def shell_arg(text: str) -> str:
|
|
|
471
485
|
ANNOUNCE_ID = "<your session id>"
|
|
472
486
|
|
|
473
487
|
|
|
474
|
-
def announce_text(
|
|
488
|
+
def announce_text(name: str, folder: str) -> str:
|
|
475
489
|
"""The sentence the start line adds, so the resumed session names itself and tells its live peers once.
|
|
476
490
|
|
|
477
|
-
A new session cannot expand `${CLAUDE_PLUGIN_ROOT}`,
|
|
478
|
-
|
|
479
|
-
|
|
491
|
+
A new session cannot expand `${CLAUDE_PLUGIN_ROOT}`, and an expanded path holds the plugin version, which is gone
|
|
492
|
+
after an update. So the command is the stable launcher (`caddis_run.py`, never a versioned path). It holds no
|
|
493
|
+
double quote (`shell_arg` turns each into a typographic one), so the launcher path is NOT quoted here: a home
|
|
494
|
+
folder with a space needs the quotes, which the owner's machine does not have. A peer without a name (`-`) is
|
|
495
|
+
not messaged."""
|
|
496
|
+
py = f"python {caddis_run.launcher_path().as_posix()} caddis_fleet.py"
|
|
480
497
|
return (f"Then announce yourself once. Run `{py} whoami --session-id {ANNOUNCE_ID} --name {name} --root .` and "
|
|
481
498
|
f"`{py} peers --session-id {ANNOUNCE_ID} --root .` (your session id is printed at session start). "
|
|
482
499
|
f"Send each peer that has a name (not `-`) one SendMessage: "
|
|
@@ -485,11 +502,11 @@ def announce_text(script: Path, name: str, folder: str) -> str:
|
|
|
485
502
|
|
|
486
503
|
|
|
487
504
|
def render_resume(session: str, session_id: str, workstream: str, prompt: str, role: str, stamp: datetime,
|
|
488
|
-
fleet_mode: bool = False,
|
|
505
|
+
fleet_mode: bool = False, announce: bool = False, folder: str = "",
|
|
489
506
|
root: Path | None = None) -> str:
|
|
490
507
|
"""The last output of `/caddis:handoff`. In a fleet close the restart sheet holds the only start line.
|
|
491
508
|
|
|
492
|
-
With `
|
|
509
|
+
With `announce`, the start line (not the fenced block, which stays the relay's text) ends with the
|
|
493
510
|
whoami + announce sentence: the start line is what the new session receives with its name.
|
|
494
511
|
With `root`, the block names the repo and the start line first changes to it, because the relay's paths are
|
|
495
512
|
repo-relative. `;`, as in the restart sheet: Windows PowerShell 5.1 has no `&&`."""
|
|
@@ -500,8 +517,8 @@ def render_resume(session: str, session_id: str, workstream: str, prompt: str, r
|
|
|
500
517
|
start = "Start line: from the restart sheet"
|
|
501
518
|
else:
|
|
502
519
|
name = new_name(role, stamp)
|
|
503
|
-
if
|
|
504
|
-
prompt = f"{prompt}\n{announce_text(
|
|
520
|
+
if announce:
|
|
521
|
+
prompt = f"{prompt}\n{announce_text(name, folder)}"
|
|
505
522
|
start = f"Start line:\n{cd}claude {_model_flags(role)} --name {name} {shell_arg(prompt)}"
|
|
506
523
|
return (f"{model_line(role)}=== RESUME ===\nSession: {session} ({session_id})\nWorkstream: {workstream}\n"
|
|
507
524
|
f"{repo}{_fenced(shown)}\n{start}\n")
|
|
@@ -580,7 +597,7 @@ def _resume_block_cli(args: argparse.Namespace) -> int:
|
|
|
580
597
|
sys.stderr.write(f"resume-block failed: bad role {role!r}\n")
|
|
581
598
|
return caddis_exit.BLOCKED
|
|
582
599
|
print(render_resume(session, args.session_id, args.name, prompt, role, datetime.now(), args.fleet,
|
|
583
|
-
|
|
600
|
+
True, root.name, root), end="")
|
|
584
601
|
return caddis_exit.CLEAN
|
|
585
602
|
|
|
586
603
|
|