@caddis/cli 0.4.96 → 0.4.98

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 (55) hide show
  1. package/README.md +2 -0
  2. package/bundles/antigravity-plugin/plugin.json +1 -1
  3. package/bundles/antigravity-plugin/repo_hygiene.py +134 -20
  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 +31 -21
  16. package/bundles/antigravity-plugin/scripts/caddis_gate.py +18 -1
  17. package/bundles/antigravity-plugin/scripts/caddis_guide.json +2 -2
  18. package/bundles/antigravity-plugin/scripts/caddis_handoff.py +235 -0
  19. package/bundles/antigravity-plugin/scripts/caddis_hub_collect.py +67 -15
  20. package/bundles/antigravity-plugin/scripts/caddis_lanes.py +154 -130
  21. package/bundles/antigravity-plugin/scripts/caddis_review.py +12 -0
  22. package/bundles/antigravity-plugin/scripts/caddis_tidy.py +152 -51
  23. package/bundles/antigravity-plugin/scripts/caddis_todo.py +314 -18
  24. package/bundles/antigravity-plugin/scripts/schemas/hub-collect.schema.json +117 -1
  25. package/bundles/antigravity-plugin/scripts/schemas/hub-plans.schema.json +117 -1
  26. package/bundles/antigravity-plugin/scripts/setup_project_ai.py +60 -2
  27. package/bundles/antigravity-plugin/scripts/templates/coordinator.md +3 -3
  28. package/bundles/antigravity-plugin/skills/coordinate/SKILL.md +4 -1
  29. package/bundles/antigravity-plugin/skills/cross-review/SKILL.md +6 -0
  30. package/bundles/antigravity-plugin/skills/handoff/SKILL.md +101 -23
  31. package/bundles/antigravity-plugin/skills/implement/SKILL.md +6 -0
  32. package/bundles/antigravity-plugin/skills/park/SKILL.md +7 -2
  33. package/bundles/antigravity-plugin/skills/pr-merge/SKILL.md +1 -0
  34. package/bundles/antigravity-plugin/skills/ship-pr/SKILL.md +1 -0
  35. package/bundles/manifest.json +2 -2
  36. package/dist/cli.js +276 -76
  37. package/dist/export/assets/export-B3cUoxL1.js +150 -0
  38. package/dist/export/assets/export-DQss44R1.css +1 -0
  39. package/dist/export/index.html +2 -2
  40. package/dist/ui/assets/Activity-CvEIJlnE.js +6 -0
  41. package/dist/ui/assets/{Guide-Czn5sK0f.js → Guide-BxS9L55s.js} +1 -1
  42. package/dist/ui/assets/Guide-DTd261-c.css +1 -0
  43. package/dist/ui/assets/RoadmapTab-CqlWs7dJ.js +31 -0
  44. package/dist/ui/assets/index-9pdDzLVp.css +1 -0
  45. package/dist/ui/assets/index-DSxeWPax.js +231 -0
  46. package/dist/ui/index.html +2 -2
  47. package/package.json +1 -1
  48. package/dist/export/assets/export-CMtV-slT.css +0 -1
  49. package/dist/export/assets/export-DtlDFN4L.js +0 -150
  50. package/dist/ui/assets/Activity-BDjet2xd.js +0 -6
  51. package/dist/ui/assets/Guide-D-Zy4cUT.css +0 -1
  52. package/dist/ui/assets/RoadmapTab-Bd8geyQx.js +0 -31
  53. package/dist/ui/assets/index-Bd0Z4jR8.css +0 -1
  54. package/dist/ui/assets/index-CmngQ8Mk.js +0 -231
  55. package/dist/ui/assets/time-D00tu2ZP.js +0 -1
@@ -1,7 +1,8 @@
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] [--known PATH=FP ...] --json
4
+ Usage: caddis_hub_collect.py --repos PATH [PATH ...] [--only roadmaps,plans,relays,spend,guide] [--known PATH=FP ...]
5
+ [--prs-file PATH] [--done-known PATH=TREE ...] --json
5
6
 
6
7
  The hub runs this once per cycle. It runs in ONE Python process for all repos (hub rule R15, spawn cost L8). It
7
8
  never calls gh, claude or agy, and never runs `git fetch`: the roadmap reader sees the origin refs the repo
@@ -70,13 +71,18 @@ def _fetch_time(common: Path) -> int | None:
70
71
  return None
71
72
 
72
73
 
73
- def _plans_json(root: Path) -> dict:
74
+ def _plans_json(root: Path, prs: list[dict] | None = None, off_reason: str | None = None,
75
+ done_known: str | None = None) -> dict:
74
76
  """Plans from the origin ref the repo already has (R15: local git only), so a pushed Tracker edit shows with no
75
- pull. A folder that is not a git checkout, or has no origin default branch, reads the working tree."""
77
+ pull. A folder that is not a git checkout, or has no origin default branch, reads the working tree.
78
+ `done_known` is the done tree the hub already holds: the same tree comes back as `unchanged` (D2)."""
76
79
  branch = None
77
80
  common = git_common_dir(Path(root))
78
81
  if common is None:
79
- return _sibling("caddis_todo").plans_json(root)
82
+ out = _sibling("caddis_todo").plans_json(root, prs=prs)
83
+ if off_reason is not None and isinstance(out, dict):
84
+ out["overlay"] = {"state": "off", "reason": off_reason, "count": 0}
85
+ return out
80
86
  try: # origin/HEAD is a one-line file; reading it saves a git process per repo
81
87
  head = (common / "refs" / "remotes" / "origin" / "HEAD").read_text(encoding="utf-8").strip()
82
88
  except (OSError, UnicodeDecodeError):
@@ -95,9 +101,12 @@ def _plans_json(root: Path) -> dict:
95
101
  branch = None
96
102
  finally:
97
103
  roadmap.FETCH = saved
98
- out = _sibling("caddis_todo").plans_json(root, branch=branch)
104
+ extra = {"done_known": done_known} if done_known is not None else {} # an older plans_json takes no such key
105
+ out = _sibling("caddis_todo").plans_json(root, branch=branch, prs=prs, **extra)
99
106
  if common is not None and isinstance(out, dict):
100
107
  out["fetched_at"] = _fetch_time(common)
108
+ if off_reason is not None and isinstance(out, dict):
109
+ out["overlay"] = {"state": "off", "reason": off_reason, "count": 0}
101
110
  return out
102
111
 
103
112
 
@@ -219,7 +228,25 @@ def _runner_files(common: Path) -> list[Path]:
219
228
  return _files(common / RUNNER_DIR, recurse=True)
220
229
 
221
230
 
222
- def fingerprint(repo: Path) -> str:
231
+ def load_prs(path: str) -> dict[str, list[dict]] | None:
232
+ try:
233
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
234
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
235
+ return None
236
+ if not isinstance(data, dict) or data.get("schema") != 1:
237
+ return None
238
+ repos = data.get("repos")
239
+ if not isinstance(repos, dict):
240
+ return None
241
+ out: dict[str, list[dict]] = {}
242
+ for key, val in repos.items():
243
+ if not isinstance(key, str) or not isinstance(val, list):
244
+ return None
245
+ out[key] = [item for item in val if isinstance(item, dict)]
246
+ return out
247
+
248
+
249
+ def fingerprint(repo: Path, prs: list[dict] | None = None) -> str:
223
250
  """sha256 over the sorted (name, mtime_ns, size) of every input file and origin ref file. Empty list: still a hash.
224
251
 
225
252
  The roadmaps come from the origin refs (`git show origin/<default>:...`), so a fetch must change the hash."""
@@ -236,28 +263,41 @@ def fingerprint(repo: Path) -> str:
236
263
  except OSError:
237
264
  continue # the file went away while we looked
238
265
  rows.append((name, info.st_mtime_ns, info.st_size))
266
+ if prs is not None:
267
+ rows.append((f"prs:{hashlib.sha256(json.dumps(prs, sort_keys=True).encode('utf-8')).hexdigest()}", 0, 0))
239
268
  return hashlib.sha256(json.dumps(sorted(rows)).encode("utf-8")).hexdigest()
240
269
 
241
270
 
242
- def parse_known(values: list[str]) -> dict[str, str]:
271
+ def parse_known(values: list[str], flag: str = "--known") -> dict[str, str]:
272
+ """`PATH=VALUE` items as {PATH: VALUE}, split on the last `=`. Used for --known and --done-known."""
243
273
  known: dict[str, str] = {}
244
274
  for value in values:
245
275
  if "=" not in value:
246
- raise ValueError(f"bad --known value: {value}")
276
+ raise ValueError(f"bad {flag} value: {value}")
247
277
  path, fp = value.rsplit("=", 1)
248
278
  if not path or not fp:
249
- raise ValueError(f"bad --known value: {value}")
279
+ raise ValueError(f"bad {flag} value: {value}")
250
280
  known[path] = fp
251
281
  return known
252
282
 
253
283
 
254
- def collect_repo(path: str, kinds: tuple[str, ...], known: dict[str, str] | None = None) -> dict:
284
+ def collect_repo(path: str, kinds: tuple[str, ...], known: dict[str, str] | None = None,
285
+ prs_map: dict[str, list[dict]] | None = None, overlay: bool = False,
286
+ done_known: dict[str, str] | None = None) -> dict:
255
287
  repo = Path(path)
256
288
  if not repo.is_dir():
257
289
  return {"path": path, "error": "not a folder"}
258
290
  entry: dict = {"path": path}
291
+ repo_prs, off = None, None
292
+ if overlay:
293
+ if prs_map is None:
294
+ off = "PR data unreadable"
295
+ elif path not in prs_map: # `path` is the exact --repos string
296
+ off = "no PR data"
297
+ else:
298
+ repo_prs = prs_map[path]
259
299
  try:
260
- entry["fingerprint"] = fingerprint(repo)
300
+ entry["fingerprint"] = fingerprint(repo, repo_prs)
261
301
  except Exception as exc: # a repo we cannot read must not stop the others
262
302
  return {"path": path, **_error(exc)}
263
303
  if known and known.get(path) == entry["fingerprint"]:
@@ -266,15 +306,21 @@ def collect_repo(path: str, kinds: tuple[str, ...], known: dict[str, str] | None
266
306
  if kind not in kinds:
267
307
  continue
268
308
  try:
269
- entry[kind] = _REPO_COLLECTORS[kind](repo)
309
+ if kind == "plans":
310
+ entry[kind] = _plans_json(repo, prs=repo_prs, off_reason=off,
311
+ done_known=(done_known or {}).get(path)) # keyed like --known
312
+ else:
313
+ entry[kind] = _REPO_COLLECTORS[kind](repo)
270
314
  except Exception as exc:
271
315
  entry[kind] = _error(exc)
272
316
  return entry
273
317
 
274
318
 
275
- def collect(repos: list[str], kinds: tuple[str, ...], known: dict[str, str] | None = None) -> dict:
319
+ def collect(repos: list[str], kinds: tuple[str, ...], known: dict[str, str] | None = None,
320
+ prs_map: dict[str, list[dict]] | None = None, overlay: bool = False,
321
+ done_known: dict[str, str] | None = None) -> dict:
276
322
  out: dict = {"schema": SCHEMA, "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
277
- "repos": [collect_repo(path, kinds, known) for path in repos]}
323
+ "repos": [collect_repo(path, kinds, known, prs_map, overlay, done_known) for path in repos]}
278
324
  for kind, call in (("spend", _spend_json), ("guide", _guide_json)):
279
325
  if kind not in kinds:
280
326
  continue
@@ -300,6 +346,9 @@ def main(argv: list[str] | None = None) -> int:
300
346
  parser.add_argument("--repos", nargs="+", required=True, metavar="PATH")
301
347
  parser.add_argument("--only", default=",".join(KINDS), help="comma list of: " + ", ".join(KINDS))
302
348
  parser.add_argument("--known", nargs="+", default=[], metavar="PATH=FP")
349
+ parser.add_argument("--prs-file", default=None, metavar="PATH")
350
+ parser.add_argument("--done-known", nargs="+", default=[], metavar="PATH=TREE",
351
+ help="the done-plans tree the hub holds per repo; the same tree comes back as unchanged")
303
352
  parser.add_argument("--json", action="store_true", required=True)
304
353
  args = parser.parse_args(argv)
305
354
  kinds = tuple(k.strip() for k in args.only.split(",") if k.strip())
@@ -308,9 +357,12 @@ def main(argv: list[str] | None = None) -> int:
308
357
  parser.error(f"unknown --only kind: {', '.join(unknown) or '(empty)'}; use {', '.join(KINDS)}")
309
358
  try:
310
359
  known = parse_known(args.known)
360
+ done_known = parse_known(args.done_known, "--done-known")
311
361
  except ValueError as exc:
312
362
  parser.error(str(exc))
313
- print(json.dumps(collect(args.repos, kinds, known), ensure_ascii=False))
363
+ overlay = args.prs_file is not None
364
+ prs_map = load_prs(args.prs_file) if overlay else None
365
+ print(json.dumps(collect(args.repos, kinds, known, prs_map, overlay, done_known), ensure_ascii=False))
314
366
  return 0
315
367
 
316
368
 
@@ -1453,6 +1453,12 @@ _CI_LOG_TAIL_LINES = 80
1453
1453
  _CI_LOG_TAIL_CHARS = 8000
1454
1454
  _CI_AGY_TIMEOUT_S = 300
1455
1455
  _CI_GH_SHORT_TIMEOUT_S = 60
1456
+ # The gh poll interval, and the wait before ci-watch watches a PR again. Right after `gh pr create` or a push,
1457
+ # gh can report no checks yet, or the previous head's checks (item 7, ci-watch-followups). ci-watch then
1458
+ # watches again, at most _CI_SETTLE_RETRIES times (about 3 minutes), inside the --timeout budget. A PR that
1459
+ # never gets checks (docs only) still ends in `timeout`.
1460
+ _CI_POLL_S = 30
1461
+ _CI_SETTLE_RETRIES = 6
1456
1462
  _RUN_ID_IN_URL = re.compile(r"/actions/runs/(\d+)")
1457
1463
 
1458
1464
 
@@ -1611,13 +1617,16 @@ def ci_watch(
1611
1617
  run_agy=run_lane,
1612
1618
  run_gh=subprocess.run,
1613
1619
  clock=time.monotonic,
1620
+ sleep=time.sleep,
1614
1621
  ) -> int:
1615
1622
  """Wait for CI with `gh`, using one shared time budget. agy only summarises a failure.
1616
1623
 
1617
1624
  `gh pr checks --watch` (or `gh run watch`) does the waiting, but its exit code is not proof. On a PR,
1618
1625
  RESULT is `pass` only when the check rollup of the PR's head (one `gh pr view --json
1619
1626
  mergeStateStatus,headRefOid,statusCheckRollup`) is non-empty and every check is COMPLETED and green, and
1620
- the head is the one read before the watch began (a push during the watch is exit 3). On a run, `gh run
1627
+ the head is the one read before the watch began (a push during the watch is exit 3). When the PR head has
1628
+ no checks yet, or gh read an older head's checks (the head's rollup is empty or unfinished, or the head
1629
+ moved), ci-watch waits _CI_POLL_S and watches again, at most _CI_SETTLE_RETRIES times. On a run, `gh run
1621
1630
  view --json status,conclusion,headSha` must read COMPLETED and SUCCESS (a skipped run ran no job). HEAD prints
1622
1631
  the commit. When the result is `fail` and the `ci-watch` routing chain holds agy, agy reads the last lines
1623
1632
  of the failed log (inside its prompt) and returns one line for SUMMARY. agy never changes the result or
@@ -1653,139 +1662,154 @@ def ci_watch(
1653
1662
  _print_ci_watch("timeout", "n/a", "n/a", "none", "gh")
1654
1663
  return EXIT_CONFIG
1655
1664
  repo_args = ["--repo", repo_slug] if repo_slug else []
1656
- head_before: str | None = None
1657
- if target_kind == "pr":
1658
- # The head before the watch: a push during the watch can make a new head look green before all its
1659
- # checks exist, so a pass needs the same head after the watch.
1660
- before = _ci_gh_run(run_gh, [gh_path, "pr", "view", str(target_id), "--json", "headRefOid", *repo_args],
1661
- repo, min(_CI_GH_SHORT_TIMEOUT_S, remaining()))
1662
- if before is not None and before.returncode == 0:
1663
- try:
1664
- head_before = str(json.loads(before.stdout or "").get("headRefOid") or "") or None
1665
- except (ValueError, AttributeError):
1666
- head_before = None
1667
- command = [gh_path, "pr", "checks", str(target_id), "--watch", "--interval", "30", *repo_args]
1668
- else:
1669
- command = [gh_path, "run", "watch", str(target_id), "--exit-status", "--interval", "30", *repo_args]
1670
- try:
1671
- completed = run_gh(
1672
- command, cwd=repo, capture_output=True, text=True,
1673
- encoding="utf-8", errors="replace", timeout=remaining(),
1674
- )
1675
- except subprocess.TimeoutExpired:
1676
- print("[caddis-lanes] ci-watch: gh timed out", file=sys.stderr)
1677
- _print_ci_watch("timeout", "n/a", "n/a", "none", "gh")
1678
- return EXIT_CONFIG
1679
- except OSError as exc:
1680
- print(f"[caddis-lanes] ci-watch: gh could not start ({exc})", file=sys.stderr)
1681
- _print_ci_watch("timeout", "n/a", "n/a", "none", "gh")
1682
- return EXIT_CONFIG
1683
- output = "\n".join(part for part in (completed.stdout, completed.stderr) if part)
1684
- if output:
1685
- print("\n".join(output.splitlines()[-40:]), file=sys.stderr)
1686
- no_checks = "no checks reported" in output.lower()
1687
- code = EXIT_OK if completed.returncode == 0 else (
1688
- EXIT_FAIL if completed.returncode == 1 and not no_checks else EXIT_CONFIG
1689
- )
1690
- result = "pass" if code == EXIT_OK else "fail" if code == EXIT_FAIL else "timeout"
1691
-
1692
- checks, merge_state = "n/a", "n/a"
1693
- failing = "see gh output" if code == EXIT_FAIL else "none"
1694
- run_id: str | None = str(target_id) if target_kind == "run" else None
1695
- if target_kind == "pr" and code != EXIT_CONFIG:
1696
- rows = _parse_pr_checks(completed.stdout or "")
1697
- if rows:
1698
- # `skipping` is not a failure: count it as passed.
1699
- passed = sum(1 for _, state, _ in rows if state in {"pass", "skipping"})
1700
- checks = f"{passed}/{len(rows)}"
1701
- # Failed checks first; cancelled ones only when nothing failed (they name the wrong run).
1702
- bad = ([(name, url) for name, state, url in rows if state == "fail"]
1703
- or [(name, url) for name, state, url in rows if state == "cancel"])
1704
- if code == EXIT_FAIL and bad:
1705
- failing = ", ".join(name for name, _ in bad)
1706
- for _, url in bad:
1707
- found = _RUN_ID_IN_URL.search(url)
1708
- if found:
1709
- run_id = found.group(1)
1710
- break
1711
- head = "n/a"
1712
- if target_kind == "pr" and code != EXIT_CONFIG:
1713
- # The watch table alone is not proof. gh exited 0 on 16 Oct 2026 with a cancelled row (CHECKS 6/7) and
1714
- # with a row still unfinished (5/6), and its table can still show an older head's checks. So a pass
1715
- # also needs the check rollup of the PR's CURRENT head: every check COMPLETED and green. HEAD names
1716
- # that commit, so a caller can merge only that head.
1717
- rollup_view = None
1718
- left = remaining()
1719
- if left > 0:
1720
- view = _ci_gh_run(
1721
- run_gh,
1722
- [gh_path, "pr", "view", str(target_id), "--json", "mergeStateStatus,headRefOid,statusCheckRollup",
1723
- *repo_args],
1724
- repo, min(_CI_GH_SHORT_TIMEOUT_S, left),
1725
- )
1726
- if view is not None and view.returncode == 0:
1665
+ for attempt in range(_CI_SETTLE_RETRIES + 1):
1666
+ settle: str | None = None # why the PR head is not settled yet; set means watch again
1667
+ head_before: str | None = None
1668
+ if target_kind == "pr":
1669
+ # The head before the watch: a push during the watch can make a new head look green before all its
1670
+ # checks exist, so a pass needs the same head after the watch.
1671
+ before = _ci_gh_run(run_gh, [gh_path, "pr", "view", str(target_id), "--json", "headRefOid", *repo_args],
1672
+ repo, min(_CI_GH_SHORT_TIMEOUT_S, remaining()))
1673
+ if before is not None and before.returncode == 0:
1727
1674
  try:
1728
- rollup_view = json.loads(view.stdout or "")
1729
- except ValueError:
1730
- rollup_view = None
1731
- if isinstance(rollup_view, dict):
1732
- merge_state = str(rollup_view.get("mergeStateStatus") or "") or "n/a"
1733
- head = str(rollup_view.get("headRefOid") or "") or "n/a"
1734
- verdict = _rollup_verdict(rollup_view.get("statusCheckRollup")) if isinstance(rollup_view, dict) else None
1735
- if code == EXIT_OK:
1736
- if verdict is None or head == "n/a":
1737
- print("[caddis-lanes] ci-watch: gh said pass, but the head's checks could not be read",
1738
- file=sys.stderr)
1739
- code, result, failing = EXIT_CONFIG, "timeout", "none"
1740
- else:
1741
- green, failed, unfinished = verdict
1742
- checks = f"{green}/{green + len(failed) + len(unfinished)}"
1743
- if failed:
1744
- code, result, failing = EXIT_FAIL, "fail", ", ".join(failed)
1745
- elif unfinished:
1746
- print(f"[caddis-lanes] ci-watch: gh said pass, but not finished: {', '.join(unfinished)}",
1675
+ head_before = str(json.loads(before.stdout or "").get("headRefOid") or "") or None
1676
+ except (ValueError, AttributeError):
1677
+ head_before = None
1678
+ command = [gh_path, "pr", "checks", str(target_id), "--watch", "--interval", str(_CI_POLL_S), *repo_args]
1679
+ else:
1680
+ command = [gh_path, "run", "watch", str(target_id), "--exit-status", "--interval", str(_CI_POLL_S),
1681
+ *repo_args]
1682
+ try:
1683
+ completed = run_gh(
1684
+ command, cwd=repo, capture_output=True, text=True,
1685
+ encoding="utf-8", errors="replace", timeout=remaining(),
1686
+ )
1687
+ except subprocess.TimeoutExpired:
1688
+ print("[caddis-lanes] ci-watch: gh timed out", file=sys.stderr)
1689
+ _print_ci_watch("timeout", "n/a", "n/a", "none", "gh")
1690
+ return EXIT_CONFIG
1691
+ except OSError as exc:
1692
+ print(f"[caddis-lanes] ci-watch: gh could not start ({exc})", file=sys.stderr)
1693
+ _print_ci_watch("timeout", "n/a", "n/a", "none", "gh")
1694
+ return EXIT_CONFIG
1695
+ output = "\n".join(part for part in (completed.stdout, completed.stderr) if part)
1696
+ if output:
1697
+ print("\n".join(output.splitlines()[-40:]), file=sys.stderr)
1698
+ no_checks = "no checks reported" in output.lower()
1699
+ if target_kind == "pr" and no_checks:
1700
+ settle = "the PR head has no checks yet"
1701
+ code = EXIT_OK if completed.returncode == 0 else (
1702
+ EXIT_FAIL if completed.returncode == 1 and not no_checks else EXIT_CONFIG
1703
+ )
1704
+ result = "pass" if code == EXIT_OK else "fail" if code == EXIT_FAIL else "timeout"
1705
+
1706
+ checks, merge_state = "n/a", "n/a"
1707
+ failing = "see gh output" if code == EXIT_FAIL else "none"
1708
+ run_id: str | None = str(target_id) if target_kind == "run" else None
1709
+ if target_kind == "pr" and code != EXIT_CONFIG:
1710
+ rows = _parse_pr_checks(completed.stdout or "")
1711
+ if rows:
1712
+ # `skipping` is not a failure: count it as passed.
1713
+ passed = sum(1 for _, state, _ in rows if state in {"pass", "skipping"})
1714
+ checks = f"{passed}/{len(rows)}"
1715
+ # Failed checks first; cancelled ones only when nothing failed (they name the wrong run).
1716
+ bad = ([(name, url) for name, state, url in rows if state == "fail"]
1717
+ or [(name, url) for name, state, url in rows if state == "cancel"])
1718
+ if code == EXIT_FAIL and bad:
1719
+ failing = ", ".join(name for name, _ in bad)
1720
+ for _, url in bad:
1721
+ found = _RUN_ID_IN_URL.search(url)
1722
+ if found:
1723
+ run_id = found.group(1)
1724
+ break
1725
+ head = "n/a"
1726
+ if target_kind == "pr" and code != EXIT_CONFIG:
1727
+ # The watch table alone is not proof. gh exited 0 on 16 Oct 2026 with a cancelled row (CHECKS 6/7) and
1728
+ # with a row still unfinished (5/6), and its table can still show an older head's checks. So a pass
1729
+ # also needs the check rollup of the PR's CURRENT head: every check COMPLETED and green. HEAD names
1730
+ # that commit, so a caller can merge only that head.
1731
+ rollup_view = None
1732
+ left = remaining()
1733
+ if left > 0:
1734
+ view = _ci_gh_run(
1735
+ run_gh,
1736
+ [gh_path, "pr", "view", str(target_id), "--json", "mergeStateStatus,headRefOid,statusCheckRollup",
1737
+ *repo_args],
1738
+ repo, min(_CI_GH_SHORT_TIMEOUT_S, left),
1739
+ )
1740
+ if view is not None and view.returncode == 0:
1741
+ try:
1742
+ rollup_view = json.loads(view.stdout or "")
1743
+ except ValueError:
1744
+ rollup_view = None
1745
+ if isinstance(rollup_view, dict):
1746
+ merge_state = str(rollup_view.get("mergeStateStatus") or "") or "n/a"
1747
+ head = str(rollup_view.get("headRefOid") or "") or "n/a"
1748
+ verdict = _rollup_verdict(rollup_view.get("statusCheckRollup")) if isinstance(rollup_view, dict) else None
1749
+ if code == EXIT_OK:
1750
+ if verdict is None or head == "n/a":
1751
+ print("[caddis-lanes] ci-watch: gh said pass, but the head's checks could not be read",
1747
1752
  file=sys.stderr)
1748
1753
  code, result, failing = EXIT_CONFIG, "timeout", "none"
1749
- elif head_before is None:
1750
- print("[caddis-lanes] ci-watch: the head before the watch could not be read, so a push "
1751
- "during the watch cannot be ruled out; watch again", file=sys.stderr)
1752
- code, result, failing = EXIT_CONFIG, "timeout", "head not read before the watch"
1753
- elif head != head_before:
1754
- print(f"[caddis-lanes] ci-watch: the head moved during the watch ({head_before} -> {head}); "
1755
- "watch again", file=sys.stderr)
1756
- code, result, failing = EXIT_CONFIG, "timeout", "head moved during the watch"
1757
- elif target_kind == "run" and code == EXIT_OK:
1758
- # The same rule for one run: pass only when the run reads COMPLETED and SUCCESS; HEAD is its commit. A whole
1759
- # run that is SKIPPED or NEUTRAL ran no job (gh run watch --exit-status exits 0 on it): could not tell.
1760
- run_view = None
1761
- left = remaining()
1762
- if left > 0:
1763
- view = _ci_gh_run(
1764
- run_gh, [gh_path, "run", "view", str(target_id), "--json", "status,conclusion,headSha", *repo_args],
1765
- repo, min(_CI_GH_SHORT_TIMEOUT_S, left),
1766
- )
1767
- if view is not None and view.returncode == 0:
1768
- try:
1769
- run_view = json.loads(view.stdout or "")
1770
- except ValueError:
1771
- run_view = None
1772
- if not isinstance(run_view, dict) or not run_view.get("headSha"):
1773
- print("[caddis-lanes] ci-watch: gh said pass, but the run could not be read", file=sys.stderr)
1774
- code, result = EXIT_CONFIG, "timeout"
1775
- else:
1776
- head = str(run_view["headSha"])
1777
- status = str(run_view.get("status") or "").upper()
1778
- conclusion = str(run_view.get("conclusion") or "").upper()
1779
- if status != "COMPLETED":
1780
- print(f"[caddis-lanes] ci-watch: gh said pass, but run {target_id} is {status.lower() or 'unknown'}",
1781
- file=sys.stderr)
1754
+ if head != "n/a": # gh read an older head's checks; the new head has none yet
1755
+ settle = "the head's checks are not reported yet"
1756
+ else:
1757
+ green, failed, unfinished = verdict
1758
+ checks = f"{green}/{green + len(failed) + len(unfinished)}"
1759
+ if failed:
1760
+ code, result, failing = EXIT_FAIL, "fail", ", ".join(failed)
1761
+ elif unfinished:
1762
+ print(f"[caddis-lanes] ci-watch: gh said pass, but not finished: {', '.join(unfinished)}",
1763
+ file=sys.stderr)
1764
+ code, result, failing = EXIT_CONFIG, "timeout", "none"
1765
+ settle = "the head's checks are not finished"
1766
+ elif head_before is None:
1767
+ print("[caddis-lanes] ci-watch: the head before the watch could not be read, so a push "
1768
+ "during the watch cannot be ruled out; watch again", file=sys.stderr)
1769
+ code, result, failing = EXIT_CONFIG, "timeout", "head not read before the watch"
1770
+ elif head != head_before:
1771
+ print(f"[caddis-lanes] ci-watch: the head moved during the watch ({head_before} -> {head}); "
1772
+ "watch again", file=sys.stderr)
1773
+ code, result, failing = EXIT_CONFIG, "timeout", "head moved during the watch"
1774
+ settle = "the head moved during the watch"
1775
+ elif target_kind == "run" and code == EXIT_OK:
1776
+ # The same rule for one run: pass only when the run reads COMPLETED and SUCCESS; HEAD is its commit. A whole
1777
+ # run that is SKIPPED or NEUTRAL ran no job (gh run watch --exit-status exits 0 on it): could not tell.
1778
+ run_view = None
1779
+ left = remaining()
1780
+ if left > 0:
1781
+ view = _ci_gh_run(
1782
+ run_gh, [gh_path, "run", "view", str(target_id), "--json", "status,conclusion,headSha", *repo_args],
1783
+ repo, min(_CI_GH_SHORT_TIMEOUT_S, left),
1784
+ )
1785
+ if view is not None and view.returncode == 0:
1786
+ try:
1787
+ run_view = json.loads(view.stdout or "")
1788
+ except ValueError:
1789
+ run_view = None
1790
+ if not isinstance(run_view, dict) or not run_view.get("headSha"):
1791
+ print("[caddis-lanes] ci-watch: gh said pass, but the run could not be read", file=sys.stderr)
1782
1792
  code, result = EXIT_CONFIG, "timeout"
1783
- elif conclusion in {"SKIPPED", "NEUTRAL"}:
1784
- print(f"[caddis-lanes] ci-watch: run {target_id} is {conclusion.lower()}: no job ran, so this is "
1785
- "not a pass", file=sys.stderr)
1786
- code, result, failing = EXIT_CONFIG, "timeout", f"run {target_id} ({conclusion.lower()})"
1787
- elif conclusion != "SUCCESS":
1788
- code, result, failing = EXIT_FAIL, "fail", f"run {target_id} ({conclusion.lower() or 'unknown'})"
1793
+ else:
1794
+ head = str(run_view["headSha"])
1795
+ status = str(run_view.get("status") or "").upper()
1796
+ conclusion = str(run_view.get("conclusion") or "").upper()
1797
+ if status != "COMPLETED":
1798
+ print(f"[caddis-lanes] ci-watch: gh said pass, but run {target_id} is {status.lower() or 'unknown'}",
1799
+ file=sys.stderr)
1800
+ code, result = EXIT_CONFIG, "timeout"
1801
+ elif conclusion in {"SKIPPED", "NEUTRAL"}:
1802
+ print(f"[caddis-lanes] ci-watch: run {target_id} is {conclusion.lower()}: no job ran, so this is "
1803
+ "not a pass", file=sys.stderr)
1804
+ code, result, failing = EXIT_CONFIG, "timeout", f"run {target_id} ({conclusion.lower()})"
1805
+ elif conclusion != "SUCCESS":
1806
+ code, result, failing = EXIT_FAIL, "fail", f"run {target_id} ({conclusion.lower() or 'unknown'})"
1807
+ if (settle is None or attempt == _CI_SETTLE_RETRIES
1808
+ or remaining() <= _CI_POLL_S):
1809
+ break
1810
+ print(f"[caddis-lanes] ci-watch: {settle}; watching again in {_CI_POLL_S}s "
1811
+ f"(retry {attempt + 1}/{_CI_SETTLE_RETRIES})", file=sys.stderr)
1812
+ sleep(_CI_POLL_S)
1789
1813
 
1790
1814
  summary: str | None = None
1791
1815
  # Walk the chain in order: agy summarises only when it comes before claude (claude = no helper).
@@ -527,6 +527,18 @@ def phase_risk(plan: Path, n: int | str) -> str:
527
527
  return max(values, key=_RISK_ORDER.index) if values else "normal"
528
528
 
529
529
 
530
+ _TYPE_RE = re.compile(r"^[\s>*_`~#+\-\[\]]*type\s*[*_`~]*\s*:[*_`~\s]*([a-z]+)", re.IGNORECASE)
531
+
532
+
533
+ def phase_type(plan: Path, n: int | str) -> str | None:
534
+ """The phase's `Type:` value: the first word of the first `Type:` line, lower case. None when there is none."""
535
+ for raw in phase_section(plan, n).splitlines():
536
+ m = _TYPE_RE.match(_normalize(raw))
537
+ if m:
538
+ return m.group(1).lower()
539
+ return None
540
+
541
+
530
542
  def plan_card(plan: Path, n: int | str, plan_ref: str | None = None) -> str:
531
543
  """The review card for one plan phase: its heading, Goal, Touches and Exit gate."""
532
544
  lines = phase_section(plan, n).splitlines()