@caddis/cli 0.4.88 → 0.4.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +46 -0
  2. package/bundles/antigravity-plugin/agents/preflight.md +4 -0
  3. package/bundles/antigravity-plugin/plugin.json +1 -1
  4. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
  5. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
  6. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
  7. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
  8. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
  9. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
  10. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
  11. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
  12. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
  13. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
  14. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
  15. package/bundles/antigravity-plugin/scripts/caddis_fleet.py +37 -10
  16. package/bundles/antigravity-plugin/scripts/caddis_guide.json +16 -11
  17. package/bundles/antigravity-plugin/scripts/caddis_handoff.py +370 -0
  18. package/bundles/antigravity-plugin/scripts/caddis_heartbeat.py +339 -0
  19. package/bundles/antigravity-plugin/scripts/caddis_hub_collect.py +37 -8
  20. package/bundles/antigravity-plugin/scripts/caddis_roadmap_run.py +130 -63
  21. package/bundles/antigravity-plugin/scripts/caddis_routing.py +36 -0
  22. package/bundles/antigravity-plugin/scripts/caddis_todo.py +55 -10
  23. package/bundles/antigravity-plugin/scripts/caddis_workstreams.py +35 -12
  24. package/bundles/antigravity-plugin/scripts/schemas/hub-collect.schema.json +42 -0
  25. package/bundles/antigravity-plugin/scripts/schemas/hub-plans.schema.json +23 -0
  26. package/bundles/antigravity-plugin/session_end_agy.py +26 -1
  27. package/bundles/antigravity-plugin/skills/code-review/SKILL.md +2 -0
  28. package/bundles/antigravity-plugin/skills/coordinate/SKILL.md +5 -3
  29. package/bundles/antigravity-plugin/skills/cross-review/SKILL.md +1 -0
  30. package/bundles/antigravity-plugin/skills/feature-plan/SKILL.md +47 -19
  31. package/bundles/antigravity-plugin/skills/fleet-open/SKILL.md +1 -1
  32. package/bundles/antigravity-plugin/skills/handoff/SKILL.md +82 -7
  33. package/bundles/antigravity-plugin/skills/implement/SKILL.md +86 -6
  34. package/bundles/antigravity-plugin/skills/park/SKILL.md +1 -0
  35. package/bundles/antigravity-plugin/skills/preflight/SKILL.md +1 -0
  36. package/bundles/antigravity-plugin/skills/roadmap/assets/plan-resume-prompt.md +8 -1
  37. package/bundles/antigravity-plugin/warm_start_agy.py +29 -1
  38. package/bundles/antigravity-plugin-extras/plugin.json +1 -1
  39. package/bundles/antigravity-plugin-extras/skills/cross-review/SKILL.md +1 -0
  40. package/bundles/codex/.codex/skills/coding/code-review/SKILL.md +2 -0
  41. package/bundles/codex/.codex/skills/workflow/preflight/SKILL.md +1 -0
  42. package/bundles/codex/.codex/skills/workflow/roadmap/assets/plan-resume-prompt.md +8 -1
  43. package/bundles/manifest.json +3 -3
  44. package/dist/allowed-urls.txt +3 -2
  45. package/dist/cli.js +554 -275
  46. package/dist/export/assets/export-B7BBDg5I.js +150 -0
  47. package/dist/export/assets/export-HxTgj3z2.css +1 -0
  48. package/dist/export/assets/mark-anim-DZa95SHo.webp +0 -0
  49. package/dist/export/assets/mark-still-CcPgBc_-.png +0 -0
  50. package/dist/export/fonts/ibm-plex-mono-400.6d569bb7.woff2 +0 -0
  51. package/dist/export/fonts/ibm-plex-mono-700.9f478677.woff2 +0 -0
  52. package/dist/export/fonts/ibm-plex-sans-400.17fc1ce7.woff2 +0 -0
  53. package/dist/export/fonts/ibm-plex-sans-500.dcc69acf.woff2 +0 -0
  54. package/dist/export/fonts/ibm-plex-sans-600.d4dad061.woff2 +0 -0
  55. package/dist/export/fonts/ibm-plex-sans-700.40d9a530.woff2 +0 -0
  56. package/dist/export/index.html +2 -2
  57. package/dist/export/licenses/{OFL-MapleMono.txt → OFL-IBMPlexMono.txt} +4 -4
  58. package/dist/{ui/licenses/OFL-MapleMono.txt → export/licenses/OFL-IBMPlexSans.txt} +4 -4
  59. package/dist/ui/assets/{Activity-C9TCizJV.js → Activity-DZKPMOeV.js} +1 -1
  60. package/dist/ui/assets/Guide-5ZFfL6sl.js +9 -0
  61. package/dist/ui/assets/Guide-Dnsb-TRd.css +1 -0
  62. package/dist/ui/assets/RoadmapTab-DPsiSmIF.js +31 -0
  63. package/dist/ui/assets/index-DGlNAmeA.css +1 -0
  64. package/dist/ui/assets/index-xl156OCN.js +231 -0
  65. package/dist/ui/assets/mark-anim-DZa95SHo.webp +0 -0
  66. package/dist/ui/assets/mark-still-CcPgBc_-.png +0 -0
  67. package/dist/ui/fonts/ibm-plex-mono-400.6d569bb7.woff2 +0 -0
  68. package/dist/ui/fonts/ibm-plex-mono-700.9f478677.woff2 +0 -0
  69. package/dist/ui/fonts/ibm-plex-sans-400.17fc1ce7.woff2 +0 -0
  70. package/dist/ui/fonts/ibm-plex-sans-500.dcc69acf.woff2 +0 -0
  71. package/dist/ui/fonts/ibm-plex-sans-600.d4dad061.woff2 +0 -0
  72. package/dist/ui/fonts/ibm-plex-sans-700.40d9a530.woff2 +0 -0
  73. package/dist/ui/index.html +2 -2
  74. package/dist/{export/licenses/OFL-Atkinson.txt → ui/licenses/OFL-IBMPlexMono.txt} +3 -3
  75. package/dist/ui/licenses/{OFL-Atkinson.txt → OFL-IBMPlexSans.txt} +3 -3
  76. package/package.json +4 -1
  77. package/dist/export/assets/export-CEtCs5rg.css +0 -1
  78. package/dist/export/assets/export-v-kcNvPW.js +0 -150
  79. package/dist/export/assets/mark-small-B1q4Vk3J.svg +0 -8
  80. package/dist/export/fonts/atkinson-400.849ae6f0.woff2 +0 -0
  81. package/dist/export/fonts/atkinson-500.21d6ef26.woff2 +0 -0
  82. package/dist/export/fonts/atkinson-600.ce9f3210.woff2 +0 -0
  83. package/dist/export/fonts/atkinson-700.3a9cc18a.woff2 +0 -0
  84. package/dist/export/fonts/maple-mono-400.071799fd.woff2 +0 -0
  85. package/dist/export/fonts/maple-mono-700.1e17b237.woff2 +0 -0
  86. package/dist/ui/assets/Guide-6aEYW9oW.js +0 -9
  87. package/dist/ui/assets/Guide-zcVFGUxR.css +0 -1
  88. package/dist/ui/assets/RoadmapTab-hUK2kzCW.js +0 -31
  89. package/dist/ui/assets/index-DE7v-v_o.css +0 -1
  90. package/dist/ui/assets/index-d44hkSAE.js +0 -221
  91. package/dist/ui/assets/mark-small-B1q4Vk3J.svg +0 -8
  92. package/dist/ui/fonts/atkinson-400.849ae6f0.woff2 +0 -0
  93. package/dist/ui/fonts/atkinson-500.21d6ef26.woff2 +0 -0
  94. package/dist/ui/fonts/atkinson-600.ce9f3210.woff2 +0 -0
  95. package/dist/ui/fonts/atkinson-700.3a9cc18a.woff2 +0 -0
  96. package/dist/ui/fonts/maple-mono-400.071799fd.woff2 +0 -0
  97. 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
- return _sibling("caddis_todo").plans_json(root, branch=branch)
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:
@@ -198,8 +208,8 @@ def git_common_dir(repo: Path) -> Path | None:
198
208
 
199
209
 
200
210
  def _origin_ref_files(common: Path) -> list[Path]:
201
- """The ref files the roadmap reader gets its data from: packed-refs, origin/HEAD, every origin branch."""
202
- 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)]
203
213
  # refs/remotes/origin/HEAD sits inside refs/remotes/origin/, so the walk covers it.
204
214
  return files + _files(common / "refs" / "remotes" / "origin", recurse=True)
205
215
 
@@ -229,7 +239,19 @@ def fingerprint(repo: Path) -> str:
229
239
  return hashlib.sha256(json.dumps(sorted(rows)).encode("utf-8")).hexdigest()
230
240
 
231
241
 
232
- def collect_repo(path: str, kinds: tuple[str, ...]) -> dict:
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:
233
255
  repo = Path(path)
234
256
  if not repo.is_dir():
235
257
  return {"path": path, "error": "not a folder"}
@@ -238,6 +260,8 @@ def collect_repo(path: str, kinds: tuple[str, ...]) -> dict:
238
260
  entry["fingerprint"] = fingerprint(repo)
239
261
  except Exception as exc: # a repo we cannot read must not stop the others
240
262
  return {"path": path, **_error(exc)}
263
+ if known and known.get(path) == entry["fingerprint"]:
264
+ return {**entry, "unchanged": True}
241
265
  for kind in _REPO_KINDS:
242
266
  if kind not in kinds:
243
267
  continue
@@ -248,9 +272,9 @@ def collect_repo(path: str, kinds: tuple[str, ...]) -> dict:
248
272
  return entry
249
273
 
250
274
 
251
- 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:
252
276
  out: dict = {"schema": SCHEMA, "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
253
- "repos": [collect_repo(path, kinds) for path in repos]}
277
+ "repos": [collect_repo(path, kinds, known) for path in repos]}
254
278
  for kind, call in (("spend", _spend_json), ("guide", _guide_json)):
255
279
  if kind not in kinds:
256
280
  continue
@@ -275,13 +299,18 @@ def main(argv: list[str] | None = None) -> int:
275
299
  parser = _Parser(description=__doc__.splitlines()[0])
276
300
  parser.add_argument("--repos", nargs="+", required=True, metavar="PATH")
277
301
  parser.add_argument("--only", default=",".join(KINDS), help="comma list of: " + ", ".join(KINDS))
302
+ parser.add_argument("--known", nargs="+", default=[], metavar="PATH=FP")
278
303
  parser.add_argument("--json", action="store_true", required=True)
279
304
  args = parser.parse_args(argv)
280
305
  kinds = tuple(k.strip() for k in args.only.split(",") if k.strip())
281
306
  unknown = [k for k in kinds if k not in KINDS]
282
307
  if unknown or not kinds:
283
308
  parser.error(f"unknown --only kind: {', '.join(unknown) or '(empty)'}; use {', '.join(KINDS)}")
284
- print(json.dumps(collect(args.repos, kinds), ensure_ascii=False))
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))
285
314
  return 0
286
315
 
287
316