@caddis/cli 0.4.87 → 0.4.89
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 +46 -0
- package/bundles/antigravity-plugin/agents/preflight.md +4 -0
- package/bundles/antigravity-plugin/plugin.json +1 -1
- 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_fleet.py +28 -6
- package/bundles/antigravity-plugin/scripts/caddis_guide.json +2418 -0
- package/bundles/antigravity-plugin/scripts/caddis_handoff.py +370 -0
- package/bundles/antigravity-plugin/scripts/caddis_heartbeat.py +339 -0
- package/bundles/antigravity-plugin/scripts/caddis_hub_collect.py +60 -9
- package/bundles/antigravity-plugin/scripts/caddis_routing.py +36 -0
- package/bundles/antigravity-plugin/scripts/caddis_todo.py +101 -12
- package/bundles/antigravity-plugin/scripts/schemas/hub-collect.schema.json +46 -0
- package/bundles/antigravity-plugin/scripts/schemas/hub-plans.schema.json +27 -0
- package/bundles/antigravity-plugin/session_end_agy.py +26 -1
- package/bundles/antigravity-plugin/skills/coordinate/SKILL.md +5 -3
- package/bundles/antigravity-plugin/skills/feature-plan/SKILL.md +47 -19
- package/bundles/antigravity-plugin/skills/fleet-open/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/handoff/SKILL.md +77 -6
- package/bundles/antigravity-plugin/skills/implement/SKILL.md +67 -5
- package/bundles/antigravity-plugin/warm_start_agy.py +29 -1
- package/bundles/manifest.json +2 -2
- package/dist/allowed-urls.txt +3 -2
- package/dist/cli.js +545 -274
- package/dist/export/assets/export-B7BBDg5I.js +150 -0
- package/dist/export/assets/export-HxTgj3z2.css +1 -0
- package/dist/export/assets/mark-anim-DZa95SHo.webp +0 -0
- package/dist/export/assets/mark-still-CcPgBc_-.png +0 -0
- package/dist/export/fonts/ibm-plex-mono-400.6d569bb7.woff2 +0 -0
- package/dist/export/fonts/ibm-plex-mono-700.9f478677.woff2 +0 -0
- package/dist/export/fonts/ibm-plex-sans-400.17fc1ce7.woff2 +0 -0
- package/dist/export/fonts/ibm-plex-sans-500.dcc69acf.woff2 +0 -0
- package/dist/export/fonts/ibm-plex-sans-600.d4dad061.woff2 +0 -0
- package/dist/export/fonts/ibm-plex-sans-700.40d9a530.woff2 +0 -0
- package/dist/export/index.html +2 -2
- package/dist/export/licenses/{OFL-MapleMono.txt → OFL-IBMPlexMono.txt} +4 -4
- package/dist/{ui/licenses/OFL-MapleMono.txt → export/licenses/OFL-IBMPlexSans.txt} +4 -4
- package/dist/ui/assets/{Activity-BgqFFOv1.js → Activity-DZKPMOeV.js} +1 -1
- package/dist/ui/assets/Guide-5ZFfL6sl.js +9 -0
- package/dist/ui/assets/Guide-Dnsb-TRd.css +1 -0
- package/dist/ui/assets/RoadmapTab-DPsiSmIF.js +31 -0
- package/dist/ui/assets/index-DGlNAmeA.css +1 -0
- package/dist/ui/assets/index-xl156OCN.js +231 -0
- package/dist/ui/assets/mark-anim-DZa95SHo.webp +0 -0
- package/dist/ui/assets/mark-still-CcPgBc_-.png +0 -0
- package/dist/ui/fonts/ibm-plex-mono-400.6d569bb7.woff2 +0 -0
- package/dist/ui/fonts/ibm-plex-mono-700.9f478677.woff2 +0 -0
- package/dist/ui/fonts/ibm-plex-sans-400.17fc1ce7.woff2 +0 -0
- package/dist/ui/fonts/ibm-plex-sans-500.dcc69acf.woff2 +0 -0
- package/dist/ui/fonts/ibm-plex-sans-600.d4dad061.woff2 +0 -0
- package/dist/ui/fonts/ibm-plex-sans-700.40d9a530.woff2 +0 -0
- package/dist/ui/index.html +2 -2
- package/dist/{export/licenses/OFL-Atkinson.txt → ui/licenses/OFL-IBMPlexMono.txt} +3 -3
- package/dist/ui/licenses/{OFL-Atkinson.txt → OFL-IBMPlexSans.txt} +3 -3
- package/package.json +4 -1
- package/dist/export/assets/export-Dro73_I7.js +0 -150
- package/dist/export/assets/export-N0paGhbL.css +0 -1
- package/dist/export/assets/mark-small-CwCIyjyC.svg +0 -8
- package/dist/export/fonts/atkinson-400.849ae6f0.woff2 +0 -0
- package/dist/export/fonts/atkinson-700.3a9cc18a.woff2 +0 -0
- package/dist/export/fonts/maple-mono-400.071799fd.woff2 +0 -0
- package/dist/export/fonts/maple-mono-700.1e17b237.woff2 +0 -0
- package/dist/ui/assets/Guide-Df0Kg8wI.js +0 -9
- package/dist/ui/assets/Guide-zcVFGUxR.css +0 -1
- package/dist/ui/assets/RoadmapTab-CV7WCGBL.js +0 -31
- package/dist/ui/assets/index-DEge93wH.css +0 -1
- package/dist/ui/assets/index-DQbpiY2a.js +0 -221
- package/dist/ui/assets/mark-small-CwCIyjyC.svg +0 -8
- package/dist/ui/fonts/atkinson-400.849ae6f0.woff2 +0 -0
- package/dist/ui/fonts/atkinson-700.3a9cc18a.woff2 +0 -0
- package/dist/ui/fonts/maple-mono-400.071799fd.woff2 +0 -0
- package/dist/ui/fonts/maple-mono-700.1e17b237.woff2 +0 -0
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
"""One small heartbeat file per live session, so `caddis doctor` can name sessions on an old caddis.
|
|
2
|
+
|
|
3
|
+
WHY (robustness audit #18, 18 Oct 2026). A plugin update reaches only NEW sessions. A session that
|
|
4
|
+
started before the update keeps the old hooks and the old guard until it restarts (or runs
|
|
5
|
+
/reload-plugins), and nothing on the machine said which sessions those were. Each SessionStart (and
|
|
6
|
+
PreCompact) now writes `~/.caddis/sessions/<session-id>.json`:
|
|
7
|
+
|
|
8
|
+
{"session_id", "harness", "caddis_version", "pid", "started", "last_seen"}
|
|
9
|
+
|
|
10
|
+
`caddis doctor` reads the folder and lists the live sessions whose version is older than the installed one.
|
|
11
|
+
|
|
12
|
+
STATUS BEATS (26 Oct 2026). The caddis hub lists live sessions. Claude Code sessions come from
|
|
13
|
+
`claude agents --json`; any other agent (agy today) writes a STATUS beat into the same folder. It is the
|
|
14
|
+
same file with more keys, so `caddis doctor` still reads it:
|
|
15
|
+
|
|
16
|
+
{..., "status": "working" | "waiting", "status_since", "cwd", "repo_path", "waiting_for"}
|
|
17
|
+
|
|
18
|
+
`pid` may be null when the agent process cannot be found; such an entry expires by time only
|
|
19
|
+
(NO_PID_STALE_AFTER_S). `agy_beat` is the agy adapter: the PreInvocation hook writes `working`, the
|
|
20
|
+
Stop hook writes `waiting`. The format is documented in cli/README.md (the `caddis hub` section).
|
|
21
|
+
|
|
22
|
+
RULES
|
|
23
|
+
- Atomic: a temp file in the same folder, then os.replace. A reader never sees half a file.
|
|
24
|
+
- Cheap expiry: every beat prunes the entries whose pid is dead or whose last_seen is older than
|
|
25
|
+
STALE_AFTER_S (a pid reused by another program after a long time). No subprocess: the pid check is
|
|
26
|
+
OpenProcess on Windows and kill(pid, 0) elsewhere.
|
|
27
|
+
- Fail open: every public function catches its own errors. A heartbeat must never break a session start.
|
|
28
|
+
- `CADDIS_HOME` moves the home folder (tests and sandboxes); `CADDIS_HEARTBEAT=0` turns the writes off.
|
|
29
|
+
"""
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import json
|
|
33
|
+
import os
|
|
34
|
+
import re
|
|
35
|
+
import sys
|
|
36
|
+
import tempfile
|
|
37
|
+
import time
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
from typing import Callable
|
|
40
|
+
|
|
41
|
+
STALE_AFTER_S = 7 * 86400 # also used by the CLI doctor (cli/src/util/sessions.ts); keep the two equal
|
|
42
|
+
# An entry with no pid cannot be checked for life, so it expires sooner. The hub drops it at the same age
|
|
43
|
+
# (AGENT_DROP_AFTER_MS in cli/src/hub/sources/beats.ts); keep the two equal.
|
|
44
|
+
NO_PID_STALE_AFTER_S = 86400
|
|
45
|
+
STATUSES = ("working", "waiting")
|
|
46
|
+
# How many parents agent_pid() climbs: hook <- shell <- agent is the deep case; this leaves room.
|
|
47
|
+
_MAX_ANCESTORS = 8
|
|
48
|
+
_SAFE_ID = re.compile(r"[^A-Za-z0-9._-]")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def sessions_dir(home: "str | Path | None" = None) -> Path:
|
|
52
|
+
root = Path(home) if home else Path(os.environ.get("CADDIS_HOME") or Path.home())
|
|
53
|
+
return root / ".caddis" / "sessions"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def enabled() -> bool:
|
|
57
|
+
return os.environ.get("CADDIS_HEARTBEAT", "1").strip() != "0"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def plugin_version(plugin_root: "str | Path | None") -> "str | None":
|
|
61
|
+
"""The caddis version of the plugin this hook runs from, or None when it cannot be read."""
|
|
62
|
+
if not plugin_root:
|
|
63
|
+
return None
|
|
64
|
+
root = Path(plugin_root)
|
|
65
|
+
for manifest in (root / ".claude-plugin" / "plugin.json", root / "plugin.json"):
|
|
66
|
+
try:
|
|
67
|
+
version = json.loads(manifest.read_text(encoding="utf-8")).get("version")
|
|
68
|
+
except (OSError, ValueError, AttributeError):
|
|
69
|
+
continue
|
|
70
|
+
if isinstance(version, str) and version:
|
|
71
|
+
return version
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def session_pid() -> int:
|
|
76
|
+
"""The pid of the agent process. Claude Code exports CLAUDE_PID; otherwise the hook's parent."""
|
|
77
|
+
raw = os.environ.get("CLAUDE_PID", "").strip()
|
|
78
|
+
if raw.isdigit() and int(raw) > 0:
|
|
79
|
+
return int(raw)
|
|
80
|
+
return os.getppid()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def pid_alive(pid: int) -> bool:
|
|
84
|
+
if not isinstance(pid, int) or pid <= 0:
|
|
85
|
+
return False
|
|
86
|
+
if sys.platform == "win32":
|
|
87
|
+
import ctypes
|
|
88
|
+
from ctypes import wintypes
|
|
89
|
+
|
|
90
|
+
k = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
91
|
+
k.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
|
|
92
|
+
k.OpenProcess.restype = wintypes.HANDLE
|
|
93
|
+
k.GetExitCodeProcess.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD))
|
|
94
|
+
k.GetExitCodeProcess.restype = wintypes.BOOL
|
|
95
|
+
k.CloseHandle.argtypes = (wintypes.HANDLE,)
|
|
96
|
+
handle = k.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
|
|
97
|
+
if not handle:
|
|
98
|
+
return ctypes.get_last_error() == 5 # ERROR_ACCESS_DENIED: it exists, this user may not open it
|
|
99
|
+
try:
|
|
100
|
+
code = wintypes.DWORD()
|
|
101
|
+
return bool(k.GetExitCodeProcess(handle, ctypes.byref(code))) and code.value == 259 # STILL_ACTIVE
|
|
102
|
+
finally:
|
|
103
|
+
k.CloseHandle(handle)
|
|
104
|
+
try:
|
|
105
|
+
os.kill(pid, 0)
|
|
106
|
+
except ProcessLookupError:
|
|
107
|
+
return False
|
|
108
|
+
except PermissionError:
|
|
109
|
+
return True
|
|
110
|
+
except OSError:
|
|
111
|
+
return False
|
|
112
|
+
return True
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _read(path: Path) -> "dict | None":
|
|
116
|
+
try:
|
|
117
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
118
|
+
except (OSError, ValueError):
|
|
119
|
+
return None
|
|
120
|
+
return data if isinstance(data, dict) else None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _is_live(entry: "dict | None", now: float, alive: Callable[[int], bool]) -> bool:
|
|
124
|
+
if not entry:
|
|
125
|
+
return False
|
|
126
|
+
try:
|
|
127
|
+
last_seen = float(entry.get("last_seen", 0))
|
|
128
|
+
if entry.get("pid") is None and entry.get("status") in STATUSES:
|
|
129
|
+
return now - last_seen <= NO_PID_STALE_AFTER_S
|
|
130
|
+
pid = int(entry.get("pid", 0))
|
|
131
|
+
except (TypeError, ValueError):
|
|
132
|
+
return False
|
|
133
|
+
return now - last_seen <= STALE_AFTER_S and alive(pid)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def repo_top(cwd: "str | None") -> "str | None":
|
|
137
|
+
"""The folder that holds `.git` (a dir, or a worktree's file) at or above `cwd`. No subprocess, no network."""
|
|
138
|
+
if not cwd:
|
|
139
|
+
return None
|
|
140
|
+
try:
|
|
141
|
+
here = Path(cwd).resolve()
|
|
142
|
+
for folder in (here, *here.parents):
|
|
143
|
+
if (folder / ".git").exists():
|
|
144
|
+
return str(folder)
|
|
145
|
+
except (OSError, ValueError):
|
|
146
|
+
return None
|
|
147
|
+
return None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _process_table() -> "dict[int, tuple[int, str]]":
|
|
151
|
+
"""pid -> (parent pid, image name, lowercase). Windows: one Toolhelp snapshot; Linux: /proc. Else empty."""
|
|
152
|
+
table: dict[int, tuple[int, str]] = {}
|
|
153
|
+
if sys.platform == "win32":
|
|
154
|
+
import ctypes
|
|
155
|
+
from ctypes import wintypes
|
|
156
|
+
|
|
157
|
+
class _Entry(ctypes.Structure):
|
|
158
|
+
_fields_ = [("dwSize", wintypes.DWORD), ("cntUsage", wintypes.DWORD),
|
|
159
|
+
("th32ProcessID", wintypes.DWORD), ("th32DefaultHeapID", ctypes.c_size_t),
|
|
160
|
+
("th32ModuleID", wintypes.DWORD), ("cntThreads", wintypes.DWORD),
|
|
161
|
+
("th32ParentProcessID", wintypes.DWORD), ("pcPriClassBase", ctypes.c_long),
|
|
162
|
+
("dwFlags", wintypes.DWORD), ("szExeFile", ctypes.c_wchar * 260)]
|
|
163
|
+
|
|
164
|
+
k = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
165
|
+
k.CreateToolhelp32Snapshot.argtypes = (wintypes.DWORD, wintypes.DWORD)
|
|
166
|
+
k.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
|
|
167
|
+
k.Process32FirstW.argtypes = (wintypes.HANDLE, ctypes.POINTER(_Entry))
|
|
168
|
+
k.Process32FirstW.restype = wintypes.BOOL
|
|
169
|
+
k.Process32NextW.argtypes = (wintypes.HANDLE, ctypes.POINTER(_Entry))
|
|
170
|
+
k.Process32NextW.restype = wintypes.BOOL
|
|
171
|
+
k.CloseHandle.argtypes = (wintypes.HANDLE,)
|
|
172
|
+
snap = k.CreateToolhelp32Snapshot(0x2, 0) # TH32CS_SNAPPROCESS
|
|
173
|
+
if not snap or snap == ctypes.c_void_p(-1).value:
|
|
174
|
+
return table
|
|
175
|
+
try:
|
|
176
|
+
entry = _Entry()
|
|
177
|
+
entry.dwSize = ctypes.sizeof(_Entry)
|
|
178
|
+
more = k.Process32FirstW(snap, ctypes.byref(entry))
|
|
179
|
+
while more:
|
|
180
|
+
table[int(entry.th32ProcessID)] = (int(entry.th32ParentProcessID), entry.szExeFile.lower())
|
|
181
|
+
more = k.Process32NextW(snap, ctypes.byref(entry))
|
|
182
|
+
finally:
|
|
183
|
+
k.CloseHandle(snap)
|
|
184
|
+
return table
|
|
185
|
+
proc = Path("/proc")
|
|
186
|
+
if not proc.is_dir():
|
|
187
|
+
return table
|
|
188
|
+
pid = os.getpid() # only this process's own chain: a few small reads, not the whole table
|
|
189
|
+
for _ in range(_MAX_ANCESTORS + 1):
|
|
190
|
+
try:
|
|
191
|
+
stat = (proc / str(pid) / "stat").read_text(encoding="utf-8", errors="replace")
|
|
192
|
+
name = stat[stat.index("(") + 1:stat.rindex(")")].lower()
|
|
193
|
+
ppid = int(stat[stat.rindex(")") + 2:].split()[1])
|
|
194
|
+
except (OSError, ValueError, IndexError):
|
|
195
|
+
break
|
|
196
|
+
table[pid] = (ppid, name)
|
|
197
|
+
if ppid <= 0:
|
|
198
|
+
break
|
|
199
|
+
pid = ppid
|
|
200
|
+
return table
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def agent_pid(image: str, start: "int | None" = None,
|
|
204
|
+
table: "dict[int, tuple[int, str]] | None" = None) -> "int | None":
|
|
205
|
+
"""The pid of the nearest ancestor whose image is `image` (or `image`.exe), else None. Never raises.
|
|
206
|
+
|
|
207
|
+
A hook's parent may be a short-lived shell, so the parent pid alone would look dead at once. Climbing to
|
|
208
|
+
the agent's own process gives the hub a pid that lives as long as the session's window.
|
|
209
|
+
"""
|
|
210
|
+
try:
|
|
211
|
+
want = {image.lower(), image.lower() + ".exe"}
|
|
212
|
+
table = _process_table() if table is None else table
|
|
213
|
+
pid = os.getpid() if start is None else start
|
|
214
|
+
for _ in range(_MAX_ANCESTORS):
|
|
215
|
+
row = table.get(pid)
|
|
216
|
+
if row is None:
|
|
217
|
+
return None
|
|
218
|
+
ppid = row[0]
|
|
219
|
+
parent = table.get(ppid)
|
|
220
|
+
if parent is None or ppid == pid:
|
|
221
|
+
return None
|
|
222
|
+
if parent[1] in want:
|
|
223
|
+
return ppid
|
|
224
|
+
pid = ppid
|
|
225
|
+
except Exception:
|
|
226
|
+
return None
|
|
227
|
+
return None
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def beat(session_id: str, version: "str | None", harness: str, pid: "int | None" = None,
|
|
231
|
+
home: "str | Path | None" = None, now: "float | None" = None, *, status: "str | None" = None,
|
|
232
|
+
cwd: "str | None" = None, waiting_for: "str | None" = None) -> "Path | None":
|
|
233
|
+
"""Write (or refresh) this session's heartbeat. Returns its path, or None when nothing was written.
|
|
234
|
+
|
|
235
|
+
Without `status` this is the Claude Code heartbeat, and `pid=None` means "this session's pid". With
|
|
236
|
+
`status` (one of STATUSES) it is a status beat for the hub: `pid=None` stays null (unknown), and the
|
|
237
|
+
status keys are added.
|
|
238
|
+
"""
|
|
239
|
+
try:
|
|
240
|
+
if not session_id or not enabled():
|
|
241
|
+
return None
|
|
242
|
+
if status is not None and status not in STATUSES:
|
|
243
|
+
return None
|
|
244
|
+
now = time.time() if now is None else now
|
|
245
|
+
if pid is None and status is None:
|
|
246
|
+
pid = session_pid()
|
|
247
|
+
folder = sessions_dir(home)
|
|
248
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
249
|
+
target = folder / (_SAFE_ID.sub("_", session_id)[:120] + ".json")
|
|
250
|
+
old = _read(target)
|
|
251
|
+
started = old.get("started") if old and old.get("pid") == pid else None
|
|
252
|
+
entry = {"session_id": session_id, "harness": harness, "caddis_version": version, "pid": pid,
|
|
253
|
+
"started": started if isinstance(started, (int, float)) else now, "last_seen": now}
|
|
254
|
+
if status is not None:
|
|
255
|
+
since = old.get("status_since") if old and old.get("status") == status else None
|
|
256
|
+
entry.update({"status": status, "status_since": since if isinstance(since, (int, float)) else now,
|
|
257
|
+
"cwd": cwd or None, "repo_path": repo_top(cwd),
|
|
258
|
+
"waiting_for": waiting_for if status == "waiting" else None})
|
|
259
|
+
fd, tmp = tempfile.mkstemp(dir=str(folder), prefix=".hb-", suffix=".tmp")
|
|
260
|
+
try:
|
|
261
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
262
|
+
json.dump(entry, fh)
|
|
263
|
+
os.replace(tmp, target)
|
|
264
|
+
except BaseException:
|
|
265
|
+
try:
|
|
266
|
+
os.unlink(tmp)
|
|
267
|
+
except OSError:
|
|
268
|
+
pass
|
|
269
|
+
raise
|
|
270
|
+
prune(home=home, now=now, keep=target)
|
|
271
|
+
return target
|
|
272
|
+
except Exception:
|
|
273
|
+
return None
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
_AGY_WAITING_FOR = {"max_steps_exceeded": "step limit reached", "error": "an error to be read"}
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def agy_beat(data: object, status: str, home: "str | Path | None" = None, now: "float | None" = None,
|
|
280
|
+
plugin_root: "str | Path | None" = None) -> "Path | None":
|
|
281
|
+
"""The agy adapter: write a status beat from an agy hook payload. Never raises.
|
|
282
|
+
|
|
283
|
+
agy's payload (camelCase) gives `conversationId` and `workspacePaths`; the hook's own cwd is the plugin
|
|
284
|
+
folder, so it is never used as the session's folder. With no id, the id is stable per agy process.
|
|
285
|
+
"""
|
|
286
|
+
try:
|
|
287
|
+
data = data if isinstance(data, dict) else {}
|
|
288
|
+
pid = agent_pid("agy")
|
|
289
|
+
conv = data.get("conversationId")
|
|
290
|
+
session_id = conv.strip() if isinstance(conv, str) and conv.strip() else f"agy-{pid or os.getppid()}"
|
|
291
|
+
roots = data.get("workspacePaths")
|
|
292
|
+
roots = [r for r in roots if isinstance(r, str) and r.strip()] if isinstance(roots, list) else []
|
|
293
|
+
reason = data.get("terminationReason")
|
|
294
|
+
waiting_for = _AGY_WAITING_FOR.get(reason, "input needed") if isinstance(reason, str) else "input needed"
|
|
295
|
+
return beat(session_id, plugin_version(plugin_root), "agy", pid=pid, home=home, now=now,
|
|
296
|
+
status=status, cwd=roots[0] if roots else None, waiting_for=waiting_for)
|
|
297
|
+
except Exception:
|
|
298
|
+
return None
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def prune(home: "str | Path | None" = None, now: "float | None" = None,
|
|
302
|
+
alive: Callable[[int], bool] = pid_alive, keep: "Path | None" = None) -> int:
|
|
303
|
+
"""Remove dead or stale heartbeats (and temp files older than an hour). Returns how many went."""
|
|
304
|
+
removed = 0
|
|
305
|
+
try:
|
|
306
|
+
now = time.time() if now is None else now
|
|
307
|
+
for path in sessions_dir(home).iterdir():
|
|
308
|
+
if keep is not None and path == keep:
|
|
309
|
+
continue
|
|
310
|
+
try:
|
|
311
|
+
if path.name.startswith(".hb-"):
|
|
312
|
+
gone = now - path.stat().st_mtime > 3600
|
|
313
|
+
elif path.suffix == ".json":
|
|
314
|
+
gone = not _is_live(_read(path), now, alive)
|
|
315
|
+
else:
|
|
316
|
+
continue
|
|
317
|
+
if gone:
|
|
318
|
+
path.unlink()
|
|
319
|
+
removed += 1
|
|
320
|
+
except OSError:
|
|
321
|
+
continue
|
|
322
|
+
except OSError:
|
|
323
|
+
pass
|
|
324
|
+
return removed
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def live(home: "str | Path | None" = None, now: "float | None" = None,
|
|
328
|
+
alive: Callable[[int], bool] = pid_alive) -> list[dict]:
|
|
329
|
+
"""The live heartbeats, oldest start first. Read-only."""
|
|
330
|
+
now = time.time() if now is None else now
|
|
331
|
+
out = []
|
|
332
|
+
try:
|
|
333
|
+
for path in sessions_dir(home).glob("*.json"):
|
|
334
|
+
entry = _read(path)
|
|
335
|
+
if _is_live(entry, now, alive):
|
|
336
|
+
out.append(entry)
|
|
337
|
+
except OSError:
|
|
338
|
+
return []
|
|
339
|
+
return sorted(out, key=lambda e: e.get("started") or 0)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
"""Batched hub collector: every repo's roadmaps, plans and relays, plus agy spend and the guide, as one JSON object.
|
|
3
3
|
|
|
4
|
-
Usage: caddis_hub_collect.py --repos PATH [PATH ...] [--only roadmaps,plans,relays,spend,guide] --json
|
|
4
|
+
Usage: caddis_hub_collect.py --repos PATH [PATH ...] [--only roadmaps,plans,relays,spend,guide] [--known PATH=FP ...] --json
|
|
5
5
|
|
|
6
6
|
The hub runs this once per cycle. It runs in ONE Python process for all repos (hub rule R15, spawn cost L8). It
|
|
7
7
|
never calls gh, claude or agy, and never runs `git fetch`: the roadmap reader sees the origin refs the repo
|
|
@@ -63,6 +63,13 @@ def _local_origin_branches(common: Path) -> list[str]:
|
|
|
63
63
|
if (common / "refs" / "remotes" / "origin" / name).is_file() or f"refs/remotes/origin/{name}" in packed_refs]
|
|
64
64
|
|
|
65
65
|
|
|
66
|
+
def _fetch_time(common: Path) -> int | None:
|
|
67
|
+
try:
|
|
68
|
+
return int((common / "FETCH_HEAD").stat().st_mtime)
|
|
69
|
+
except OSError:
|
|
70
|
+
return None
|
|
71
|
+
|
|
72
|
+
|
|
66
73
|
def _plans_json(root: Path) -> dict:
|
|
67
74
|
"""Plans from the origin ref the repo already has (R15: local git only), so a pushed Tracker edit shows with no
|
|
68
75
|
pull. A folder that is not a git checkout, or has no origin default branch, reads the working tree."""
|
|
@@ -88,7 +95,10 @@ def _plans_json(root: Path) -> dict:
|
|
|
88
95
|
branch = None
|
|
89
96
|
finally:
|
|
90
97
|
roadmap.FETCH = saved
|
|
91
|
-
|
|
98
|
+
out = _sibling("caddis_todo").plans_json(root, branch=branch)
|
|
99
|
+
if common is not None and isinstance(out, dict):
|
|
100
|
+
out["fetched_at"] = _fetch_time(common)
|
|
101
|
+
return out
|
|
92
102
|
|
|
93
103
|
|
|
94
104
|
def _relays_json(root: Path) -> dict:
|
|
@@ -99,8 +109,30 @@ def _spend_json() -> dict:
|
|
|
99
109
|
return _sibling("caddis_spend").spend_json(Path.home())
|
|
100
110
|
|
|
101
111
|
|
|
112
|
+
# An installed bundle has no source pool to scan: the export writes the guide data beside this script.
|
|
113
|
+
GUIDE_DATA = Path(__file__).resolve().parent / "caddis_guide.json"
|
|
114
|
+
|
|
115
|
+
|
|
102
116
|
def _guide_json() -> dict:
|
|
103
|
-
|
|
117
|
+
"""The guide data file of an install, else build_reference in a source checkout."""
|
|
118
|
+
try:
|
|
119
|
+
text = GUIDE_DATA.read_text(encoding="utf-8")
|
|
120
|
+
except FileNotFoundError:
|
|
121
|
+
text = None
|
|
122
|
+
if text is not None:
|
|
123
|
+
data = json.loads(text)
|
|
124
|
+
if not isinstance(data, dict):
|
|
125
|
+
raise ValueError(f"{GUIDE_DATA.name} is not a JSON object")
|
|
126
|
+
return data
|
|
127
|
+
try:
|
|
128
|
+
module = _sibling("build_reference")
|
|
129
|
+
except ModuleNotFoundError as exc:
|
|
130
|
+
if exc.name != "build_reference":
|
|
131
|
+
raise
|
|
132
|
+
raise RuntimeError(
|
|
133
|
+
f"the guide data is missing from this install: no {GUIDE_DATA.name} beside {Path(__file__).name}"
|
|
134
|
+
) from None
|
|
135
|
+
return module.guide_json()
|
|
104
136
|
|
|
105
137
|
|
|
106
138
|
_REPO_COLLECTORS = {"roadmaps": _roadmaps_json, "plans": _plans_json, "relays": _relays_json}
|
|
@@ -176,8 +208,8 @@ def git_common_dir(repo: Path) -> Path | None:
|
|
|
176
208
|
|
|
177
209
|
|
|
178
210
|
def _origin_ref_files(common: Path) -> list[Path]:
|
|
179
|
-
"""The ref files the roadmap reader gets its data from: packed-refs, origin/HEAD, every origin branch."""
|
|
180
|
-
files = [p for p in (common / "packed-refs",) if p.is_file() and not _is_link(p)]
|
|
211
|
+
"""The ref files the roadmap reader gets its data from: packed-refs, FETCH_HEAD, origin/HEAD, every origin branch."""
|
|
212
|
+
files = [p for p in (common / "packed-refs", common / "FETCH_HEAD") if p.is_file() and not _is_link(p)]
|
|
181
213
|
# refs/remotes/origin/HEAD sits inside refs/remotes/origin/, so the walk covers it.
|
|
182
214
|
return files + _files(common / "refs" / "remotes" / "origin", recurse=True)
|
|
183
215
|
|
|
@@ -207,7 +239,19 @@ def fingerprint(repo: Path) -> str:
|
|
|
207
239
|
return hashlib.sha256(json.dumps(sorted(rows)).encode("utf-8")).hexdigest()
|
|
208
240
|
|
|
209
241
|
|
|
210
|
-
def
|
|
242
|
+
def parse_known(values: list[str]) -> dict[str, str]:
|
|
243
|
+
known: dict[str, str] = {}
|
|
244
|
+
for value in values:
|
|
245
|
+
if "=" not in value:
|
|
246
|
+
raise ValueError(f"bad --known value: {value}")
|
|
247
|
+
path, fp = value.rsplit("=", 1)
|
|
248
|
+
if not path or not fp:
|
|
249
|
+
raise ValueError(f"bad --known value: {value}")
|
|
250
|
+
known[path] = fp
|
|
251
|
+
return known
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def collect_repo(path: str, kinds: tuple[str, ...], known: dict[str, str] | None = None) -> dict:
|
|
211
255
|
repo = Path(path)
|
|
212
256
|
if not repo.is_dir():
|
|
213
257
|
return {"path": path, "error": "not a folder"}
|
|
@@ -216,6 +260,8 @@ def collect_repo(path: str, kinds: tuple[str, ...]) -> dict:
|
|
|
216
260
|
entry["fingerprint"] = fingerprint(repo)
|
|
217
261
|
except Exception as exc: # a repo we cannot read must not stop the others
|
|
218
262
|
return {"path": path, **_error(exc)}
|
|
263
|
+
if known and known.get(path) == entry["fingerprint"]:
|
|
264
|
+
return {**entry, "unchanged": True}
|
|
219
265
|
for kind in _REPO_KINDS:
|
|
220
266
|
if kind not in kinds:
|
|
221
267
|
continue
|
|
@@ -226,9 +272,9 @@ def collect_repo(path: str, kinds: tuple[str, ...]) -> dict:
|
|
|
226
272
|
return entry
|
|
227
273
|
|
|
228
274
|
|
|
229
|
-
def collect(repos: list[str], kinds: tuple[str, ...]) -> dict:
|
|
275
|
+
def collect(repos: list[str], kinds: tuple[str, ...], known: dict[str, str] | None = None) -> dict:
|
|
230
276
|
out: dict = {"schema": SCHEMA, "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
231
|
-
"repos": [collect_repo(path, kinds) for path in repos]}
|
|
277
|
+
"repos": [collect_repo(path, kinds, known) for path in repos]}
|
|
232
278
|
for kind, call in (("spend", _spend_json), ("guide", _guide_json)):
|
|
233
279
|
if kind not in kinds:
|
|
234
280
|
continue
|
|
@@ -253,13 +299,18 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
253
299
|
parser = _Parser(description=__doc__.splitlines()[0])
|
|
254
300
|
parser.add_argument("--repos", nargs="+", required=True, metavar="PATH")
|
|
255
301
|
parser.add_argument("--only", default=",".join(KINDS), help="comma list of: " + ", ".join(KINDS))
|
|
302
|
+
parser.add_argument("--known", nargs="+", default=[], metavar="PATH=FP")
|
|
256
303
|
parser.add_argument("--json", action="store_true", required=True)
|
|
257
304
|
args = parser.parse_args(argv)
|
|
258
305
|
kinds = tuple(k.strip() for k in args.only.split(",") if k.strip())
|
|
259
306
|
unknown = [k for k in kinds if k not in KINDS]
|
|
260
307
|
if unknown or not kinds:
|
|
261
308
|
parser.error(f"unknown --only kind: {', '.join(unknown) or '(empty)'}; use {', '.join(KINDS)}")
|
|
262
|
-
|
|
309
|
+
try:
|
|
310
|
+
known = parse_known(args.known)
|
|
311
|
+
except ValueError as exc:
|
|
312
|
+
parser.error(str(exc))
|
|
313
|
+
print(json.dumps(collect(args.repos, kinds, known), ensure_ascii=False))
|
|
263
314
|
return 0
|
|
264
315
|
|
|
265
316
|
|
|
@@ -29,6 +29,33 @@ DEFAULT_ROUTING: dict[str, list[str]] = {
|
|
|
29
29
|
}
|
|
30
30
|
KNOWN_MODELS = frozenset({"opus", "sonnet", "haiku", "agy", "codex", "glm", "deepseek", "claude"})
|
|
31
31
|
|
|
32
|
+
# One session model+effort table (owner, 27 Oct; .caddis/plans/context-handoff-strategy.md Phase 7). handoff,
|
|
33
|
+
# coordinate and implement read it; DEFAULT_ROUTING and `show` stay as they are. `orchestrator` stays high until
|
|
34
|
+
# Phase 9 measures it; `measure` is for measurement and screenshot subagents. Review is not a row: it goes by tier
|
|
35
|
+
# (`caddis_gate.py review-tier`).
|
|
36
|
+
SESSION_DEFAULTS: dict[str, tuple[str, str]] = {
|
|
37
|
+
"orchestrator": ("sonnet", "high"),
|
|
38
|
+
"plan-writer": ("opus", "high"),
|
|
39
|
+
"coordinator": ("sonnet", "low"),
|
|
40
|
+
"measure": ("sonnet", "medium"),
|
|
41
|
+
"critical-phase": ("opus", "medium"),
|
|
42
|
+
"coding-phase": ("agy", "medium"),
|
|
43
|
+
"mechanical-phase": ("haiku", "low"),
|
|
44
|
+
}
|
|
45
|
+
AGY_MODEL_BY_EFFORT: dict[str, str] = {"medium": "gemini-4-argon-medium", "high": "gemini-4-argon-high"}
|
|
46
|
+
CLAUDE_SESSION_MODELS = frozenset({"opus", "sonnet", "haiku"})
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def session_start(role: str) -> tuple[str, str]:
|
|
50
|
+
"""The `claude --model --effort` pair for a new session of `role`.
|
|
51
|
+
|
|
52
|
+
A start line can name only a Claude model, so a role with no Claude row (any session-name role, or
|
|
53
|
+
`coding-phase`) starts as the orchestrator."""
|
|
54
|
+
model, effort = SESSION_DEFAULTS.get(role, SESSION_DEFAULTS["orchestrator"])
|
|
55
|
+
if model not in CLAUDE_SESSION_MODELS:
|
|
56
|
+
return SESSION_DEFAULTS["orchestrator"]
|
|
57
|
+
return model, effort
|
|
58
|
+
|
|
32
59
|
|
|
33
60
|
class RoutingConfigError(Exception):
|
|
34
61
|
"""A routing file has an invalid value or cannot be parsed."""
|
|
@@ -89,8 +116,17 @@ def main(argv: list[str] | None = None, env: Mapping[str, str] | None = None) ->
|
|
|
89
116
|
show = commands.add_parser("show", help="print the resolved routing table")
|
|
90
117
|
show.add_argument("--json", action="store_true", help="print JSON")
|
|
91
118
|
show.add_argument("--repo", type=Path, default=Path.cwd(), help="repository path")
|
|
119
|
+
session = commands.add_parser("session", help="print the model and effort for a session role")
|
|
120
|
+
session.add_argument("--role", required=True, help=f"one of: {', '.join(SESSION_DEFAULTS)}")
|
|
92
121
|
args = parser.parse_args(argv)
|
|
93
122
|
|
|
123
|
+
if args.command == "session":
|
|
124
|
+
if args.role not in SESSION_DEFAULTS:
|
|
125
|
+
print(f"unknown session role {args.role!r}; known: {', '.join(SESSION_DEFAULTS)}", file=sys.stderr)
|
|
126
|
+
return 4
|
|
127
|
+
print(" ".join(SESSION_DEFAULTS[args.role]))
|
|
128
|
+
return 0
|
|
129
|
+
|
|
94
130
|
try:
|
|
95
131
|
routing = resolve(Path.home(), args.repo, env=env)
|
|
96
132
|
except RoutingConfigError as exc:
|