@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
@@ -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
 
@@ -281,24 +344,30 @@ class _Batch:
281
344
  self.proc.stdout.close()
282
345
 
283
346
 
284
- def _tree_blobs(tree: bytes, oid_len: int) -> list[tuple[str, str]]:
285
- """[(name, blob oid)] from a raw tree object: `<mode> <name>\\0<oid bytes>` repeated. Files only."""
286
- out: list[tuple[str, str]] = []
347
+ def _tree_entries(tree: bytes, oid_len: int) -> list[tuple[bytes, str, str]]:
348
+ """[(mode, name, oid)] from a raw tree object: `<mode> <name>\\0<oid bytes>` repeated."""
349
+ out: list[tuple[bytes, str, str]] = []
287
350
  at = 0
288
351
  while at < len(tree):
289
352
  space = tree.index(b" ", at)
290
353
  nul = tree.index(b"\0", space)
291
354
  mode, name = tree[at:space], tree[space + 1:nul].decode("utf-8", errors="replace")
292
- oid = tree[nul + 1:nul + 1 + oid_len].hex()
355
+ out.append((mode, name, tree[nul + 1:nul + 1 + oid_len].hex()))
293
356
  at = nul + 1 + oid_len
294
- if mode in (b"100644", b"100755"):
295
- out.append((name, oid))
296
357
  return out
297
358
 
298
359
 
299
- def _origin_plan_texts(root: Path, branch: str) -> tuple[str, int | None, list[tuple[str, str]]] | None:
300
- """(commit_oid, commit_at, [(path, text)]) of the plan files on origin/<branch>: `.caddis/plans/*.md`, else
301
- `.github/plans/*.md`, never `done/`. One git process for the whole read. None when git cannot read the ref."""
360
+ def _tree_blobs(tree: bytes, oid_len: int) -> list[tuple[str, str]]:
361
+ """[(name, blob oid)] from a raw tree object. Files only."""
362
+ return [(name, oid) for mode, name, oid in _tree_entries(tree, oid_len) if mode in (b"100644", b"100755")]
363
+
364
+
365
+ def _origin_plan_texts(root: Path, branch: str
366
+ ) -> tuple[str, int | None, list[tuple[str, str]], str | None] | None:
367
+ """(commit_oid, commit_at, [(path, text)], done_tree) of the plan files on origin/<branch>: `.caddis/plans/*.md`,
368
+ else `.github/plans/*.md`, never `done/`. `done_tree` is the oid of `<folder>/done` for the folder that held the
369
+ plans (`.caddis/plans` when none did), read from the folder's tree object, or None when there is no such tree.
370
+ One git process for the whole read. None when git cannot read the ref."""
302
371
  try:
303
372
  batch = _Batch(root)
304
373
  except OSError:
@@ -317,12 +386,18 @@ def _origin_plan_texts(root: Path, branch: str) -> tuple[str, int | None, list[t
317
386
  commit_at = int(line.split()[-2])
318
387
  except (IndexError, ValueError):
319
388
  commit_at = None
320
- for folder in (".caddis/plans", ".github/plans"):
389
+ default_done: str | None = None # the done tree of `.caddis/plans` when no folder holds a current plan
390
+ for folder in (_PLANS_DIR, ".github/plans"):
321
391
  tree = batch.get(f"refs/remotes/origin/{branch}:{folder}")
322
392
  if tree is None or tree[1] != "tree":
323
393
  continue
324
- names = sorted((name, oid) for name, oid in _tree_blobs(tree[2], len(tree[0]) // 2) if name.endswith(".md"))
394
+ entries = _tree_entries(tree[2], len(tree[0]) // 2)
395
+ done_tree = next((oid for mode, name, oid in entries if name == "done" and mode == b"40000"), None)
396
+ names = sorted((name, oid) for mode, name, oid in entries
397
+ if mode in (b"100644", b"100755") and name.endswith(".md"))
325
398
  if not names:
399
+ if folder == _PLANS_DIR:
400
+ default_done = done_tree
326
401
  continue
327
402
  texts: list[tuple[str, str]] = []
328
403
  for name, oid in names:
@@ -330,8 +405,8 @@ def _origin_plan_texts(root: Path, branch: str) -> tuple[str, int | None, list[t
330
405
  if blob is None:
331
406
  return None
332
407
  texts.append((f"{folder}/{name}", blob[2].decode("utf-8", errors="replace").replace("\r\n", "\n")))
333
- return commit_oid, commit_at, texts
334
- return commit_oid, commit_at, []
408
+ return commit_oid, commit_at, texts, done_tree
409
+ return commit_oid, commit_at, [], default_done
335
410
  except (OSError, ValueError):
336
411
  return None
337
412
  finally:
@@ -367,6 +442,106 @@ def _origin_plan_times(root: Path, branch: str, folder: str) -> dict[str, int]:
367
442
  return times
368
443
 
369
444
 
445
+ _PR_SUFFIX = re.compile(r"\(#(\d+)\)")
446
+ _PR_MERGE = re.compile(r"\bMerge pull request #(\d+)\b")
447
+ _TITLE_SUFFIX = re.compile(r"\s+[—–-]+\s*Implementation Plan\s*$", re.I)
448
+
449
+
450
+ def pr_of_subject(subject: str) -> int | None:
451
+ """D3: the PR a commit subject names: the last `(#n)` (squash and Gitea merges), else `Merge pull request #n`."""
452
+ found = _PR_SUFFIX.findall(subject)
453
+ if found:
454
+ return int(found[-1])
455
+ merge = _PR_MERGE.search(subject)
456
+ return int(merge.group(1)) if merge else None
457
+
458
+
459
+ def done_entry(rel: str, text: str, closed_at: int | None, pr: int | None) -> dict:
460
+ """D5: one done-plan row. Title from the first `# ` heading less ` — Implementation Plan`; phases = Tracker
461
+ rows, else unique `Phase` headings."""
462
+ entry = _plan_entry_text(rel, text)
463
+ title = entry["title"] if isinstance(entry["title"], str) and entry["title"].strip() else None
464
+ title = (_TITLE_SUFFIX.sub("", title).strip() if title else "") or rel.rsplit("/", 1)[-1].removesuffix(".md")
465
+ return {"path": rel, "title": title, "closed_at": closed_at,
466
+ "phases": len(entry["tracker"]) or len(entry["phases"]), "pr": pr}
467
+
468
+
469
+ def _origin_done_adds(root: Path, branch: str, folder: str) -> dict[str, tuple[int, int | None]]:
470
+ """{path: (commit time, PR)} of the newest first-parent commit on origin/<branch> that ADDED each file under
471
+ `<folder>/done` (D3). One local git process. Empty when git fails: the date is shown as unknown."""
472
+ try:
473
+ out = subprocess.run(
474
+ ["git", "-C", str(root), "-c", "core.quotepath=off", "log", "--no-renames", "--first-parent",
475
+ "--diff-merges=first-parent", "--diff-filter=A", "--format=%x00%ct%x09%s", "--name-only",
476
+ f"refs/remotes/origin/{branch}", "--", f"{folder}/done"],
477
+ capture_output=True, timeout=30, creationflags=_NO_WINDOW,
478
+ )
479
+ except (OSError, subprocess.SubprocessError):
480
+ return {}
481
+ if out.returncode != 0:
482
+ return {}
483
+ adds: dict[str, tuple[int, int | None]] = {}
484
+ for chunk in out.stdout.decode("utf-8", errors="replace").split("\x00")[1:]:
485
+ lines = chunk.splitlines()
486
+ if not lines:
487
+ continue
488
+ when, _, subject = lines[0].partition("\t")
489
+ try:
490
+ at = int(when)
491
+ except ValueError:
492
+ continue
493
+ pr = pr_of_subject(subject)
494
+ for name in lines[1:]:
495
+ if name.strip():
496
+ adds.setdefault(name.strip(), (at, pr)) # git log is newest first: the first add seen is the newest
497
+ return adds
498
+
499
+
500
+ def done_plans(root: Path, branch: str, folder: str, tree_oid: str) -> dict:
501
+ """`{"tree": tree_oid, "plans": [...]}`: every `<folder>/done/*.md` in the tree, newest close first, then path
502
+ A-Z; no close date sorts last (D4). One `git log` and one `cat-file --batch`. A file that fails gives
503
+ `{"path", "error"}`."""
504
+ adds = _origin_done_adds(root, branch, folder)
505
+ rows: list[dict] = []
506
+ batch = _Batch(root)
507
+ try:
508
+ tree = batch.get(tree_oid)
509
+ if tree is None or tree[1] != "tree":
510
+ raise ValueError(f"{folder}/done is not a tree on origin/{branch}")
511
+ for name, oid in sorted(_tree_blobs(tree[2], len(tree[0]) // 2)):
512
+ if not name.endswith(".md"):
513
+ continue
514
+ rel = f"{folder}/done/{name}"
515
+ blob = batch.get(oid)
516
+ if blob is None:
517
+ rows.append({"path": rel, "error": "the file is missing from the git store"})
518
+ continue
519
+ text = blob[2].decode("utf-8", errors="replace").replace("\r\n", "\n")
520
+ closed_at, pr = adds.get(rel, (None, None))
521
+ rows.append(_entry_or_error(rel, lambda rel=rel, text=text, closed_at=closed_at, pr=pr:
522
+ done_entry(rel, text, closed_at, pr)))
523
+ finally:
524
+ batch.close()
525
+
526
+ def order(row: dict) -> tuple:
527
+ at = adds.get(row["path"], (None, None))[0]
528
+ return (at is None, -(at or 0), row["path"])
529
+
530
+ return {"tree": tree_oid, "plans": sorted(rows, key=order)}
531
+
532
+
533
+ def _done_slot(root: Path, branch: str, folder: str, tree: str | None, known: str | None) -> dict:
534
+ """D2/D6: the `done` value of an origin source."""
535
+ if tree is None:
536
+ return {"tree": None, "plans": []}
537
+ if tree == known:
538
+ return {"tree": tree, "unchanged": True}
539
+ try:
540
+ return done_plans(root, branch, folder, tree)
541
+ except Exception as exc: # done plans must never hide the current plans
542
+ return {"error": (str(exc).splitlines() or [type(exc).__name__])[0]}
543
+
544
+
370
545
  def _file_time(path: Path) -> int | None:
371
546
  try:
372
547
  return int(path.stat().st_mtime)
@@ -381,30 +556,151 @@ def _entry_or_error(rel: str, read) -> dict:
381
556
  return {"path": rel, "error": (str(exc).splitlines() or [type(exc).__name__])[0]}
382
557
 
383
558
 
384
- def plans_json(root: Path, branch: str | None = None) -> dict:
559
+ MAX_PRS = 20 # D3: per repo, only the newest open PRs are looked at (bounds the merge-base cost)
560
+ _HEAD_REF = re.compile(r"^(?!-|/)(?!.*\.\.)[^\x00-\x20\x7f:~^?*\[\\]+$") # D3: a ref name git and `cat-file --batch` accept
561
+ _PLANS_DIR = ".caddis/plans"
562
+
563
+
564
+ def branch_plan_changes(batch: _Batch, root: Path, default_branch: str, head_ref: str
565
+ ) -> dict[str, tuple[str, str | None]] | None:
566
+ """The plan files a PR branch changed: `{".caddis/plans/<name>.md": (head_text, merge_base_text_or_None)}`.
567
+
568
+ Local git only. None when `refs/remotes/origin/<head_ref>` is missing or `git merge-base` fails; {} when the
569
+ plans folder is the same tree on head and default (no `merge-base` runs) or no plan file differs.
570
+ """
571
+ head_ref_name = f"refs/remotes/origin/{head_ref}"
572
+ default_ref_name = f"refs/remotes/origin/{default_branch}"
573
+ if batch.get(head_ref_name) is None:
574
+ return None
575
+ head_tree = batch.get(f"{head_ref_name}:{_PLANS_DIR}")
576
+ default_tree = batch.get(f"{default_ref_name}:{_PLANS_DIR}")
577
+ if head_tree is None or head_tree[1] != "tree":
578
+ return {} # the branch has no plan folder: it deletes or never had plans, nothing to overlay
579
+ if default_tree is not None and default_tree[0] == head_tree[0]:
580
+ return {}
581
+ try:
582
+ found = subprocess.run(["git", "-C", str(root), "merge-base", default_ref_name, head_ref_name],
583
+ capture_output=True, timeout=30, creationflags=_NO_WINDOW)
584
+ except (OSError, subprocess.SubprocessError):
585
+ return None
586
+ base = found.stdout.decode("ascii", errors="replace").strip()
587
+ if found.returncode != 0 or not base:
588
+ return None
589
+ base_tree = batch.get(f"{base}:{_PLANS_DIR}")
590
+ base_blobs = dict(_tree_blobs(base_tree[2], len(base_tree[0]) // 2)) if base_tree and base_tree[1] == "tree" else {}
591
+ changes: dict[str, tuple[str, str | None]] = {}
592
+ for name, oid in sorted(_tree_blobs(head_tree[2], len(head_tree[0]) // 2)):
593
+ if not name.endswith(".md") or base_blobs.get(name) == oid:
594
+ continue
595
+ head_blob = batch.get(oid)
596
+ if head_blob is None:
597
+ continue
598
+ base_blob = batch.get(base_blobs[name]) if name in base_blobs else None
599
+ changes[f"{_PLANS_DIR}/{name}"] = (
600
+ head_blob[2].decode("utf-8", errors="replace").replace("\r\n", "\n"),
601
+ base_blob[2].decode("utf-8", errors="replace").replace("\r\n", "\n") if base_blob else None)
602
+ return changes
603
+
604
+
605
+ def _usable_prs(prs: list[dict], branch: str) -> list[dict]:
606
+ """D3: same-repo PRs with a safe head ref that is not the default branch; the newest MAX_PRS of them."""
607
+ usable = []
608
+ for pr in prs:
609
+ if not isinstance(pr, dict) or pr.get("fork") or isinstance(pr.get("number"), bool) \
610
+ or not isinstance(pr.get("number"), int):
611
+ continue
612
+ ref = pr.get("head_ref")
613
+ if not isinstance(ref, str) or not ref or ref == branch or not _HEAD_REF.fullmatch(ref):
614
+ continue
615
+ usable.append({**pr, "updated_at": pr["updated_at"] if isinstance(pr.get("updated_at"), str) else ""})
616
+ usable.sort(key=lambda pr: (pr["updated_at"], pr["number"]), reverse=True)
617
+ return usable[:MAX_PRS]
618
+
619
+
620
+ def _overlay_prs(root: Path, branch: str, plans: list[dict], prs: list[dict]) -> int:
621
+ """Lay open PR branches over `plans` (changed in place). Returns how many plans got an overlay."""
622
+ usable = _usable_prs(prs, branch)
623
+ if not usable:
624
+ return 0
625
+ try:
626
+ batch = _Batch(root)
627
+ except OSError:
628
+ return 0
629
+ cands: dict[str, list[tuple[dict, dict, dict | None]]] = {} # plan path -> [(pr, head entry, base entry)]
630
+ try:
631
+ for pr in usable:
632
+ try:
633
+ changes = branch_plan_changes(batch, root, branch, pr["head_ref"])
634
+ except (OSError, ValueError):
635
+ changes = None
636
+ for path, (head_text, base_text) in (changes or {}).items():
637
+ try:
638
+ head = _plan_entry_text(path, head_text)
639
+ base = _plan_entry_text(path, base_text) if base_text is not None else None
640
+ except Exception: # a branch plan that does not parse is skipped; main shows
641
+ continue
642
+ cands.setdefault(path, []).append((pr, head, base))
643
+ finally:
644
+ batch.close()
645
+ by_path = {plan["path"]: i for i, plan in enumerate(plans)}
646
+ count = 0
647
+ for path, found in cands.items():
648
+ pr, also = pick_pr([item[0] for item in found])
649
+ _, head, base = next(item for item in found if item[0] is pr)
650
+ at = by_path.get(path)
651
+ if at is None:
652
+ if base is not None:
653
+ continue # main deleted a plan the branch still edits: a deleted plan is not shown from the branch
654
+ plans.append(overlay_plan(None, None, head, pr, also))
655
+ elif "error" in plans[at]:
656
+ continue
657
+ else:
658
+ plans[at] = overlay_plan(plans[at], base, head, pr, also)
659
+ count += 1
660
+ return count
661
+
662
+
663
+ def plans_json(root: Path, branch: str | None = None, prs: list[dict] | None = None,
664
+ done_known: str | None = None) -> dict:
385
665
  """Every current plan as data: `{"schema": 1, "source": ..., "plans": [...]}`. Never prints, never exits.
386
666
 
387
667
  With `branch`, read the plans from the local `origin/<branch>` ref (the hub: a pushed Tracker edit shows with
388
668
  no pull); when git cannot read that ref, read the working tree. `source` names which one was read. A file that
389
669
  does not parse gives `{"path", "error"}`; the other plans still come back.
670
+
671
+ An origin source also carries `done` (the finished plans in `<folder>/done`): `{"tree": None, "plans": []}`
672
+ with no done tree, `{"tree": t, "unchanged": True}` when `t == done_known` (the caller keeps its list),
673
+ `{"tree": t, "plans": [...]}` (`done_plans`), or `{"error": ...}`. A working-tree source has no `done` key.
674
+
675
+ With `prs` (the open PRs, D2 items) and an origin source, plans a PR branch changed get that branch's Tracker
676
+ laid over main's (`overlay_plan`) and the result carries `overlay`. Without `prs` the output has no overlay key.
390
677
  """
391
678
  root = Path(root)
392
679
  origin = _origin_plan_texts(root, branch) if branch else None
393
680
  if origin is not None:
394
- commit, commit_at, texts = origin
681
+ commit, commit_at, texts, done_tree = origin
682
+ folder = texts[0][0].rsplit("/", 1)[0] if texts else _PLANS_DIR
395
683
  plans = [_entry_or_error(rel, lambda rel=rel, text=text: _plan_entry_text(rel, text)) for rel, text in texts]
396
- times = _origin_plan_times(root, branch, texts[0][0].rsplit("/", 1)[0]) if texts else {}
684
+ times = _origin_plan_times(root, branch, folder) if texts else {}
397
685
  for plan in plans:
398
686
  if "error" not in plan:
399
687
  plan["changed_at"] = times.get(plan["path"])
400
- return {"schema": 1, "source": f"origin/{branch}", "commit": commit[:12], "commit_at": commit_at, "plans": plans}
688
+ data = {"schema": 1, "source": f"origin/{branch}", "commit": commit[:12], "commit_at": commit_at, "plans": plans,
689
+ "done": _done_slot(root, branch, folder, done_tree, done_known)}
690
+ if prs is not None:
691
+ count = _overlay_prs(root, branch, plans, prs)
692
+ data["overlay"] = {"state": "on", "reason": None, "count": count}
693
+ return data
401
694
  plans = []
402
695
  for path in _plan_files(root):
403
696
  plan = _entry_or_error(path.relative_to(root).as_posix(), lambda path=path: _plan_entry(root, path))
404
697
  if "error" not in plan:
405
698
  plan["changed_at"] = _file_time(path)
406
699
  plans.append(plan)
407
- return {"schema": 1, "source": "working-tree", "plans": plans}
700
+ data = {"schema": 1, "source": "working-tree", "plans": plans}
701
+ if prs is not None:
702
+ data["overlay"] = {"state": "off", "reason": "no git", "count": 0}
703
+ return data
408
704
 
409
705
 
410
706
  def main(argv: list[str] | None = None) -> int:
@@ -364,6 +364,87 @@
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
+ },
392
+ "done": {
393
+ "description": "Finished plans from origin/<default>:.caddis/plans/done (origin source only). unchanged: the tree equals --done-known.",
394
+ "type": "object",
395
+ "properties": {
396
+ "tree": {
397
+ "type": [
398
+ "string",
399
+ "null"
400
+ ]
401
+ },
402
+ "unchanged": {
403
+ "const": true
404
+ },
405
+ "error": {
406
+ "type": "string"
407
+ },
408
+ "plans": {
409
+ "type": "array",
410
+ "items": {
411
+ "type": "object",
412
+ "required": [
413
+ "path"
414
+ ],
415
+ "properties": {
416
+ "path": {
417
+ "type": "string"
418
+ },
419
+ "title": {
420
+ "type": [
421
+ "string",
422
+ "null"
423
+ ]
424
+ },
425
+ "closed_at": {
426
+ "type": [
427
+ "integer",
428
+ "null"
429
+ ]
430
+ },
431
+ "phases": {
432
+ "type": "integer"
433
+ },
434
+ "pr": {
435
+ "type": [
436
+ "integer",
437
+ "null"
438
+ ]
439
+ },
440
+ "error": {
441
+ "type": "string"
442
+ }
443
+ }
444
+ }
445
+ }
446
+ }
447
+ },
367
448
  "plans": {
368
449
  "type": "array",
369
450
  "items": {
@@ -425,6 +506,12 @@
425
506
  "done",
426
507
  "moved"
427
508
  ]
509
+ },
510
+ "source": {
511
+ "enum": [
512
+ "main",
513
+ "branch"
514
+ ]
428
515
  }
429
516
  }
430
517
  }
@@ -433,8 +520,37 @@
433
520
  "type": "integer"
434
521
  },
435
522
  "changed_at": {
436
- "type": ["integer", "null"],
523
+ "type": [
524
+ "integer",
525
+ "null"
526
+ ],
437
527
  "description": "Unix time of the last change: the commit time on origin, or the file time in the working tree. null when unknown."
528
+ },
529
+ "overlay": {
530
+ "type": "object",
531
+ "required": [
532
+ "pr",
533
+ "draft",
534
+ "head_ref",
535
+ "also"
536
+ ],
537
+ "properties": {
538
+ "pr": {
539
+ "type": "integer"
540
+ },
541
+ "draft": {
542
+ "type": "boolean"
543
+ },
544
+ "head_ref": {
545
+ "type": "string"
546
+ },
547
+ "also": {
548
+ "type": "array",
549
+ "items": {
550
+ "type": "integer"
551
+ }
552
+ }
553
+ }
438
554
  }
439
555
  }
440
556
  },