@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.
Files changed (99) hide show
  1. package/README.md +4 -0
  2. package/bundles/antigravity-plugin/agents/debug.md +2 -0
  3. package/bundles/antigravity-plugin/guard_agy.py +6 -2
  4. package/bundles/antigravity-plugin/plugin.json +1 -1
  5. package/bundles/antigravity-plugin/repo_freshness.py +71 -6
  6. package/bundles/antigravity-plugin/repo_hygiene.py +516 -0
  7. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
  8. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
  9. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
  10. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
  11. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
  12. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
  13. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
  14. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
  15. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
  16. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
  17. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
  18. package/bundles/antigravity-plugin/scripts/caddis_checkout_guard.py +1 -1
  19. package/bundles/antigravity-plugin/scripts/caddis_finished.py +537 -0
  20. package/bundles/antigravity-plugin/scripts/caddis_fleet.py +26 -9
  21. package/bundles/antigravity-plugin/scripts/caddis_guide.json +65 -12
  22. package/bundles/antigravity-plugin/scripts/caddis_own_cleanup.py +23 -248
  23. package/bundles/antigravity-plugin/scripts/caddis_preload_review.py +554 -0
  24. package/bundles/antigravity-plugin/scripts/caddis_repo_tidy.py +240 -0
  25. package/bundles/antigravity-plugin/scripts/caddis_roadmap_run.py +9 -3
  26. package/bundles/antigravity-plugin/scripts/caddis_run.py +160 -0
  27. package/bundles/antigravity-plugin/scripts/caddis_spawn.py +17 -1
  28. package/bundles/antigravity-plugin/scripts/caddis_tidy.py +12 -0
  29. package/bundles/antigravity-plugin/scripts/caddis_upstream_check.py +108 -10
  30. package/bundles/antigravity-plugin/scripts/caddis_worktree_root.py +111 -2
  31. package/bundles/antigravity-plugin/scripts/setup_project_ai.py +132 -11
  32. package/bundles/antigravity-plugin/skills/_registry.md +7 -5
  33. package/bundles/antigravity-plugin/skills/adopt-app/SKILL.md +2 -5
  34. package/bundles/antigravity-plugin/skills/brainstorming/SKILL.md +232 -40
  35. package/bundles/antigravity-plugin/skills/brainstorming/builder-check-prompt.md +25 -0
  36. package/bundles/antigravity-plugin/skills/cloud-phases/SKILL.md +1 -1
  37. package/bundles/antigravity-plugin/skills/dashboard-perf-sweep/SKILL.md +1 -1
  38. package/bundles/antigravity-plugin/skills/db-diagram/SKILL.md +1 -1
  39. package/bundles/antigravity-plugin/skills/explainer-doc/SKILL.md +1 -1
  40. package/bundles/antigravity-plugin/skills/feature-plan/SKILL.md +7 -1
  41. package/bundles/antigravity-plugin/skills/fleet-close/SKILL.md +4 -1
  42. package/bundles/antigravity-plugin/skills/graph-email/SKILL.md +15 -0
  43. package/bundles/antigravity-plugin/skills/handoff/SKILL.md +9 -2
  44. package/bundles/antigravity-plugin/skills/implement/SKILL.md +7 -0
  45. package/bundles/antigravity-plugin/skills/particle-art/SKILL.md +1 -3
  46. package/bundles/antigravity-plugin/skills/port-to-github/SKILL.md +2 -5
  47. package/bundles/antigravity-plugin/skills/pr-merge/SKILL.md +1 -1
  48. package/bundles/antigravity-plugin/skills/preload-review/SKILL.md +69 -0
  49. package/bundles/antigravity-plugin/skills/roadmap/SKILL.md +4 -0
  50. package/bundles/antigravity-plugin/skills/roadmap/assets/plan-resume-prompt.md +6 -5
  51. package/bundles/antigravity-plugin/skills/ship-merge/SKILL.md +1 -1
  52. package/bundles/antigravity-plugin/skills/ship-pr/SKILL.md +1 -1
  53. package/bundles/antigravity-plugin/skills/spawn-session/SKILL.md +5 -0
  54. package/bundles/antigravity-plugin/skills/tdd/SKILL.md +2 -1
  55. package/bundles/antigravity-plugin/skills/tech-explainer/SKILL.md +2 -6
  56. package/bundles/antigravity-plugin/skills/usage-review/SKILL.md +2 -0
  57. package/bundles/antigravity-plugin/skills/using-git-worktrees/SKILL.md +19 -2
  58. package/bundles/antigravity-plugin/skills/warm-editorial-ui/SKILL.md +1 -1
  59. package/bundles/antigravity-plugin-extras/plugin.json +1 -1
  60. package/bundles/antigravity-plugin-extras/skills/_registry.md +3 -2
  61. package/bundles/antigravity-plugin-extras/skills/building-ai-agent-on-cloudflare/SKILL.md +1 -2
  62. package/bundles/antigravity-plugin-extras/skills/building-mcp-server-on-cloudflare/SKILL.md +1 -2
  63. package/bundles/antigravity-plugin-extras/skills/data-contract-pipeline/SKILL.md +1 -1
  64. package/bundles/antigravity-plugin-extras/skills/graph-email/SKILL.md +53 -0
  65. package/bundles/antigravity-plugin-extras/skills/graph-email/email.toml.example +44 -0
  66. package/bundles/antigravity-plugin-extras/skills/graph-email/scripts/send_email.py +432 -0
  67. package/bundles/antigravity-plugin-extras/skills/responsive-mobile-native/SKILL.md +2 -4
  68. package/bundles/antigravity-plugin-extras/skills/runner-move/SKILL.md +2 -4
  69. package/bundles/antigravity-plugin-extras/skills/setup-project-ai/SKILL.md +1 -1
  70. package/bundles/antigravity-plugin-extras/skills/understand-anything/SKILL.md +2 -5
  71. package/bundles/codex/.codex/skills/coding/dashboard-perf-sweep/SKILL.md +1 -1
  72. package/bundles/codex/.codex/skills/data/db-diagram/SKILL.md +1 -1
  73. package/bundles/codex/.codex/skills/devops/adopt-app/SKILL.md +2 -5
  74. package/bundles/codex/.codex/skills/devops/port-to-github/SKILL.md +2 -5
  75. package/bundles/codex/.codex/skills/devops/using-git-worktrees/SKILL.md +19 -2
  76. package/bundles/codex/.codex/skills/docs/explainer-doc/SKILL.md +1 -1
  77. package/bundles/codex/.codex/skills/docs/tech-explainer/SKILL.md +2 -6
  78. package/bundles/codex/.codex/skills/frontend/warm-editorial-ui/SKILL.md +1 -1
  79. package/bundles/codex/.codex/skills/media/particle-art/SKILL.md +1 -3
  80. package/bundles/codex/.codex/skills/workflow/brainstorming/SKILL.md +232 -40
  81. package/bundles/codex/.codex/skills/workflow/brainstorming/builder-check-prompt.md +25 -0
  82. package/bundles/codex/.codex/skills/workflow/roadmap/SKILL.md +4 -0
  83. package/bundles/codex/.codex/skills/workflow/roadmap/assets/plan-resume-prompt.md +6 -5
  84. package/bundles/manifest.json +3 -3
  85. package/dist/export/assets/export-CMtV-slT.css +1 -0
  86. package/dist/export/index.html +2 -2
  87. package/dist/ui/assets/{Activity-DZKPMOeV.js → Activity-BDjet2xd.js} +1 -1
  88. package/dist/ui/assets/Guide-Czn5sK0f.js +9 -0
  89. package/dist/ui/assets/Guide-D-Zy4cUT.css +1 -0
  90. package/dist/ui/assets/{RoadmapTab-DPsiSmIF.js → RoadmapTab-Bd8geyQx.js} +1 -1
  91. package/dist/ui/assets/index-Bd0Z4jR8.css +1 -0
  92. package/dist/ui/assets/{index-xl156OCN.js → index-CmngQ8Mk.js} +12 -12
  93. package/dist/ui/index.html +2 -2
  94. package/package.json +1 -1
  95. package/dist/export/assets/export-HxTgj3z2.css +0 -1
  96. package/dist/ui/assets/Guide-5ZFfL6sl.js +0 -9
  97. package/dist/ui/assets/Guide-Dnsb-TRd.css +0 -1
  98. package/dist/ui/assets/index-DGlNAmeA.css +0 -1
  99. /package/dist/export/assets/{export-B7BBDg5I.js → export-DtlDFN4L.js} +0 -0
@@ -0,0 +1,516 @@
1
+ """The session-start hygiene report: worktrees, branches, uncommitted work and the pre-push gate, in ONE line.
2
+
3
+ Plan: `.caddis/plans/repo-hygiene-report.md` (Phase 3). `repo_freshness._report` calls `report_lines()`, so Claude
4
+ Code, Codex and agy all get the report through one function, one process and one time budget.
5
+
6
+ REPORT ONLY. Nothing here deletes, moves or changes anything. The one file it writes is the gh cache
7
+ `<git-common-dir>/caddis-hygiene-prs.json`. Removal is `caddis_tidy.py --hygiene --apply`, which re-proves every
8
+ candidate with the deletion-grade test in `caddis_finished.py`.
9
+
10
+ Every decision lives in `caddis_finished.py` (stdlib only). This module holds the I/O and the formatting. Every git
11
+ call goes through the `git(cwd, *args) -> (code, stdout)` seam (`repo_freshness._git` in the hook). gh and orca go
12
+ through a `subprocess.run`-shaped seam that never opens a console window.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ import time
22
+ from collections.abc import Callable, Mapping
23
+ from concurrent.futures import Future, ThreadPoolExecutor
24
+ from pathlib import Path
25
+ from typing import NamedTuple
26
+
27
+
28
+ def _import_finished():
29
+ """`caddis_finished`, probed beside this hook: plugin layout, agy flat layout, then the source tree (D1)."""
30
+ here = Path(__file__).resolve().parent
31
+ for cand in (here.parent / "scripts", here / "scripts", here.parent.parent / "scripts"):
32
+ if (cand / "caddis_finished.py").is_file():
33
+ if str(cand) not in sys.path:
34
+ sys.path.append(str(cand))
35
+ try:
36
+ import caddis_finished
37
+ except (ImportError, SyntaxError, OSError): # a broken file must not crash a session start
38
+ return None
39
+ return caddis_finished
40
+ return None
41
+
42
+
43
+ cf = _import_finished()
44
+
45
+ ScanResult = tuple[list[dict], int, int]
46
+ SCAN_STOP_S = 4.0 # the scan of other repos stops when fewer seconds than this are left
47
+ PR_CACHE_NAME = "caddis-hygiene-prs.json"
48
+ PR_CACHE_MAX_AGE_S = 600 # the same as repo_freshness.FETCH_MAX_AGE_S
49
+ GH_FIELDS = "headRefName,state,number,headRefOid"
50
+ GH_TIMEOUT_S = 5.0 # the most gh may take; less when less of the session-start budget is left
51
+ ORCA_TIMEOUT_S = 3.0 # the same for orca
52
+ NO_TIME_LEFT = "no time left in the session-start budget"
53
+
54
+ # No child opens a console window on Windows; git never takes an optional lock or asks for a credential.
55
+ _NO_WINDOW = 0x08000000 if os.name == "nt" else 0
56
+ _ENV_OVERRIDES = {"GIT_OPTIONAL_LOCKS": "0", "GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never"}
57
+
58
+
59
+ def _key(path: str | os.PathLike) -> str:
60
+ """One spelling for a path: resolved, case-folded and back-slashed on Windows (git and Orca write `E:/x`)."""
61
+ return os.path.normcase(os.path.realpath(str(path)))
62
+
63
+
64
+ # ---- roots and the cheap scan (Task 3.1) -----------------------------------------------------------------------
65
+
66
+ def _common_dir(top: Path, git: Callable) -> Path | None:
67
+ code, out = git(str(top), "rev-parse", "--path-format=absolute", "--git-common-dir")
68
+ return Path(out) if code == 0 and out else None
69
+
70
+
71
+ def main_checkout(top: Path, git: Callable) -> Path:
72
+ """The main checkout of the repo that holds `top`: the parent of `--git-common-dir`. `top` when git fails."""
73
+ common = _common_dir(top, git)
74
+ return common.parent if common is not None else top
75
+
76
+
77
+ def _config_roots(home: Path) -> list[str]:
78
+ """`[hygiene] roots` from `<home>/.caddis/config.toml`, else []. A missing or bad file is just no config."""
79
+ path = home / ".caddis" / "config.toml"
80
+ try:
81
+ import tomllib
82
+ except ImportError: # Python < 3.11
83
+ return []
84
+ try:
85
+ with open(path, "rb") as fh:
86
+ data = tomllib.load(fh)
87
+ except (OSError, ValueError):
88
+ return []
89
+ roots = data.get("hygiene", {}).get("roots", []) if isinstance(data.get("hygiene"), dict) else []
90
+ return [r for r in roots if isinstance(r, str)] if isinstance(roots, list) else []
91
+
92
+
93
+ def resolve_roots(current_top: Path | None, env: Mapping[str, str], home: Path) -> list[Path]:
94
+ """The folders whose direct children are scanned for repos (decision 6).
95
+
96
+ `CADDIS_FLEET_ROOTS` (`;`-separated) > `<home>/.caddis/config.toml` `[hygiene] roots` > the parent of the
97
+ current repo's main checkout plus `<home>/Documents` when it exists. Duplicates (by case and slash form) go.
98
+ """
99
+ raw = [p.strip() for p in env.get("CADDIS_FLEET_ROOTS", "").split(";") if p.strip()]
100
+ if not raw:
101
+ raw = [p.strip() for p in _config_roots(home) if p.strip()]
102
+ if raw:
103
+ roots = [Path(p) for p in raw]
104
+ else:
105
+ roots = [current_top.parent] if current_top is not None else []
106
+ if (home / "Documents").is_dir():
107
+ roots.append(home / "Documents")
108
+ seen: set[str] = set()
109
+ unique: list[Path] = []
110
+ for root in roots:
111
+ k = _key(root)
112
+ if k not in seen:
113
+ seen.add(k)
114
+ unique.append(root)
115
+ return unique
116
+
117
+
118
+ def _repos_under(roots: list[Path], exclude: Path | None) -> list[Path]:
119
+ """Direct children of the roots whose `.git` is a DIRECTORY (a `.git` file is a linked worktree), sorted."""
120
+ skip = {_key(exclude)} if exclude is not None else set()
121
+ repos: list[Path] = []
122
+ for root in roots:
123
+ try:
124
+ children = sorted(p for p in Path(root).iterdir() if p.is_dir())
125
+ except OSError:
126
+ continue
127
+ for child in children:
128
+ k = _key(child)
129
+ if k in skip or not (child / ".git").is_dir():
130
+ continue
131
+ skip.add(k)
132
+ repos.append(child)
133
+ return repos
134
+
135
+
136
+ def _worktree_records(repo: Path, git: Callable) -> list[dict]:
137
+ """`git worktree list --porcelain` of one repo, parsed; the first record is the main working tree."""
138
+ code, out = git(str(repo), "worktree", "list", "--porcelain")
139
+ return cf.parse_worktree_porcelain(out) if code == 0 else []
140
+
141
+
142
+ def _classify(repo_name: str, linked: list[dict], git: Callable) -> list[dict]:
143
+ """One finding per linked worktree record, classified by `caddis_finished.worktree_state`."""
144
+ findings = []
145
+ for rec in linked:
146
+ exists = Path(rec["path"]).is_dir()
147
+ dirty = False
148
+ if exists:
149
+ s_code, s_out = git(rec["path"], "--no-optional-locks", "status", "--porcelain")
150
+ dirty = s_code != 0 or bool(s_out) # git failed: unknown is treated as dirty (the keep side)
151
+ session = cf.session_id_from_path(rec["path"])
152
+ idle = cf.session_idle_minutes(session) if session else -1
153
+ findings.append({"repo": repo_name, "path": rec["path"], "branch": rec["branch"],
154
+ "state": cf.worktree_state(exists, dirty, session is not None, idle),
155
+ "session": session, "idle": idle})
156
+ return findings
157
+
158
+
159
+ def _scan_repo(repo: Path, git_dir: Path, git: Callable) -> list[dict]:
160
+ """The linked worktrees of one repo, classified. No git spawn when git records no linked worktree."""
161
+ if not cf.has_linked_worktrees(git_dir):
162
+ return []
163
+ return _classify(repo.name, _worktree_records(repo, git)[1:], git)
164
+
165
+
166
+ def scan_repos(roots: list[Path], exclude: Path | None, git: Callable,
167
+ remaining: Callable[[], float]) -> ScanResult:
168
+ """The cheap worktree scan of every repo under the roots except `exclude`: (findings, scanned, not_scanned).
169
+
170
+ It stops when fewer than SCAN_STOP_S seconds of the budget are left; the repos it did not reach are counted.
171
+ """
172
+ findings: list[dict] = []
173
+ repos = _repos_under(roots, exclude)
174
+ for i, repo in enumerate(repos):
175
+ if remaining() < SCAN_STOP_S:
176
+ return findings, i, len(repos) - i
177
+ findings.extend(_scan_repo(repo, repo / ".git", git))
178
+ return findings, len(repos), 0
179
+
180
+
181
+ # ---- gh and Orca (Task 3.2) -------------------------------------------------------------------------------------
182
+
183
+ def _run(argv: list[str], timeout: float | None = None, cwd: str | None = None) -> subprocess.CompletedProcess:
184
+ """The default `subprocess.run`-shaped seam. Raises FileNotFoundError when the program is not on PATH and
185
+ subprocess.TimeoutExpired on a timeout; the callers turn both into a skip reason."""
186
+ exe = shutil.which(argv[0])
187
+ if exe is None:
188
+ raise FileNotFoundError(argv[0])
189
+ return subprocess.run([exe, *argv[1:]], cwd=cwd, capture_output=True, text=True, encoding="utf-8",
190
+ errors="replace", timeout=timeout, stdin=subprocess.DEVNULL, check=False,
191
+ env={**os.environ, **_ENV_OVERRIDES}, creationflags=_NO_WINDOW)
192
+
193
+
194
+ def _last_line(proc: subprocess.CompletedProcess, name: str) -> str:
195
+ text = (proc.stderr or proc.stdout or "").strip()
196
+ return text.splitlines()[-1].strip() if text else f"{name} exited {proc.returncode}"
197
+
198
+
199
+ def _read_cache(path: Path, now: float) -> list[dict] | None:
200
+ try:
201
+ data = json.loads(path.read_text(encoding="utf-8"))
202
+ except (OSError, ValueError):
203
+ return None
204
+ if not isinstance(data, dict) or not isinstance(data.get("prs"), list):
205
+ return None
206
+ ts = data.get("ts")
207
+ if not isinstance(ts, (int, float)) or not 0 <= now - ts < PR_CACHE_MAX_AGE_S:
208
+ return None
209
+ return data["prs"]
210
+
211
+
212
+ def fetch_prs(top: Path, git_dir: Path, run: Callable, now: float,
213
+ timeout_s: float = GH_TIMEOUT_S) -> tuple[list[dict] | None, str]:
214
+ """The last 200 PRs of the current repo from ONE gh call, cached in `<git_dir>/caddis-hygiene-prs.json` for
215
+ 600 s. (prs, "") or (None, reason). The cache is read first, so a fresh cache answers with no process at all.
216
+ """
217
+ cache = Path(git_dir) / PR_CACHE_NAME
218
+ cached = _read_cache(cache, now)
219
+ if cached is not None:
220
+ return cached, ""
221
+ try:
222
+ origin = run(["git", "-C", str(top), "remote", "get-url", "origin"], timeout=timeout_s)
223
+ except (OSError, subprocess.SubprocessError):
224
+ return None, "could not read the origin URL"
225
+ slug = cf.slug_from_url(origin.stdout.strip() if origin.returncode == 0 else "")
226
+ if not slug:
227
+ return None, "origin is not a GitHub repo"
228
+ argv = ["gh", "pr", "list", "--repo", slug, "--state", "all", "--limit", "200", "--json", GH_FIELDS]
229
+ try:
230
+ proc = run(argv, timeout=timeout_s, cwd=str(top))
231
+ except FileNotFoundError:
232
+ return None, "gh not on PATH"
233
+ except subprocess.TimeoutExpired:
234
+ return None, f"gh took longer than {timeout_s:g} s"
235
+ except (OSError, subprocess.SubprocessError) as exc:
236
+ return None, f"gh could not start: {exc}"
237
+ if proc.returncode != 0:
238
+ return None, _last_line(proc, "gh")
239
+ try:
240
+ prs = json.loads(proc.stdout)
241
+ except ValueError:
242
+ return None, "gh returned unreadable JSON"
243
+ if not isinstance(prs, list):
244
+ return None, "gh returned unreadable JSON"
245
+ try:
246
+ cache.write_text(json.dumps({"ts": now, "prs": prs}), encoding="utf-8")
247
+ except OSError:
248
+ pass # no cache this time: the next session start asks gh again
249
+ return prs, ""
250
+
251
+
252
+ def orca_worktrees(run: Callable, which: Callable, timeout_s: float = ORCA_TIMEOUT_S) -> tuple[dict[str, str] | None, str]:
253
+ """Every path Orca manages -> its Orca id, keyed by `_key(path)`. (None, reason) when Orca cannot answer
254
+ completely: not on PATH, a non-zero exit, a timeout, bad JSON, `ok` false, or `result.truncated` true."""
255
+ exe = which("orca")
256
+ if not exe:
257
+ return None, "orca not on PATH"
258
+ try:
259
+ proc = run([exe, "worktree", "list", "--limit", "10000", "--json"], timeout=timeout_s)
260
+ except subprocess.TimeoutExpired:
261
+ return None, f"orca took longer than {timeout_s:g} s"
262
+ except (OSError, subprocess.SubprocessError) as exc:
263
+ return None, f"orca could not start: {exc}"
264
+ if proc.returncode != 0:
265
+ return None, _last_line(proc, "orca")
266
+ try:
267
+ data = json.loads(proc.stdout)
268
+ except ValueError:
269
+ return None, "orca returned unreadable JSON"
270
+ if not isinstance(data, dict) or data.get("ok") is not True:
271
+ return None, "orca answered ok=false"
272
+ result = data.get("result")
273
+ if not isinstance(result, dict) or not isinstance(result.get("worktrees"), list):
274
+ return None, "orca returned unreadable JSON"
275
+ if result.get("truncated"):
276
+ return None, "orca list is truncated"
277
+ mapping: dict[str, str] = {}
278
+ for wt in result["worktrees"]:
279
+ if isinstance(wt, dict) and wt.get("path") and wt.get("id"):
280
+ mapping[_key(wt["path"])] = str(wt["id"])
281
+ return mapping, ""
282
+
283
+
284
+ def orca_id(mapping: dict[str, str] | None, path: str) -> str | None:
285
+ """The Orca id of `path`, matched case- and slash-insensitively; None when Orca does not manage it."""
286
+ return mapping.get(_key(path)) if mapping else None
287
+
288
+
289
+ # ---- current-repo facts and the summary line (Task 3.3) ----------------------------------------------------------
290
+
291
+ _which = shutil.which
292
+ SKIP_HYGIENE = "[HARNESS] skipped: repo hygiene - caddis_finished.py not found beside this hook"
293
+ TOP_REPOS = 6
294
+ TOP_TRIAGE = 3
295
+ BUCKETS = ("merged", "DIRTY", "idle-session", "orphan", "merge not checked", "needs-triage")
296
+ _STATE_BUCKET = {"orphan-registration": "orphan", "DIRTY": "DIRTY", "idle-session": "idle-session"}
297
+
298
+
299
+ def summary_line(f: dict) -> str:
300
+ """PURE: the one line every session start prints. `[OK]` only when every field is known and level.
301
+
302
+ Unknown is never 0 (D5): a skipped gh call prints `branches ? (gh skipped)` and a scan cut short prints
303
+ `worktrees >=<n> stale (<k> repos not scanned)`; either one makes the prefix `[HARNESS]`.
304
+ """
305
+ ref = f.get("ref") or ""
306
+ parts = [f"branch '{f['branch']}'"]
307
+ parts += [f"{f['behind']} behind {ref}", f"{f['ahead']} ahead"] if ref else ["no remote"]
308
+ parts.append(f"{f['dirty']} uncommitted")
309
+ if f.get("not_scanned"):
310
+ parts.append(f"worktrees >={f['stale']} stale ({f['not_scanned']} repos not scanned)")
311
+ else:
312
+ parts.append(f"worktrees {f['stale']} stale")
313
+ if not ref:
314
+ parts.append("branches ? (no origin)")
315
+ elif f.get("gh_skipped"):
316
+ parts.append("branches ? (gh skipped)")
317
+ else:
318
+ parts.append(f"branches {f['merged']} merged-not-deleted, {f['triage']} needs-triage")
319
+ if f.get("gate_missing"):
320
+ parts.append("pre-push gate missing")
321
+ level = (ref and f["branch"] == ref.split("/", 1)[-1] and not f.get("gh_skipped") and not f.get("gate_missing")
322
+ and not any(f.get(k) for k in ("behind", "ahead", "dirty", "stale", "not_scanned", "merged", "triage")))
323
+ return ("[OK] " if level else "[HARNESS] ") + " | ".join(parts)
324
+
325
+
326
+ def _old_line(fresh: dict) -> list[str]:
327
+ """The pre-hygiene freshness line, kept when caddis_finished cannot be imported."""
328
+ ref = fresh.get("ref") or ""
329
+ if ref and (fresh["branch"] != ref.split("/", 1)[-1] or fresh["behind"] or fresh["dirty"]):
330
+ return [(f"[HARNESS] branch '{fresh['branch']}' | {fresh['behind']} behind {ref} | {fresh['ahead']} ahead "
331
+ f"| {fresh['dirty']} uncommitted")]
332
+ return []
333
+
334
+
335
+ def _local_branches(repo: Path, git: Callable) -> dict[str, tuple[str, int]]:
336
+ """{branch: (tip oid, committer unix time)} for every local branch."""
337
+ code, out = git(str(repo), "for-each-ref", "--format=%(refname:short)%09%(objectname)%09%(committerdate:unix)",
338
+ "refs/heads")
339
+ branches: dict[str, tuple[str, int]] = {}
340
+ for line in out.splitlines() if code == 0 else []:
341
+ name, _, rest = line.partition("\t")
342
+ oid, _, date = rest.partition("\t")
343
+ if name and oid:
344
+ branches[name] = (oid, int(date) if date.strip().isdigit() else 0)
345
+ return branches
346
+
347
+
348
+ def _result(future: Future | None, what: str, fallback: tuple) -> tuple:
349
+ """A future's result; a crash in the thread becomes a skip reason, never an exception at session start."""
350
+ if future is None:
351
+ return fallback
352
+ try:
353
+ return future.result()
354
+ except Exception as exc: # noqa: BLE001 - fail open: the hook must never break a session start
355
+ return None, f"{what} failed: {type(exc).__name__}"
356
+
357
+
358
+ def _prs_by_branch(prs: list[dict]) -> dict[str, list[dict]]:
359
+ """PRs grouped on headRefName, newest (highest number) first."""
360
+ grouped: dict[str, list[dict]] = {}
361
+ for pr in prs:
362
+ if isinstance(pr, dict) and pr.get("headRefName"):
363
+ grouped.setdefault(pr["headRefName"], []).append(pr)
364
+ for group in grouped.values():
365
+ group.sort(key=lambda pr: pr.get("number") or 0, reverse=True)
366
+ return grouped
367
+
368
+
369
+ def _bucket(f: dict, orca_map: dict | None, prs: dict[str, list[dict]] | None, tips: dict, is_anc: Callable,
370
+ here: bool) -> str | None:
371
+ """The stale bucket of one linked worktree, or None when it is not stale (D4): IN USE, Orca-managed, or (in the
372
+ current repo, with PRs known) its branch has an OPEN PR."""
373
+ if f["state"] == "IN USE" or orca_id(orca_map, f["path"]):
374
+ return None
375
+ branch_prs = prs.get(f["branch"], []) if here and prs is not None else []
376
+ if any(pr.get("state") == "OPEN" for pr in branch_prs):
377
+ return None
378
+ if f["state"] in _STATE_BUCKET:
379
+ return _STATE_BUCKET[f["state"]]
380
+ if not here or prs is None:
381
+ return "merge not checked"
382
+ state, _ = cf.branch_report_state(tips.get(f["branch"], ("", 0))[0], branch_prs, is_anc)
383
+ return "merged" if state == "merged-not-deleted" else "needs-triage"
384
+
385
+
386
+ def _stale_line(here: list[str], other: list[dict], home: Path, repo: Path) -> str:
387
+ counts = dict.fromkeys(BUCKETS, 0)
388
+ for b in here + [f["bucket"] for f in other]:
389
+ counts[b] += 1
390
+ where = f"{len(here)} here, {len(other)} in other repos"
391
+ if other:
392
+ groups = cf.count_by_repo(other)
393
+ listed = ", ".join(f"{name} x{n}" for name, n in groups[:TOP_REPOS])
394
+ more = f" (+{len(groups) - TOP_REPOS} more repos)" if len(groups) > TOP_REPOS else ""
395
+ where += f" ({listed}{more})"
396
+ buckets = ", ".join(f"{counts[b]} {b}" for b in BUCKETS)
397
+ return (f"[HARNESS] stale worktrees: {where}. {buckets}. List: python \"{home.as_posix()}/.caddis/bin/"
398
+ f"caddis_run.py\" caddis_tidy.py --hygiene --repo-root {repo.as_posix()}")
399
+
400
+
401
+ def _triage_line(names: list[str], repo: Path, ref: str, tips: dict, git: Callable, now: float) -> str:
402
+ shown = []
403
+ for name in names[:TOP_TRIAGE]:
404
+ code, out = git(str(repo), "rev-list", "--count", f"{ref}..{name}" if ref else name)
405
+ commits = out.strip() if code == 0 and out.strip().isdigit() else "?"
406
+ age = max(0, int((now - tips[name][1]) // 86400)) if tips[name][1] else "?"
407
+ shown.append(f"{name} ({age}d, {commits} commits)")
408
+ more = f" (+{len(names) - TOP_TRIAGE} more)" if len(names) > TOP_TRIAGE else ""
409
+ return f"[HARNESS] branches needing triage (no PR or closed): {', '.join(shown)}{more}"
410
+
411
+
412
+ class Jobs(NamedTuple):
413
+ """The current repo's main checkout, the roots, and the gh and orca threads `start_jobs` started."""
414
+ main: Path
415
+ roots: list[Path]
416
+ any_linked: bool
417
+ gh: Future | None
418
+ orca: Future | None
419
+
420
+
421
+ def _done(value: tuple) -> Future:
422
+ future: Future = Future()
423
+ future.set_result(value)
424
+ return future
425
+
426
+
427
+ def start_jobs(top: Path, git: Callable, remaining: Callable[[], float], *, want_prs: bool = True,
428
+ env: Mapping[str, str] | None = None, home: Path | None = None) -> Jobs:
429
+ """Resolve the main checkout and the roots, and start gh and orca in two threads (D8). The caller starts this
430
+ as early as it can, so the gh and orca waits overlap its own git work. Each timeout is cut to the time left in
431
+ the budget, so neither thread outlives it; with no time left neither starts and the reason is the answer.
432
+ orca is asked only when a linked worktree exists (D7)."""
433
+ if cf is None:
434
+ raise RuntimeError("caddis_finished.py is missing") # the caller falls back to report_lines
435
+ env = os.environ if env is None else env
436
+ home = Path.home() if home is None else home
437
+ common = _common_dir(Path(top), git)
438
+ main = common.parent if common is not None else Path(top)
439
+ git_dir = common if common is not None else main / ".git"
440
+ roots = resolve_roots(main, env, home)
441
+ any_linked = cf.has_linked_worktrees(git_dir) or any(
442
+ cf.has_linked_worktrees(r / ".git") for r in _repos_under(roots, main))
443
+ gh_s, orca_s = min(GH_TIMEOUT_S, remaining()), min(ORCA_TIMEOUT_S, remaining())
444
+ pool = ThreadPoolExecutor(max_workers=2)
445
+ try:
446
+ gh = orca = None
447
+ if want_prs:
448
+ gh = (pool.submit(fetch_prs, main, git_dir, _run, time.time(), gh_s) if gh_s > 0
449
+ else _done((None, NO_TIME_LEFT)))
450
+ if any_linked:
451
+ orca = pool.submit(orca_worktrees, _run, _which, orca_s) if orca_s > 0 else _done((None, NO_TIME_LEFT))
452
+ finally:
453
+ pool.shutdown(wait=False) # the submitted calls still run; their timeouts bound them
454
+ return Jobs(main, roots, any_linked, gh, orca)
455
+
456
+
457
+ def report_lines(top: Path | None, fresh: dict, git: Callable, remaining: Callable[[], float],
458
+ env: Mapping[str, str] | None = None, home: Path | None = None,
459
+ jobs: Jobs | None = None) -> list[str]:
460
+ """The summary line, then the skipped and detail lines. REPORT ONLY: nothing here changes anything.
461
+
462
+ `fresh` holds `branch`, `ref`, `behind`, `ahead`, `dirty`, `gate_missing` from repo_freshness. The current repo
463
+ (resolved to its MAIN checkout, so a session in a linked worktree counts it once) gets the full report; every
464
+ other repo under the roots gets the cheap worktree scan. gh and orca run in two threads that start before the
465
+ scans (D8): pass `jobs` from an earlier `start_jobs` call, or this call starts them itself.
466
+ """
467
+ if top is None:
468
+ return []
469
+ if cf is None:
470
+ return [SKIP_HYGIENE, *_old_line(fresh)]
471
+ ref = fresh.get("ref") or ""
472
+ if jobs is None:
473
+ jobs = start_jobs(Path(top), git, remaining, want_prs=bool(ref), env=env, home=home)
474
+ home = Path.home() if home is None else home
475
+ main, roots, any_linked = jobs.main, jobs.roots, jobs.any_linked
476
+ gh_job = jobs.gh if ref else None # started early on `origin` alone: with no default ref its answer is unused
477
+
478
+ records = _worktree_records(main, git)
479
+ here_found = _classify(main.name, records[1:], git)
480
+ other_found, _scanned, not_scanned = scan_repos(roots, main, git, remaining)
481
+ tips = _local_branches(main, git)
482
+ prs, gh_reason = _result(gh_job, "gh", (None, ""))
483
+ orca_map, orca_reason = _result(jobs.orca, "orca", ({}, ""))
484
+
485
+ def is_anc(tip: str, head: str) -> bool:
486
+ return git(str(main), "merge-base", "--is-ancestor", tip, head)[0] == 0
487
+
488
+ by_branch = _prs_by_branch(prs) if prs is not None else None
489
+ here = [b for f in here_found if (b := _bucket(f, orca_map, by_branch, tips, is_anc, True))]
490
+ other = [{**f, "bucket": b} for f in other_found if (b := _bucket(f, orca_map, None, tips, is_anc, False))]
491
+
492
+ merged, triage = 0, []
493
+ if by_branch is not None:
494
+ default = ref.split("/", 1)[-1]
495
+ checked_out = {r["branch"] for r in records}
496
+ for name, (tip, _date) in tips.items():
497
+ if name == default or name in checked_out:
498
+ continue
499
+ state, _ = cf.branch_report_state(tip, by_branch.get(name, []), is_anc)
500
+ if state == "merged-not-deleted":
501
+ merged += 1
502
+ elif state == "needs-triage":
503
+ triage.append(name)
504
+
505
+ gh_skipped = bool(ref) and prs is None
506
+ lines = [summary_line({**fresh, "stale": len(here) + len(other), "not_scanned": not_scanned, "merged": merged,
507
+ "triage": len(triage), "gh_skipped": gh_skipped})]
508
+ if gh_skipped:
509
+ lines.append(f"[HARNESS] skipped: branch PR states - {gh_reason}")
510
+ if any_linked and orca_map is None:
511
+ lines.append(f"[HARNESS] skipped: Orca check - {orca_reason}; no worktree is treated as Orca-managed")
512
+ if here or other:
513
+ lines.append(_stale_line(here, other, home, main))
514
+ if triage:
515
+ lines.append(_triage_line(triage, main, ref, tips, git, time.time()))
516
+ return lines
@@ -37,7 +37,7 @@ except ModuleNotFoundError as exc:
37
37
  # and they are not another session's edit. Patterns are fnmatch on the path inside the artifact folder; `*` crosses `/`.
38
38
  GENERATED_DIRS = ("relay/", "session-state/", "context-window/", ".relay-injected/")
39
39
  GENERATED_PATTERNS = (
40
- "relay.md", "usage-log.jsonl*", "agent-log.jsonl*", ".last-usage-review", "session-state.md",
40
+ "relay.md", "usage-log.jsonl*", "agent-log.jsonl*", ".last-usage-review", ".last-preload-review", "session-state.md",
41
41
  "context-window.json*", ".session-state-*.tmp", "hook-errors.jsonl", "memory.jsonl", "reviews/*.html",
42
42
  "*.lock", "*.bak",
43
43
  )