@caddis/cli 0.4.96 → 0.4.97

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 (35) hide show
  1. package/README.md +2 -0
  2. package/bundles/antigravity-plugin/plugin.json +1 -1
  3. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
  4. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
  5. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
  6. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
  7. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
  8. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
  9. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
  10. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
  11. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
  12. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
  13. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
  14. package/bundles/antigravity-plugin/scripts/caddis_fleet.py +31 -21
  15. package/bundles/antigravity-plugin/scripts/caddis_guide.json +2 -2
  16. package/bundles/antigravity-plugin/scripts/caddis_hub_collect.py +51 -10
  17. package/bundles/antigravity-plugin/scripts/caddis_lanes.py +154 -130
  18. package/bundles/antigravity-plugin/scripts/caddis_todo.py +180 -3
  19. package/bundles/antigravity-plugin/scripts/schemas/hub-collect.schema.json +57 -0
  20. package/bundles/antigravity-plugin/scripts/schemas/hub-plans.schema.json +57 -0
  21. package/bundles/antigravity-plugin/scripts/templates/coordinator.md +3 -3
  22. package/bundles/antigravity-plugin/skills/coordinate/SKILL.md +4 -1
  23. package/bundles/antigravity-plugin/skills/handoff/SKILL.md +21 -8
  24. package/bundles/manifest.json +2 -2
  25. package/dist/cli.js +214 -71
  26. package/dist/export/assets/{export-CMtV-slT.css → export-B5Lzo-9e.css} +1 -1
  27. package/dist/export/assets/{export-DtlDFN4L.js → export-PF4z_ff4.js} +29 -29
  28. package/dist/export/index.html +2 -2
  29. package/dist/ui/assets/{Activity-BDjet2xd.js → Activity-DN1XBfsH.js} +1 -1
  30. package/dist/ui/assets/{Guide-Czn5sK0f.js → Guide-D-lZVEKf.js} +1 -1
  31. package/dist/ui/assets/{RoadmapTab-Bd8geyQx.js → RoadmapTab-tqQd2sYq.js} +7 -7
  32. package/dist/ui/assets/{index-CmngQ8Mk.js → index-CWslZIzV.js} +44 -44
  33. package/dist/ui/assets/{index-Bd0Z4jR8.css → index-CwgRPpjT.css} +1 -1
  34. package/dist/ui/index.html +2 -2
  35. package/package.json +1 -1
package/README.md CHANGED
@@ -141,6 +141,8 @@ starts it in the background; `caddis hub stop` stops it.
141
141
 
142
142
  **Timeline first, Board second.** Roadmaps and plans open on the Timeline view by default, with the Board view as the second option. Click any phase tile on the Timeline to open the phase panel and read its Tracker status, PR links and plan section text.
143
143
 
144
+ **Branch progress.** A plan that an open PR changes shows the PR branch's Tracker and `status:`, with the badge `on branch (PR #n)`. Done on main never goes back, and forks are not shown. The hub reads PR heads from GitHub and branch refs from the local origin refs, and never fetches. With no PR data, the line above the plans says `branch progress off (no PR data)`. `caddis hub export --prs <file>` takes the output of `gh pr list --json number,headRefName,isDraft,isCrossRepository,updatedAt`. The export never publishes a branch name, and a privacy hit only in branch content publishes main only.
145
+
144
146
  **Guide Poster and Details.** The Guide page has a `Poster` tab (with `Workflow` and `Mind map` views, plus a `Print` button for a two-page A3 landscape wall poster) and a `Details` tab. Every item on the poster links to its entry in Details.
145
147
 
146
148
  **Guide Wall poster.** A third tab, `Wall poster` (`#/guide/wall`), shows one A4 landscape sheet: the daily commands in order, a card per stage (plan, build, review, ship, continuity, knowledge, setup), and the agents. The `Print` button prints exactly that sheet on one page. It is built from the same installed guide data as the other tabs, so a new command, agent or count appears by itself after `caddis update` and a hub restart. The text shrinks (to 60% at most) when the guide grows, so nothing is cut off. Each line is the first clause of the description; the Details tab has the full text.
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "caddis",
3
- "version": "1.3.180",
3
+ "version": "1.3.181",
4
4
  "description": "caddis — agent-agnostic dev harness as an Antigravity (agy) plugin: TDD skills + commands, single-sourced with the Claude Code plugin."
5
5
  }
@@ -204,10 +204,10 @@ def render_roster(acks: list[Ack], coordinator: str) -> str:
204
204
  return "\n".join(lines) + "\n"
205
205
 
206
206
 
207
- def _fenced(text: str) -> str:
207
+ def _fenced(text: str, lang: str = "text") -> str:
208
208
  longest = max((len(r) for r in re.findall(r"`+", text)), default=0)
209
209
  fence = "`" * max(3, longest + 1)
210
- return f"{fence}text\n{text}\n{fence}"
210
+ return f"{fence}{lang}\n{text}\n{fence}"
211
211
 
212
212
 
213
213
  def start_line(ack: Ack, stamp: datetime) -> str:
@@ -475,11 +475,15 @@ def resume_prompt(relay_text: str) -> str:
475
475
  return prompt
476
476
 
477
477
 
478
+ def one_line(text: str) -> str:
479
+ """The text on one line, with no `'` and no `"`: a `'` would end a single-quoted word in bash and a `"` is dropped
480
+ by Windows PowerShell 5.1, so both become typographic."""
481
+ return " ".join(text.split()).replace("'", "’").replace('"', "”")
482
+
483
+
478
484
  def shell_arg(text: str) -> str:
479
- """One word that PowerShell and bash read the same: one line, inside single quotes (no expansion in either).
480
- A `'` would end the word in bash and a `"` is dropped by Windows PowerShell 5.1, so both become typographic."""
481
- one_line = " ".join(text.split())
482
- return "'" + one_line.replace("'", "’").replace('"', "”") + "'"
485
+ """One word that PowerShell and bash read the same: one line, inside single quotes (no expansion in either)."""
486
+ return "'" + one_line(text) + "'"
483
487
 
484
488
 
485
489
  ANNOUNCE_ID = "<your session id>"
@@ -501,27 +505,33 @@ def announce_text(name: str, folder: str) -> str:
501
505
  f"a reply. If the script is missing or lists no peer, skip this.")
502
506
 
503
507
 
508
+ RESUME_PROMPT_LABEL = "After /clear in this window, paste this:"
509
+ RESUME_LINE_LABEL = "In a new terminal, paste this:"
510
+
511
+
504
512
  def render_resume(session: str, session_id: str, workstream: str, prompt: str, role: str, stamp: datetime,
505
513
  fleet_mode: bool = False, announce: bool = False, folder: str = "",
506
514
  root: Path | None = None) -> str:
507
- """The last output of `/caddis:handoff`. In a fleet close the restart sheet holds the only start line.
508
-
509
- With `announce`, the start line (not the fenced block, which stays the relay's text) ends with the
510
- whoami + announce sentence: the start line is what the new session receives with its name.
511
- With `root`, the block names the repo and the start line first changes to it, because the relay's paths are
512
- repo-relative. `;`, as in the restart sheet: Windows PowerShell 5.1 has no `&&`."""
513
- shown = prompt # the fenced block stays the relay text
515
+ """The last output of `/caddis:handoff`. In a fleet close the restart sheet holds the only start line, so the
516
+ block keeps the relay's own prompt and says so.
517
+
518
+ Otherwise it ends with two labelled copy blocks. The model re-types this output in a Markdown reply, so colour
519
+ cannot reach the owner; a label and a fence can (owner, 5 Nov). Block 1 is the prompt on one line, to paste after
520
+ `/clear` in the same window. Block 2 is the full start line, to paste in a new terminal.
521
+ With `announce`, both end with the whoami + announce sentence: the new session receives it with its name.
522
+ With `root`, block 2 first changes to the repo, because the relay's paths are repo-relative. `;`, as in the
523
+ restart sheet: Windows PowerShell 5.1 has no `&&`."""
514
524
  repo = f"Repo: {root.as_posix()}\n" if root is not None else ""
515
525
  cd = f'cd "{root.as_posix()}"; ' if root is not None else ""
526
+ head = f"{model_line(role)}=== RESUME ===\nSession: {session} ({session_id})\nWorkstream: {workstream}\n{repo}"
516
527
  if fleet_mode:
517
- start = "Start line: from the restart sheet"
518
- else:
519
- name = new_name(role, stamp)
520
- if announce:
521
- prompt = f"{prompt}\n{announce_text(name, folder)}"
522
- start = f"Start line:\n{cd}claude {_model_flags(role)} --name {name} {shell_arg(prompt)}"
523
- return (f"{model_line(role)}=== RESUME ===\nSession: {session} ({session_id})\nWorkstream: {workstream}\n"
524
- f"{repo}{_fenced(shown)}\n{start}\n")
528
+ return f"{head}{_fenced(prompt)}\nStart line: from the restart sheet\n"
529
+ name = new_name(role, stamp)
530
+ if announce:
531
+ prompt = f"{prompt}\n{announce_text(name, folder)}"
532
+ full = f"{cd}claude {_model_flags(role)} --name {name} {shell_arg(prompt)}"
533
+ return (f"{head}{RESUME_PROMPT_LABEL}\n{_fenced(one_line(prompt))}\n"
534
+ f"{RESUME_LINE_LABEL}\n{_fenced(full, 'bash')}\n")
525
535
 
526
536
 
527
537
  def render_coordinator_resume(session: str, session_id: str, workstream: str) -> str:
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "version": "1.3.179",
4
- "generated": "2026-11-05 13:49 UTC",
3
+ "version": "1.3.180",
4
+ "generated": "2026-11-07 04:52 UTC",
5
5
  "commands": [
6
6
  {
7
7
  "name": "add-rules",
@@ -70,13 +70,16 @@ def _fetch_time(common: Path) -> int | None:
70
70
  return None
71
71
 
72
72
 
73
- def _plans_json(root: Path) -> dict:
73
+ def _plans_json(root: Path, prs: list[dict] | None = None, off_reason: str | None = None) -> dict:
74
74
  """Plans from the origin ref the repo already has (R15: local git only), so a pushed Tracker edit shows with no
75
75
  pull. A folder that is not a git checkout, or has no origin default branch, reads the working tree."""
76
76
  branch = None
77
77
  common = git_common_dir(Path(root))
78
78
  if common is None:
79
- return _sibling("caddis_todo").plans_json(root)
79
+ out = _sibling("caddis_todo").plans_json(root, prs=prs)
80
+ if off_reason is not None and isinstance(out, dict):
81
+ out["overlay"] = {"state": "off", "reason": off_reason, "count": 0}
82
+ return out
80
83
  try: # origin/HEAD is a one-line file; reading it saves a git process per repo
81
84
  head = (common / "refs" / "remotes" / "origin" / "HEAD").read_text(encoding="utf-8").strip()
82
85
  except (OSError, UnicodeDecodeError):
@@ -95,9 +98,11 @@ def _plans_json(root: Path) -> dict:
95
98
  branch = None
96
99
  finally:
97
100
  roadmap.FETCH = saved
98
- out = _sibling("caddis_todo").plans_json(root, branch=branch)
101
+ out = _sibling("caddis_todo").plans_json(root, branch=branch, prs=prs)
99
102
  if common is not None and isinstance(out, dict):
100
103
  out["fetched_at"] = _fetch_time(common)
104
+ if off_reason is not None and isinstance(out, dict):
105
+ out["overlay"] = {"state": "off", "reason": off_reason, "count": 0}
101
106
  return out
102
107
 
103
108
 
@@ -219,7 +224,25 @@ def _runner_files(common: Path) -> list[Path]:
219
224
  return _files(common / RUNNER_DIR, recurse=True)
220
225
 
221
226
 
222
- def fingerprint(repo: Path) -> str:
227
+ def load_prs(path: str) -> dict[str, list[dict]] | None:
228
+ try:
229
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
230
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
231
+ return None
232
+ if not isinstance(data, dict) or data.get("schema") != 1:
233
+ return None
234
+ repos = data.get("repos")
235
+ if not isinstance(repos, dict):
236
+ return None
237
+ out: dict[str, list[dict]] = {}
238
+ for key, val in repos.items():
239
+ if not isinstance(key, str) or not isinstance(val, list):
240
+ return None
241
+ out[key] = [item for item in val if isinstance(item, dict)]
242
+ return out
243
+
244
+
245
+ def fingerprint(repo: Path, prs: list[dict] | None = None) -> str:
223
246
  """sha256 over the sorted (name, mtime_ns, size) of every input file and origin ref file. Empty list: still a hash.
224
247
 
225
248
  The roadmaps come from the origin refs (`git show origin/<default>:...`), so a fetch must change the hash."""
@@ -236,6 +259,8 @@ def fingerprint(repo: Path) -> str:
236
259
  except OSError:
237
260
  continue # the file went away while we looked
238
261
  rows.append((name, info.st_mtime_ns, info.st_size))
262
+ if prs is not None:
263
+ rows.append((f"prs:{hashlib.sha256(json.dumps(prs, sort_keys=True).encode('utf-8')).hexdigest()}", 0, 0))
239
264
  return hashlib.sha256(json.dumps(sorted(rows)).encode("utf-8")).hexdigest()
240
265
 
241
266
 
@@ -251,13 +276,22 @@ def parse_known(values: list[str]) -> dict[str, str]:
251
276
  return known
252
277
 
253
278
 
254
- def collect_repo(path: str, kinds: tuple[str, ...], known: dict[str, str] | None = None) -> dict:
279
+ def collect_repo(path: str, kinds: tuple[str, ...], known: dict[str, str] | None = None,
280
+ prs_map: dict[str, list[dict]] | None = None, overlay: bool = False) -> dict:
255
281
  repo = Path(path)
256
282
  if not repo.is_dir():
257
283
  return {"path": path, "error": "not a folder"}
258
284
  entry: dict = {"path": path}
285
+ repo_prs, off = None, None
286
+ if overlay:
287
+ if prs_map is None:
288
+ off = "PR data unreadable"
289
+ elif path not in prs_map: # `path` is the exact --repos string
290
+ off = "no PR data"
291
+ else:
292
+ repo_prs = prs_map[path]
259
293
  try:
260
- entry["fingerprint"] = fingerprint(repo)
294
+ entry["fingerprint"] = fingerprint(repo, repo_prs)
261
295
  except Exception as exc: # a repo we cannot read must not stop the others
262
296
  return {"path": path, **_error(exc)}
263
297
  if known and known.get(path) == entry["fingerprint"]:
@@ -266,15 +300,19 @@ def collect_repo(path: str, kinds: tuple[str, ...], known: dict[str, str] | None
266
300
  if kind not in kinds:
267
301
  continue
268
302
  try:
269
- entry[kind] = _REPO_COLLECTORS[kind](repo)
303
+ if kind == "plans":
304
+ entry[kind] = _plans_json(repo, prs=repo_prs, off_reason=off)
305
+ else:
306
+ entry[kind] = _REPO_COLLECTORS[kind](repo)
270
307
  except Exception as exc:
271
308
  entry[kind] = _error(exc)
272
309
  return entry
273
310
 
274
311
 
275
- def collect(repos: list[str], kinds: tuple[str, ...], known: dict[str, str] | None = None) -> dict:
312
+ def collect(repos: list[str], kinds: tuple[str, ...], known: dict[str, str] | None = None,
313
+ prs_map: dict[str, list[dict]] | None = None, overlay: bool = False) -> dict:
276
314
  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]}
315
+ "repos": [collect_repo(path, kinds, known, prs_map, overlay) for path in repos]}
278
316
  for kind, call in (("spend", _spend_json), ("guide", _guide_json)):
279
317
  if kind not in kinds:
280
318
  continue
@@ -300,6 +338,7 @@ def main(argv: list[str] | None = None) -> int:
300
338
  parser.add_argument("--repos", nargs="+", required=True, metavar="PATH")
301
339
  parser.add_argument("--only", default=",".join(KINDS), help="comma list of: " + ", ".join(KINDS))
302
340
  parser.add_argument("--known", nargs="+", default=[], metavar="PATH=FP")
341
+ parser.add_argument("--prs-file", default=None, metavar="PATH")
303
342
  parser.add_argument("--json", action="store_true", required=True)
304
343
  args = parser.parse_args(argv)
305
344
  kinds = tuple(k.strip() for k in args.only.split(",") if k.strip())
@@ -310,7 +349,9 @@ def main(argv: list[str] | None = None) -> int:
310
349
  known = parse_known(args.known)
311
350
  except ValueError as exc:
312
351
  parser.error(str(exc))
313
- print(json.dumps(collect(args.repos, kinds, known), ensure_ascii=False))
352
+ overlay = args.prs_file is not None
353
+ prs_map = load_prs(args.prs_file) if overlay else None
354
+ print(json.dumps(collect(args.repos, kinds, known, prs_map, overlay), ensure_ascii=False))
314
355
  return 0
315
356
 
316
357
 
@@ -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).