@caddis/cli 0.4.95 → 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 (37) 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_gate.py +19 -2
  16. package/bundles/antigravity-plugin/scripts/caddis_guide.json +2 -2
  17. package/bundles/antigravity-plugin/scripts/caddis_hub_collect.py +51 -10
  18. package/bundles/antigravity-plugin/scripts/caddis_lanes.py +154 -130
  19. package/bundles/antigravity-plugin/scripts/caddis_todo.py +180 -3
  20. package/bundles/antigravity-plugin/scripts/schemas/hub-collect.schema.json +57 -0
  21. package/bundles/antigravity-plugin/scripts/schemas/hub-plans.schema.json +57 -0
  22. package/bundles/antigravity-plugin/scripts/setup_project_ai.py +13 -1
  23. package/bundles/antigravity-plugin/scripts/templates/coordinator.md +3 -3
  24. package/bundles/antigravity-plugin/skills/coordinate/SKILL.md +4 -1
  25. package/bundles/antigravity-plugin/skills/handoff/SKILL.md +21 -8
  26. package/bundles/manifest.json +2 -2
  27. package/dist/cli.js +214 -71
  28. package/dist/export/assets/{export-CMtV-slT.css → export-B5Lzo-9e.css} +1 -1
  29. package/dist/export/assets/{export-DtlDFN4L.js → export-PF4z_ff4.js} +29 -29
  30. package/dist/export/index.html +2 -2
  31. package/dist/ui/assets/{Activity-BDjet2xd.js → Activity-DN1XBfsH.js} +1 -1
  32. package/dist/ui/assets/{Guide-Czn5sK0f.js → Guide-D-lZVEKf.js} +1 -1
  33. package/dist/ui/assets/{RoadmapTab-Bd8geyQx.js → RoadmapTab-tqQd2sYq.js} +7 -7
  34. package/dist/ui/assets/{index-CmngQ8Mk.js → index-CWslZIzV.js} +44 -44
  35. package/dist/ui/assets/{index-Bd0Z4jR8.css → index-CwgRPpjT.css} +1 -1
  36. package/dist/ui/index.html +2 -2
  37. package/package.json +1 -1
@@ -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).
@@ -9,6 +9,7 @@ release as a no-op, because an older /handoff still calls it from its Step 6.
9
9
  from __future__ import annotations
10
10
 
11
11
  import argparse
12
+ import copy
12
13
  import json
13
14
  import os
14
15
  import re
@@ -250,6 +251,68 @@ def _plan_entry_text(rel: str, text: str) -> dict:
250
251
  "tracker": tracker, "open_rows": sum(1 for row in tracker if not _is_done(row["status"]))}
251
252
 
252
253
 
254
+ PLAN_STATUS_RANK: dict[str, int] = {"draft": 0, "proposed": 0, "ready": 0, "current": 1, "done": 2, "superseded": 2}
255
+
256
+
257
+ def _status_rank(status: object) -> int:
258
+ return PLAN_STATUS_RANK.get(status, 0) if isinstance(status, str) else 0
259
+
260
+
261
+ def pick_pr(cands: list[dict]) -> tuple[dict, list[int]]:
262
+ """D6: the PR with the newest `updated_at` (ISO text compare; tie: higher number) and the others' numbers."""
263
+ best = max(cands, key=lambda pr: (pr["updated_at"], pr["number"]))
264
+ return best, sorted(pr["number"] for pr in cands if pr is not best)
265
+
266
+
267
+ def _first_by_key(rows: list[dict]) -> dict[str, dict]:
268
+ """D4.6: the first row with each non-empty key."""
269
+ out: dict[str, dict] = {}
270
+ for row in rows:
271
+ if row["key"] and row["key"] not in out:
272
+ out[row["key"]] = row
273
+ return out
274
+
275
+
276
+ def overlay_plan(main: dict | None, base: dict | None, head: dict, pr: dict, also: list[int]) -> dict:
277
+ """One plan with an open PR branch laid over main: rows by D4, plan status by D5. Inputs are never changed."""
278
+ overlay = {"pr": pr["number"], "draft": bool(pr.get("draft")), "head_ref": pr["head_ref"], "also": list(also)}
279
+ if main is None: # D5: a plan only on the branch takes every field from the head entry
280
+ out = copy.deepcopy(head)
281
+ out["tracker"] = [{**row, "source": "branch"} for row in out["tracker"]]
282
+ out["changed_at"] = None
283
+ else:
284
+ out = copy.deepcopy(main)
285
+ heads = _first_by_key(head["tracker"])
286
+ bases = _first_by_key(base["tracker"]) if base is not None else {}
287
+
288
+ def untouched(h: dict) -> bool: # D4.2 / D4.4: the branch left the row as it was at the merge base
289
+ b = bases.get(h["key"])
290
+ return b is not None and h["status"] == b["status"]
291
+
292
+ tracker: list[dict] = []
293
+ matched: set[str] = set()
294
+ for m in out["tracker"]:
295
+ h = heads.get(m["key"]) if m["key"] and m["key"] not in matched else None
296
+ if m["key"]:
297
+ matched.add(m["key"])
298
+ if h is None or untouched(h): # D4.1, D4.2 (and D4.5: an empty key is kept)
299
+ tracker.append({**m, "source": "main"})
300
+ elif m["state"] in ("done", "moved") and h["state"] not in ("done", "moved"): # D4.3: done never goes back
301
+ tracker.append({**m, "source": "main"})
302
+ else:
303
+ tracker.append({**copy.deepcopy(h), "source": "branch"})
304
+ for key, h in heads.items(): # D4.4: dict order is head order
305
+ if key not in matched and not untouched(h):
306
+ tracker.append({**copy.deepcopy(h), "source": "branch"})
307
+ out["tracker"] = tracker
308
+ base_status = base.get("status") if base is not None else None
309
+ if (base is None or head.get("status") != base_status) and _status_rank(main.get("status")) != 2:
310
+ out["status"] = head.get("status")
311
+ out["open_rows"] = sum(1 for row in out["tracker"] if not _is_done(row["status"]))
312
+ out["overlay"] = overlay
313
+ return out
314
+
315
+
253
316
  class _Batch:
254
317
  """One `git cat-file --batch` process, asked object by object (local git only, no network)."""
255
318
 
@@ -381,12 +444,119 @@ def _entry_or_error(rel: str, read) -> dict:
381
444
  return {"path": rel, "error": (str(exc).splitlines() or [type(exc).__name__])[0]}
382
445
 
383
446
 
384
- def plans_json(root: Path, branch: str | None = None) -> dict:
447
+ MAX_PRS = 20 # D3: per repo, only the newest open PRs are looked at (bounds the merge-base cost)
448
+ _HEAD_REF = re.compile(r"^(?!-|/)(?!.*\.\.)[^\x00-\x20\x7f:~^?*\[\\]+$") # D3: a ref name git and `cat-file --batch` accept
449
+ _PLANS_DIR = ".caddis/plans"
450
+
451
+
452
+ def branch_plan_changes(batch: _Batch, root: Path, default_branch: str, head_ref: str
453
+ ) -> dict[str, tuple[str, str | None]] | None:
454
+ """The plan files a PR branch changed: `{".caddis/plans/<name>.md": (head_text, merge_base_text_or_None)}`.
455
+
456
+ Local git only. None when `refs/remotes/origin/<head_ref>` is missing or `git merge-base` fails; {} when the
457
+ plans folder is the same tree on head and default (no `merge-base` runs) or no plan file differs.
458
+ """
459
+ head_ref_name = f"refs/remotes/origin/{head_ref}"
460
+ default_ref_name = f"refs/remotes/origin/{default_branch}"
461
+ if batch.get(head_ref_name) is None:
462
+ return None
463
+ head_tree = batch.get(f"{head_ref_name}:{_PLANS_DIR}")
464
+ default_tree = batch.get(f"{default_ref_name}:{_PLANS_DIR}")
465
+ if head_tree is None or head_tree[1] != "tree":
466
+ return {} # the branch has no plan folder: it deletes or never had plans, nothing to overlay
467
+ if default_tree is not None and default_tree[0] == head_tree[0]:
468
+ return {}
469
+ try:
470
+ found = subprocess.run(["git", "-C", str(root), "merge-base", default_ref_name, head_ref_name],
471
+ capture_output=True, timeout=30, creationflags=_NO_WINDOW)
472
+ except (OSError, subprocess.SubprocessError):
473
+ return None
474
+ base = found.stdout.decode("ascii", errors="replace").strip()
475
+ if found.returncode != 0 or not base:
476
+ return None
477
+ base_tree = batch.get(f"{base}:{_PLANS_DIR}")
478
+ base_blobs = dict(_tree_blobs(base_tree[2], len(base_tree[0]) // 2)) if base_tree and base_tree[1] == "tree" else {}
479
+ changes: dict[str, tuple[str, str | None]] = {}
480
+ for name, oid in sorted(_tree_blobs(head_tree[2], len(head_tree[0]) // 2)):
481
+ if not name.endswith(".md") or base_blobs.get(name) == oid:
482
+ continue
483
+ head_blob = batch.get(oid)
484
+ if head_blob is None:
485
+ continue
486
+ base_blob = batch.get(base_blobs[name]) if name in base_blobs else None
487
+ changes[f"{_PLANS_DIR}/{name}"] = (
488
+ head_blob[2].decode("utf-8", errors="replace").replace("\r\n", "\n"),
489
+ base_blob[2].decode("utf-8", errors="replace").replace("\r\n", "\n") if base_blob else None)
490
+ return changes
491
+
492
+
493
+ def _usable_prs(prs: list[dict], branch: str) -> list[dict]:
494
+ """D3: same-repo PRs with a safe head ref that is not the default branch; the newest MAX_PRS of them."""
495
+ usable = []
496
+ for pr in prs:
497
+ if not isinstance(pr, dict) or pr.get("fork") or isinstance(pr.get("number"), bool) \
498
+ or not isinstance(pr.get("number"), int):
499
+ continue
500
+ ref = pr.get("head_ref")
501
+ if not isinstance(ref, str) or not ref or ref == branch or not _HEAD_REF.fullmatch(ref):
502
+ continue
503
+ usable.append({**pr, "updated_at": pr["updated_at"] if isinstance(pr.get("updated_at"), str) else ""})
504
+ usable.sort(key=lambda pr: (pr["updated_at"], pr["number"]), reverse=True)
505
+ return usable[:MAX_PRS]
506
+
507
+
508
+ def _overlay_prs(root: Path, branch: str, plans: list[dict], prs: list[dict]) -> int:
509
+ """Lay open PR branches over `plans` (changed in place). Returns how many plans got an overlay."""
510
+ usable = _usable_prs(prs, branch)
511
+ if not usable:
512
+ return 0
513
+ try:
514
+ batch = _Batch(root)
515
+ except OSError:
516
+ return 0
517
+ cands: dict[str, list[tuple[dict, dict, dict | None]]] = {} # plan path -> [(pr, head entry, base entry)]
518
+ try:
519
+ for pr in usable:
520
+ try:
521
+ changes = branch_plan_changes(batch, root, branch, pr["head_ref"])
522
+ except (OSError, ValueError):
523
+ changes = None
524
+ for path, (head_text, base_text) in (changes or {}).items():
525
+ try:
526
+ head = _plan_entry_text(path, head_text)
527
+ base = _plan_entry_text(path, base_text) if base_text is not None else None
528
+ except Exception: # a branch plan that does not parse is skipped; main shows
529
+ continue
530
+ cands.setdefault(path, []).append((pr, head, base))
531
+ finally:
532
+ batch.close()
533
+ by_path = {plan["path"]: i for i, plan in enumerate(plans)}
534
+ count = 0
535
+ for path, found in cands.items():
536
+ pr, also = pick_pr([item[0] for item in found])
537
+ _, head, base = next(item for item in found if item[0] is pr)
538
+ at = by_path.get(path)
539
+ if at is None:
540
+ if base is not None:
541
+ continue # main deleted a plan the branch still edits: a deleted plan is not shown from the branch
542
+ plans.append(overlay_plan(None, None, head, pr, also))
543
+ elif "error" in plans[at]:
544
+ continue
545
+ else:
546
+ plans[at] = overlay_plan(plans[at], base, head, pr, also)
547
+ count += 1
548
+ return count
549
+
550
+
551
+ def plans_json(root: Path, branch: str | None = None, prs: list[dict] | None = None) -> dict:
385
552
  """Every current plan as data: `{"schema": 1, "source": ..., "plans": [...]}`. Never prints, never exits.
386
553
 
387
554
  With `branch`, read the plans from the local `origin/<branch>` ref (the hub: a pushed Tracker edit shows with
388
555
  no pull); when git cannot read that ref, read the working tree. `source` names which one was read. A file that
389
556
  does not parse gives `{"path", "error"}`; the other plans still come back.
557
+
558
+ With `prs` (the open PRs, D2 items) and an origin source, plans a PR branch changed get that branch's Tracker
559
+ laid over main's (`overlay_plan`) and the result carries `overlay`. Without `prs` the output has no overlay key.
390
560
  """
391
561
  root = Path(root)
392
562
  origin = _origin_plan_texts(root, branch) if branch else None
@@ -397,14 +567,21 @@ def plans_json(root: Path, branch: str | None = None) -> dict:
397
567
  for plan in plans:
398
568
  if "error" not in plan:
399
569
  plan["changed_at"] = times.get(plan["path"])
400
- return {"schema": 1, "source": f"origin/{branch}", "commit": commit[:12], "commit_at": commit_at, "plans": plans}
570
+ data = {"schema": 1, "source": f"origin/{branch}", "commit": commit[:12], "commit_at": commit_at, "plans": plans}
571
+ if prs is not None:
572
+ count = _overlay_prs(root, branch, plans, prs)
573
+ data["overlay"] = {"state": "on", "reason": None, "count": count}
574
+ return data
401
575
  plans = []
402
576
  for path in _plan_files(root):
403
577
  plan = _entry_or_error(path.relative_to(root).as_posix(), lambda path=path: _plan_entry(root, path))
404
578
  if "error" not in plan:
405
579
  plan["changed_at"] = _file_time(path)
406
580
  plans.append(plan)
407
- return {"schema": 1, "source": "working-tree", "plans": plans}
581
+ data = {"schema": 1, "source": "working-tree", "plans": plans}
582
+ if prs is not None:
583
+ data["overlay"] = {"state": "off", "reason": "no git", "count": 0}
584
+ return data
408
585
 
409
586
 
410
587
  def main(argv: list[str] | None = None) -> int:
@@ -364,6 +364,31 @@
364
364
  }
365
365
  ]
366
366
  },
367
+ "overlay": {
368
+ "type": "object",
369
+ "required": [
370
+ "state",
371
+ "reason",
372
+ "count"
373
+ ],
374
+ "properties": {
375
+ "state": {
376
+ "enum": [
377
+ "on",
378
+ "off"
379
+ ]
380
+ },
381
+ "reason": {
382
+ "type": [
383
+ "string",
384
+ "null"
385
+ ]
386
+ },
387
+ "count": {
388
+ "type": "integer"
389
+ }
390
+ }
391
+ },
367
392
  "plans": {
368
393
  "type": "array",
369
394
  "items": {
@@ -425,6 +450,12 @@
425
450
  "done",
426
451
  "moved"
427
452
  ]
453
+ },
454
+ "source": {
455
+ "enum": [
456
+ "main",
457
+ "branch"
458
+ ]
428
459
  }
429
460
  }
430
461
  }
@@ -435,6 +466,32 @@
435
466
  "changed_at": {
436
467
  "type": ["integer", "null"],
437
468
  "description": "Unix time of the last change: the commit time on origin, or the file time in the working tree. null when unknown."
469
+ },
470
+ "overlay": {
471
+ "type": "object",
472
+ "required": [
473
+ "pr",
474
+ "draft",
475
+ "head_ref",
476
+ "also"
477
+ ],
478
+ "properties": {
479
+ "pr": {
480
+ "type": "integer"
481
+ },
482
+ "draft": {
483
+ "type": "boolean"
484
+ },
485
+ "head_ref": {
486
+ "type": "string"
487
+ },
488
+ "also": {
489
+ "type": "array",
490
+ "items": {
491
+ "type": "integer"
492
+ }
493
+ }
494
+ }
438
495
  }
439
496
  }
440
497
  },