@caddis/cli 0.4.84 → 0.4.86

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/bundles/antigravity-plugin/plugin.json +1 -1
  2. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
  3. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
  4. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
  5. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
  6. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
  7. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
  8. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
  9. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
  10. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
  11. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
  12. package/bundles/antigravity-plugin/scripts/caddis_prod_check.py +59 -11
  13. package/bundles/antigravity-plugin/scripts/caddis_roadmap.py +112 -194
  14. package/bundles/antigravity-plugin/scripts/caddis_roadmap_run.py +5 -25
  15. package/bundles/antigravity-plugin/skills/catchup/SKILL.md +2 -4
  16. package/bundles/antigravity-plugin/skills/handoff/SKILL.md +0 -6
  17. package/bundles/antigravity-plugin/skills/pr-merge/SKILL.md +2 -3
  18. package/bundles/antigravity-plugin/skills/roadmap/SKILL.md +0 -1
  19. package/bundles/codex/.codex/skills/workflow/roadmap/SKILL.md +0 -1
  20. package/bundles/manifest.json +2 -2
  21. package/dist/cli.js +7 -1
  22. package/package.json +1 -1
  23. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap_page.cpython-311.pyc +0 -0
  24. package/bundles/antigravity-plugin/scripts/caddis_roadmap_page.py +0 -1441
  25. package/bundles/antigravity-plugin/scripts/roadmap_assets/fonts.css +0 -5
  26. package/bundles/antigravity-plugin/scripts/roadmap_assets/icons.svg +0 -2
  27. package/dist/ui/fonts/LICENSE-Lucide.txt +0 -43
  28. package/dist/ui/fonts/OFL-Atkinson.txt +0 -93
  29. package/dist/ui/fonts/OFL-MapleMono.txt +0 -93
  30. /package/{bundles/antigravity-plugin/scripts/roadmap_assets → dist/export/licenses}/LICENSE-Lucide.txt +0 -0
  31. /package/{bundles/antigravity-plugin/scripts/roadmap_assets → dist/export/licenses}/OFL-Atkinson.txt +0 -0
  32. /package/{bundles/antigravity-plugin/scripts/roadmap_assets → dist/export/licenses}/OFL-MapleMono.txt +0 -0
  33. /package/dist/{export/fonts → ui/licenses}/LICENSE-Lucide.txt +0 -0
  34. /package/dist/{export/fonts → ui/licenses}/OFL-Atkinson.txt +0 -0
  35. /package/dist/{export/fonts → ui/licenses}/OFL-MapleMono.txt +0 -0
@@ -1,1441 +0,0 @@
1
- """A local, read-only roadmap page: one static HTML file built from the files that are already the truth.
2
-
3
- `caddis_roadmap.py render --roadmap <slug> [--out <file>]` writes it (default `~/.caddis/roadmap-pages/<repo>/<slug>.html`,
4
- outside every checkout). Plan: `.caddis/plans/roadmap-page.md` (owner decisions, 17 Oct).
5
-
6
- The hub: each default render writes `<slug>.body.html` (the page body) and `<slug>.json` (one summary row), and
7
- rebuilds `~/.caddis/roadmap-pages/index.html` from every summary on this machine. `index.html` is the whole app: the
8
- inbox, the gates, sessions and runners views, and one view per roadmap (its body). CSS shows one view at a time from
9
- the URL's `#view`, so there is one nav and it is never stale. `<slug>.html` is a one-line redirect to its view. It
10
- works as a local file and behind a static web server.
11
-
12
- Sections, in order: Waiting for you (sessions that wait for input, and open owner-gate blockers), Plan on a page (a
13
- swimlane: plans as lanes, milestones as columns, one tile per phase; open by default), then collapsed sections:
14
- summary, now / next / later, gates and blockers, every milestone with its phase rows, and the runner.
15
-
16
- The data is `status()` (roadmap.md and each plan's Tracker on origin), the plan headers (`### Phase <n> - <name>`,
17
- `**Model:**`, `**Lane:**`, `**Risk:**`), the runner's local lock and last stop, and the local session-state folder
18
- (`<sid>.waiting` markers from the Notification hook). No network, and one script only (id theme-toggle: the light/dark
19
- toggle, the hub's inbox reload, the phone menu, `aria-current`, the app bar crumbs and the search box): collapsing uses
20
- `<details>`. Icons are Lucide line icons from one inline sprite (`roadmap_assets/icons.svg`). Every text
21
- from the files is escaped: a plan, a relay or a hook message can hold any text.
22
- """
23
- from __future__ import annotations
24
-
25
- import datetime
26
- import functools
27
- import hashlib
28
- import html
29
- import json
30
- import os
31
- import re
32
- import shutil
33
- import stat
34
- import subprocess
35
- import sys
36
- import time
37
- from pathlib import Path
38
-
39
- PHASE_HEADER = re.compile(r"^###\s+Phase\s+(\d+)[a-z]?\s*[-–—:]\s*(.+?)\s*(?:[✅⏳\U0001F532].*)?$",
40
- re.MULTILINE)
41
- _FACT = re.compile(r"\*\*(Model|Lane|Risk):\*\*\s*([^\n]+?)\s*(?=\*\*(?:Model|Lane|Risk):\*\*|$)",
42
- re.MULTILINE)
43
- WAITING_MAX_AGE_H = 24 # a marker older than this, with no session end recorded, is shown as "stale?"
44
-
45
-
46
- # ---- reading ---------------------------------------------------------------------------------------------------
47
-
48
- def _read_json(path: Path | None):
49
- """(data, error): data is a dict or None; error names a file that exists but cannot be read."""
50
- if path is None:
51
- return None, ""
52
- try:
53
- raw = Path(path).read_text(encoding="utf-8")
54
- except FileNotFoundError:
55
- return None, ""
56
- except (OSError, UnicodeDecodeError) as exc:
57
- return None, f"{Path(path).name}: {getattr(exc, 'strerror', None) or exc}"
58
- try:
59
- data = json.loads(raw)
60
- except ValueError:
61
- return None, f"{Path(path).name}: not JSON"
62
- return (data, "") if isinstance(data, dict) else (None, f"{Path(path).name}: not a JSON object")
63
-
64
-
65
- def phase_facts(plan_text: str | None) -> dict[int, dict]:
66
- """Phase number -> {name, model, lane, risk} from the plan's `### Phase <n> - <name>` sections."""
67
- if not plan_text:
68
- return {}
69
- heads = list(PHASE_HEADER.finditer(plan_text))
70
- out: dict[int, dict] = {}
71
- for i, m in enumerate(heads):
72
- body = plan_text[m.end():heads[i + 1].start() if i + 1 < len(heads) else len(plan_text)]
73
- body = body.split("\n## ", 1)[0] # stop at the next level-2 section (Tracker, Risks, ...)
74
- facts = {k.lower(): v.strip() for k, v in _FACT.findall(body)}
75
- out.setdefault(int(m.group(1)), {"name": m.group(2).strip(), "model": facts.get("model", ""),
76
- "lane": facts.get("lane", ""), "risk": facts.get("risk", "")})
77
- return out
78
-
79
-
80
- def phase_names(plan_text: str | None) -> dict[int, str]:
81
- return {n: f["name"] for n, f in phase_facts(plan_text).items()}
82
-
83
-
84
- def tile_state(tracker_cell: str, state: str) -> str:
85
- """todo | in-progress | done | moved | blocked, from the Tracker cell (origin), falling back to status()."""
86
- cell = (tracker_cell or "").strip().lstrip("*").strip().lower()
87
- if cell.startswith("moved") or "moved" in cell.split(" - ", 1)[0]:
88
- return "moved"
89
- if cell.startswith(("done", "✅", "merged")):
90
- return "done"
91
- if cell.startswith(("blocked", "halt", "waiting")):
92
- return "blocked"
93
- if cell.startswith(("in progress", "in-progress", "active", "building", "built", "⏳")):
94
- return "in-progress"
95
- return "done" if state == "done" else "todo"
96
-
97
-
98
- def _short_model(model: str) -> str:
99
- m = model.lower()
100
- for key, label in (("opus", "Opus"), ("sonnet", "Sonnet"), ("haiku", "Haiku"), ("argon", "agy Argon"),
101
- ("agy", "agy"), ("gemini", "agy")):
102
- if key in m:
103
- return label
104
- return model.split(" - ", 1)[0].split("(", 1)[0].strip()[:24]
105
-
106
-
107
- def waiting_sessions(state_dir: Path, now: datetime.datetime) -> list[dict]:
108
- """Sessions whose Notification hook wrote `<sid>.waiting` and that have not ended (`<sid>.ended`)."""
109
- out = []
110
- if not state_dir.is_dir():
111
- return out
112
- for marker in sorted(state_dir.glob("*.waiting")):
113
- sid = marker.stem
114
- ended = state_dir / f"{sid}.ended"
115
- try: # an end mark counts only when it is newer than the waiting mark (a resumed session can ask again)
116
- if ended.exists() and ended.stat().st_mtime >= marker.stat().st_mtime:
117
- continue
118
- except OSError:
119
- continue
120
- data, err = _read_json(marker)
121
- data = data or {}
122
- name = ""
123
- try:
124
- name = (state_dir / f"{sid}.name").read_text(encoding="utf-8").split("\n", 1)[0].split("\t")[0].strip()
125
- except (OSError, UnicodeDecodeError):
126
- pass
127
- since = str(data.get("utc") or "")
128
- stale = False
129
- try:
130
- when = datetime.datetime.fromisoformat(since.replace("Z", "+00:00"))
131
- if when.tzinfo is None:
132
- when = when.replace(tzinfo=datetime.timezone.utc)
133
- stale = (now - when).total_seconds() > WAITING_MAX_AGE_H * 3600
134
- except (ValueError, TypeError):
135
- pass
136
- out.append({"session": name or sid[:8], "id": sid, "message": data.get("message") or err or "waiting",
137
- "since": since, "cwd": data.get("cwd") or "", "kind": data.get("kind") or "", "stale": stale})
138
- return out
139
-
140
-
141
- def main_checkout(root: Path) -> Path:
142
- """The main checkout of `root` (a linked worktree maps to it), so every worktree shares one page and one
143
- session-state folder; the waiting hook writes its marks there too."""
144
- try:
145
- out = subprocess.run(["git", "-C", str(root), "rev-parse", "--path-format=absolute", "--git-common-dir"],
146
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30,
147
- creationflags=0x08000000 if os.name == "nt" else 0)
148
- common = Path(out.stdout.strip()) if out.returncode == 0 and out.stdout.strip() else None
149
- except (OSError, subprocess.SubprocessError):
150
- common = None
151
- if common is not None and common.name == ".git":
152
- return common.parent.resolve()
153
- return Path(root).resolve()
154
-
155
-
156
- def _artifact_dir(root: Path) -> Path:
157
- try:
158
- import claudster_config
159
- return Path(claudster_config.artifact_root(root))
160
- except Exception: # the page must render without the harness on the path
161
- return Path(root) / ".caddis"
162
-
163
-
164
- # ---- the model -------------------------------------------------------------------------------------------------
165
-
166
- def build(root: Path, slug: str, roadmap_mod, now: datetime.datetime | None = None, sessions: bool = True) -> dict:
167
- """status() plus per-phase Tracker cell, name, model, lane, risk and tile state; waiting sessions; the runner.
168
- The hub passes `sessions=False`: it has live sessions of its own, so the marker folder is not read."""
169
- root = Path(root)
170
- now = now or datetime.datetime.now(datetime.timezone.utc)
171
- model = roadmap_mod.status(root, slug)
172
- plans: dict[str, tuple[dict[int, str], dict[int, dict]]] = {}
173
- lanes: list[str] = []
174
- for ms in model["milestones"]:
175
- for ph in ms["phases"]:
176
- m = roadmap_mod.REF_RE.match(ph["ref"])
177
- ph.update(plan="", num=0, tracker="", name="", model="", lane="", risk="")
178
- if not m:
179
- ph["tile"] = "todo"
180
- continue
181
- plan, num = m.group(1), int(m.group(2))
182
- if plan not in plans:
183
- text = roadmap_mod.show(root, model["branch"], f".caddis/plans/{plan}.md")
184
- if text is None:
185
- text = roadmap_mod.show(root, model["branch"], f".caddis/plans/done/{plan}.md")
186
- plans[plan] = (roadmap_mod.parse_tracker(text) if text else {}, phase_facts(text))
187
- lanes.append(plan)
188
- rows, facts = plans[plan]
189
- ph.update(plan=plan, num=num, tracker=rows.get(num, ""), **{k: v for k, v in facts.get(num, {}).items()})
190
- ph["tile"] = tile_state(ph["tracker"], ph["state"])
191
- model["lanes"] = lanes
192
- model["waiting"] = [{"milestone": ms["id"], "reason": b["reason"], "check": b["check"]}
193
- for ms in model["milestones"] for b in ms["blockers"]
194
- if b["type"] == "owner-gate" and ms["status"] not in roadmap_mod.FINISHED]
195
- model["sessions"] = (waiting_sessions(_artifact_dir(main_checkout(root)) / "session-state", now) if sessions else [])
196
-
197
- lock_path = roadmap_mod.runner_lock_path(root, "roadmap", slug)
198
- lock, lock_err = _read_json(lock_path)
199
- if lock is not None and not all(lock.get(k) not in (None, "") for k in ("batch", "pid", "started_utc")):
200
- lock_err = lock_err or f"{Path(lock_path).name}: missing batch, pid or started_utc"
201
- lock = None
202
- live = False
203
- if lock is not None and lock_path is not None:
204
- try:
205
- live = roadmap_mod.runner_lock_stale(lock_path) is False
206
- except Exception: # a judgement that cannot be made is not "running"
207
- live = False
208
- stop, stop_err = _read_json(roadmap_mod.last_stop_path(root, "roadmap", slug))
209
- model["runner"] = {"lock": lock if live else None, "stale_lock": lock if (lock and not live) else None,
210
- "last_stop": stop, "errors": [e for e in (lock_err, stop_err) if e]}
211
- model["generated"] = now.strftime("%Y-%m-%d %H:%M UTC")
212
- try:
213
- model["origin_commit"] = roadmap_mod._git(root, "rev-parse", "--short", f"origin/{model['branch']}",
214
- check=False).stdout.strip()
215
- except Exception:
216
- model["origin_commit"] = ""
217
- return model
218
-
219
-
220
- # ---- rendering -------------------------------------------------------------------------------------------------
221
-
222
- # One colour set for every page: light = slate + blue, dark = Dracula (owner, 17 Oct): https://draculatheme.com/contribute
223
- # Dark uses the full official palette for text, borders, links, focus and status (owner, 21 Oct). Two tones are not
224
- # Dracula's own: --muted (#a4acd4, a lighter comment: #6272a4 is only ~3:1 on the background) and the tinted chip
225
- # backgrounds. A test checks every text/background pair the CSS uses against WCAG AA (CONTRAST_PAIRS).
226
- # Dark applies when the OS asks for it, unless the reader picked light; the toggle sets data-theme on <html>.
227
- _PALETTE_LIGHT = '--bg:#f4f6f9;--panel:#fff;--panel2:#f8fafc;--fg:#0f172a;--muted:#475569;--line:#e2e8f0;--line2:#cbd5e1;--accent:#2563eb;--todo-bg:#f1f5f9;--todo-fg:#334155;--prog:#2563eb;--prog-bg:#dbeafe;--prog-fg:#1d4ed8;--done:#16a34a;--done-bg:#dcfce7;--done-fg:#15803d;--block:#d97706;--block-bg:#fef3c7;--block-fg:#92400e;--high:#dc2626;--wait-bg:#fee2e2;--wait-fg:#b91c1c;--wait-h:#b91c1c;--nav:#f8fafc;--nav-fg:#0f172a;--on-accent:#ffffff;--focus:#2563eb;--field:#64748b;--shadow:0 1px 3px rgba(15,23,42,.06);--elev:0 8px 20px rgba(15,23,42,.10);--ico-sun:none;--ico-moon:inline-block;--title:var(--fg);--summary:var(--fg);--code:var(--fg);--c0:#2563eb;--c1:#7c3aed;--c2:#0d9488;--c3:#ea580c;--c4:#db2777;--c5:#475569;--sans:"Atkinson Hyperlegible Next","Segoe UI Variable","Segoe UI",system-ui,sans-serif;--mono:"Maple Mono","Cascadia Mono",Consolas,ui-monospace,monospace;--head:"Maple Mono","Cascadia Mono",Consolas,ui-monospace,monospace;color-scheme:light;'
228
- _PALETTE_DARK = '--bg:#282a36;--panel:#21222c;--panel2:#343746;--fg:#f8f8f2;--muted:#a4acd4;--line:#44475a;--line2:#6272a4;--accent:#8be9fd;--todo-bg:#44475a;--todo-fg:#f8f8f2;--prog:#bd93f9;--prog-bg:#3c3352;--prog-fg:#bd93f9;--done:#50fa7b;--done-bg:#2b4a36;--done-fg:#50fa7b;--block:#ffb86c;--block-bg:#4a3a2b;--block-fg:#ffb86c;--high:#ff5555;--wait-bg:#3a2028;--wait-fg:#ff5555;--wait-h:#ff5555;--nav:#21222c;--nav-fg:#f8f8f2;--on-accent:#282a36;--focus:#ff79c6;--field:#6272a4;--shadow:none;--elev:0 8px 22px rgba(0,0,0,.45);--ico-sun:inline-block;--ico-moon:none;--title:#bd93f9;--summary:#ff79c6;--code:#f1fa8c;--c0:#8be9fd;--c1:#bd93f9;--c2:#50fa7b;--c3:#ffb86c;--c4:#ff79c6;--c5:#6272a4;color-scheme:dark;'
229
- _THEME_CSS = (":root{" + _PALETTE_LIGHT + "}" + '@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){'
230
- + _PALETTE_DARK + "}}" + ':root[data-theme="dark"]{' + _PALETTE_DARK + "}")
231
-
232
- _BASE_CSS = """
233
- *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);
234
- font:14px/1.5 var(--sans)}code{font:12px var(--mono);color:var(--code)}
235
- main{max-width:1360px;margin:0 auto;padding:20px 16px 48px;display:grid;gap:16px}main>*{min-width:0}
236
- h1,h2,h3,details.card>summary,.kpi b{font-family:var(--head)}h1{font-size:24px;margin:0;color:var(--title)}h2{font-size:16px;margin:0}.sub{color:var(--muted);margin:4px 0 0}
237
- .card{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:14px 16px}
238
- details.card>summary{cursor:pointer;font-weight:700;font-size:16px;list-style:none;color:var(--summary)}
239
- details.card>summary::-webkit-details-marker{display:none}details.card>summary::before{content:"\\25B8 ";color:var(--muted)}
240
- details.card[open]>summary::before{content:"\\25BE "}details.card+details.card{margin-top:8px}
241
- .wait{border-color:var(--high)}.wait h2{color:var(--wait-h)}.empty{color:var(--muted)}
242
- table{border-collapse:collapse;width:100%}th,td{text-align:left;padding:7px 9px;border-top:1px solid var(--line);
243
- vertical-align:top}th{font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:var(--muted);border-top:0}
244
- .scroll{overflow-x:auto}.pill{display:inline-block;font-size:11px;font-weight:700;text-transform:uppercase;
245
- padding:1px 8px;border-radius:999px;white-space:nowrap}
246
- .s-todo{background:var(--todo-bg);color:var(--todo-fg)}.s-in-progress{background:var(--prog-bg);color:var(--prog-fg)}
247
- .s-done,.s-moved,.s-not-needed{background:var(--done-bg);color:var(--done-fg)}.s-blocked{background:var(--block-bg);color:var(--block-fg)}
248
- .s-code-done\\/data-pending{background:var(--block-bg);color:var(--block-fg)}
249
- .lanes{display:grid}.lanes>div{border-top:1px solid var(--line);border-left:1px dashed var(--line);
250
- padding:6px}.lanes .hd{background:var(--panel2);border-top:0;font-weight:700}.lanes .ln{position:sticky;left:0;z-index:1;
251
- background:var(--panel);border-left:4px solid var(--lc,var(--line2));border-right:1px solid var(--line2);font-weight:600;overflow-wrap:anywhere}
252
- .tile{display:flex;gap:5px;align-items:center;font-size:12px;padding:3px 5px;position:relative;margin:0 0 4px;border-radius:5px;
253
- border:1px solid var(--line2);background:var(--panel);max-width:100%}.tile b{font:600 11px var(--mono)}
254
- .tile span{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;white-space:normal;overflow-wrap:anywhere}.tile.in-progress{background:var(--prog-bg);
255
- border-color:var(--prog);color:var(--prog-fg)}.tile.done{background:var(--done-bg);border-color:var(--done);
256
- color:var(--done-fg)}.tile.moved{background:repeating-linear-gradient(135deg,var(--done-bg) 0 5px,var(--panel) 5px 10px);
257
- border-color:var(--done)}.tile.blocked{background:var(--block-bg);border-color:var(--block);color:var(--block-fg)}
258
- .tile.hi::after{position:absolute;top:3px;right:3px;margin:0}
259
- .ltile{display:flex;gap:8px;align-items:baseline;font-size:13px;padding:5px 8px;margin:0 0 4px;border-radius:6px;border:1px solid var(--line2);background:var(--panel)}.ltile b{font:600 11px var(--mono);white-space:nowrap}
260
- .ltile.in-progress{background:var(--prog-bg);border-color:var(--prog);color:var(--prog-fg)}.ltile.done{background:var(--done-bg);border-color:var(--done);color:var(--done-fg)}
261
- .ltile.moved{background:repeating-linear-gradient(135deg,var(--done-bg) 0 5px,var(--panel) 5px 10px);border-color:var(--done)}.ltile.blocked{background:var(--block-bg);border-color:var(--block);color:var(--block-fg)}
262
- .bcount{display:inline-block;font-size:11px;font-weight:700;color:var(--block-fg);background:var(--block-bg);border:1px dashed var(--block);border-radius:6px;padding:0 6px;margin-top:3px}
263
- .lane-list{display:none}.lane-list h3{margin:10px 0 6px}@media (max-width:900px){.timeline .scroll{display:none}.lane-list{display:block}}
264
- .hi::after{content:"";width:7px;height:7px;border-radius:50%;background:var(--high);flex:none;margin-left:auto}
265
- .gate{font-size:11px;color:var(--block-fg);background:var(--block-bg);border:1px dashed var(--block);border-radius:6px;
266
- padding:3px 6px;margin:2px 0;white-space:normal;overflow-wrap:anywhere}.legend{display:flex;flex-wrap:wrap;gap:12px;font-size:12px;color:var(--muted);margin-top:8px}
267
- .cols{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}@media (max-width:820px){.cols{grid-template-columns:1fr}}
268
- .kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:10px}.kpi b{font-size:22px;display:block}
269
- .bar{height:8px;border-radius:99px;background:var(--todo-bg);overflow:hidden;min-width:120px;margin:4px 0}
270
- .bar i{display:block;height:100%;background:var(--done)}a{color:var(--accent)}td.num{white-space:nowrap}
271
- .theme-btn{display:inline-grid;place-items:center;flex:none;width:36px;height:36px;padding:0;border-radius:10px;border:1px solid var(--line);background:var(--panel2);color:var(--fg);cursor:pointer}
272
- .theme-btn:hover{border-color:var(--accent);color:var(--accent)}.theme-btn .ic{width:18px;height:18px;vertical-align:0}.theme-btn .t-sun{display:var(--ico-sun)}.theme-btn .t-moon{display:var(--ico-moon)}
273
- .hdr{display:flex;justify-content:space-between;align-items:flex-start;gap:12px}
274
- .chips{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}.chip{border:1px solid var(--line);border-left:4px solid var(--lc);border-radius:8px;padding:5px 10px;background:var(--panel2);font-size:12.5px}.chip span{color:var(--muted);font-family:var(--mono)}
275
- .flow{display:flex;gap:6px;align-items:stretch;min-width:max-content}.fnode{display:grid;gap:3px;padding:8px 10px;border:1px solid var(--line);border-radius:9px;background:var(--panel2);text-decoration:none;color:inherit;min-width:120px}.fnode span{font:11px var(--mono);color:var(--muted)}.fnode span.pill{font:700 11px var(--sans);justify-self:start}.arrow{align-self:center;color:var(--muted)}
276
- .kind{font-size:10.5px;font-weight:700;text-transform:uppercase;padding:2px 8px;border-radius:6px;background:var(--block-bg);color:var(--block-fg)}.k-owner-gate{background:var(--wait-bg);color:var(--wait-fg)}
277
- .note{color:var(--muted);font-weight:400;font-size:13px}.sec-h{display:flex;flex-wrap:wrap;gap:4px 10px;align-items:baseline;margin-bottom:8px}h3{font-size:14px;margin:0 0 8px}
278
- .cols .rcard{margin-bottom:8px}.cols .rcard .bar{margin:0}
279
- """
280
-
281
- _CSS = _THEME_CSS + _BASE_CSS
282
-
283
- # The one script on a page: the reader's theme choice; on the hub only, a reload every 60 s while the inbox shows
284
- # (an open roadmap view is never reset); the phone menu closes when the view changes; and the nav item of the
285
- # shown view gets aria-current. No network.
286
- _THEME_SCRIPT = ('<script id="theme-toggle">(function(){var k="caddis-roadmap-theme",d=document.documentElement;d.classList.add("js");try{var t=localStorage.getItem(k);if(t==="light"||t==="dark")d.dataset.theme=t}catch(e){}window.caddisTheme=function(){var c=d.dataset.theme||(matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),n=c==="dark"?"light":"dark";d.dataset.theme=n;try{localStorage.setItem(k,n)}catch(e){}};function shown(){var h=location.hash.slice(1),e=h&&document.getElementById(h),v=e&&e.closest(".view");return v?v.id:"inbox"}function cur(){var a=document.querySelectorAll(".nav a.nav-i");for(var i=0;i<a.length;i++){if(a[i].getAttribute("href")==="#"+shown())a[i].setAttribute("aria-current","page");else a[i].removeAttribute("aria-current")}}'
287
- # The app bar crumbs follow the shown view (a roadmap view brings its own, its .view-crumbs).
288
- 'function bar(){var c=document.getElementById("ab-crumbs");if(!c||!document.getElementById("inbox"))return;var id=shown(),v=document.getElementById(id),p=v&&v.querySelector(".view-crumbs"),a=document.querySelector(\'.nav a.nav-i[href="#\'+id+\'"]\');if(p){c.innerHTML=p.innerHTML}else{c.innerHTML=\'<a href="#inbox">Roadmaps</a> \u203a <strong></strong>\';c.lastChild.textContent=a?a.getAttribute("data-label"):"Inbox"}}'
289
- # Search: hide every [data-q] element that does not hold the text; open a matching milestone; count
290
- # the [data-qn] hits of the shown view.
291
- 'function find(){var s=document.getElementById("q");if(!s)return;var v=s.value.trim().toLowerCase(),n=0,id=shown(),e=document.querySelectorAll("[data-q]");for(var i=0;i<e.length;i++){var x=e[i],hit=!v||(x.getAttribute("data-q")+" "+x.textContent).toLowerCase().indexOf(v)>=0;x.classList.toggle("q-miss",!hit);if(x.tagName==="DETAILS"){if(v&&hit){if(!x.hasAttribute("data-o"))x.setAttribute("data-o",x.open?"1":"0");x.open=true}else if(x.hasAttribute("data-o")){x.open=x.getAttribute("data-o")==="1";x.removeAttribute("data-o")}}var w=x.closest(".view");if(v&&hit&&x.hasAttribute("data-qn")&&(!w||w.id===id))n++}var o=document.getElementById("q-n");if(o)o.textContent=v?n+(n===1?" match":" matches"):""}'
292
- 'addEventListener("DOMContentLoaded",cur);addEventListener("DOMContentLoaded",function(){bar();var s=document.getElementById("q");if(s){s.addEventListener("input",find);s.addEventListener("keydown",function(ev){if(ev.key==="Escape"){s.value="";find()}})}});'
293
- 'addEventListener("keydown",function(ev){var s=document.getElementById("q"),f=document.activeElement;if(ev.key==="/"&&s&&f!==s&&!(f&&/^(INPUT|TEXTAREA|SELECT)$/.test(f.tagName))){ev.preventDefault();s.focus()}});'
294
- 'setInterval(function(){var s=document.getElementById("q");if(document.getElementById("inbox")&&document.visibilityState==="visible"&&shown()==="inbox"&&!(s&&s.value))location.reload()},60000);addEventListener("hashchange",function(){var b=document.getElementById("nav-cb");if(b)b.checked=false;cur();bar();find()})})();</script>')
295
- # The shared copy is a static page: the inbox reload would only re-request it every minute, so it has no timer.
296
- _SITE_THEME_SCRIPT = re.sub(r"setInterval\(function\(\)\{.*?\},60000\);", "", _THEME_SCRIPT)
297
-
298
-
299
- def _fonts_link(base: str) -> str:
300
- """The one allowed <link>: bundled fonts. If it does not load, the font stacks fall back to system fonts."""
301
- return f'<link rel="stylesheet" href="{_e(base)}_assets/fonts.css">'
302
-
303
- _SHELL_CSS = """
304
- .app{display:grid;grid-template-columns:240px minmax(0,1fr);grid-template-rows:auto 1fr;min-height:100vh}
305
- .nav{background:var(--nav);color:var(--nav-fg);border-right:1px solid var(--line);padding:6px 10px 14px;position:sticky;top:56px;height:calc(100vh - 56px);overflow-y:auto}
306
- .nav-h{font-size:11px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);margin:14px 8px 4px}
307
- .nav-repo{display:flex;align-items:center;gap:6px;font-size:12px;font-weight:600;color:var(--muted);margin:10px 8px 2px}.nav-repo .ic{width:14px;height:14px}
308
- .nav-i{display:flex;align-items:center;gap:8px;padding:6px 8px;border-radius:7px;color:inherit;text-decoration:none;font-size:13px;transition:background .15s}
309
- .nav-i:hover,.nav-i:focus-visible{background:var(--panel2)}.nav-i .ic{color:var(--muted)}.nav-i[aria-current] .ic{color:var(--prog-fg)}
310
- .nav-i .n{margin-left:auto;font-family:var(--mono);font-size:11px;color:var(--muted)}.nav-rm{padding-left:16px}.nav-rm .ic{width:14px;height:14px}
311
- .nav-sub{display:grid;padding:2px 0 6px 28px}.nav-sub a{font-size:12px;color:var(--muted);text-decoration:none;padding:3px 0}
312
- .main{min-width:0}.top{grid-column:1/-1;display:flex;align-items:center;gap:14px;height:56px;padding:0 16px;border-bottom:1px solid var(--line);background:var(--panel);position:sticky;top:0;z-index:10;box-shadow:var(--shadow)}
313
- .ab-brand{display:flex;align-items:center;gap:9px;flex:none;width:208px;font:700 15px var(--head);color:var(--title);text-decoration:none;white-space:nowrap}
314
- .logo{display:inline-grid;place-items:center;flex:none;width:30px;height:30px;border-radius:9px;background:var(--accent);color:var(--on-accent)}.logo .ic{width:18px;height:18px;vertical-align:0}
315
- .crumbs{flex:1;min-width:0;font-size:13px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.crumbs a{color:var(--accent);text-decoration:none}.crumbs strong{color:var(--fg)}
316
- .search{position:relative;flex:0 1 300px;min-width:0}.search .ic{position:absolute;left:10px;top:50%;margin-top:-8px;color:var(--muted);pointer-events:none}
317
- .search input{width:100%;height:36px;padding:0 10px 0 34px;border-radius:10px;border:1px solid var(--field);background:var(--panel2);color:var(--fg);font:13px var(--sans)}
318
- .search input::placeholder{color:var(--muted);opacity:1}.q-n{font:11px var(--mono);color:var(--muted);white-space:nowrap}.q-n:empty{display:none}
319
- .gen{display:flex;align-items:center;gap:5px;font:11px var(--mono);color:var(--muted);white-space:nowrap}.gen .ic{width:13px;height:13px}
320
- .js .view-crumbs{display:none}
321
- main [id]{scroll-margin-top:60px}main>.view{scroll-margin-top:200px}
322
- .view>*+*{margin-top:16px}.view{display:none}.view:target,.view:has(:target){display:block}main:not(:has(.view:target,.view :target))>#inbox{display:block}
323
- .nav-sub{display:none}.view-crumbs{font-size:13px;color:var(--muted);margin:0 0 8px}
324
- .nav-cb{display:none}.nav-btn,.nav-close,.nav-scrim{display:none}
325
- .nav-cb:focus-visible~.app .nav-btn{outline:2px solid var(--accent);outline-offset:2px}
326
- @media (max-width:900px){.app{grid-template-columns:1fr}.nav-cb{display:block;position:absolute;opacity:0;width:1px;height:1px;pointer-events:none}.nav{position:fixed;left:0;top:0;z-index:20;width:260px;height:100vh;transform:translateX(-100%);transition:transform .2s}.nav-cb:checked~.app .nav{transform:none}.nav-btn{display:inline-grid;place-items:center;cursor:pointer;width:32px;height:32px;color:var(--fg)}.nav-btn .ic,.nav-close .ic{width:20px;height:20px;vertical-align:0}.nav-close{display:block;text-align:right;cursor:pointer;padding:6px 8px;color:var(--fg)}.nav-cb:checked~.app .nav-scrim{display:block;position:fixed;inset:0;z-index:15;background:rgba(0,0,0,.4)}
327
- .top{flex-wrap:wrap;height:auto;gap:6px 8px;padding:8px 10px}.ab-brand{width:auto}.ab-name,.gen{display:none}.search{flex:1 1 120px}.crumbs{order:5;flex-basis:100%}main [id]{scroll-margin-top:100px}}
328
- .cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:12px}
329
- .rcard{display:grid;gap:8px;background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:14px 16px;color:inherit;text-decoration:none;box-shadow:var(--shadow)}
330
- .dots{display:flex;flex-wrap:wrap;gap:4px}.dot{font:600 10.5px var(--mono);padding:1px 6px;border-radius:5px}
331
- .kpi{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:12px 14px;box-shadow:var(--shadow)}
332
- .ic{width:16px;height:16px;flex:none;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;vertical-align:-3px}
333
- .sprite{position:absolute;width:0;height:0;overflow:hidden}
334
- h2 .ic,h3 .ic{color:var(--accent);margin-right:7px}.wait h2 .ic{color:var(--wait-h)}
335
- .pill .ic,.kind .ic{width:12px;height:12px;margin-right:4px;vertical-align:-2px}.rcard .ic{margin-right:4px}.rcard strong .ic{color:var(--accent)}.tile .ic,.ltile .ic{width:13px;height:13px;align-self:center}
336
- :focus-visible{outline:2px solid var(--focus);outline-offset:2px}
337
- .rcard,.kpi,.fnode{transition:transform .15s ease,box-shadow .15s ease,border-color .15s ease}
338
- .rcard:hover,.rcard:focus-visible,.fnode:hover,.fnode:focus-visible{transform:translateY(-2px);box-shadow:var(--elev);border-color:var(--accent)}
339
- .rcard[data-st]{border-left:4px solid var(--line2)}.rcard[data-st=done]{border-left-color:var(--done)}.rcard[data-st=prog]{border-left-color:var(--prog)}.rcard[data-st=block]{border-left-color:var(--block)}.rcard[data-st=wait]{border-left-color:var(--high)}
340
- .kpi{position:relative;padding-right:56px}.kpi-ic{position:absolute;top:12px;right:12px;width:32px;height:32px;border-radius:9px;display:grid;place-items:center;background:var(--prog-bg);color:var(--prog-fg)}.kpi-ic .ic{width:18px;height:18px;vertical-align:0}
341
- .kpi-ic.k-done{background:var(--done-bg);color:var(--done-fg)}.kpi-ic.k-block{background:var(--block-bg);color:var(--block-fg)}.kpi-ic.k-wait{background:var(--wait-bg);color:var(--wait-fg)}
342
- .bar i{transform-origin:left;animation:fill .9s cubic-bezier(.2,.7,.2,1) both}@keyframes fill{from{transform:scaleX(0)}}
343
- .q-miss,.nav-rm.q-miss+.nav-sub{display:none!important}
344
- @media (prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}.rcard:hover,.rcard:focus-visible,.fnode:hover,.fnode:focus-visible{transform:none}}
345
- """
346
-
347
- _LABEL = {"todo": "to do", "in-progress": "in progress", "done": "done", "moved": "moved", "blocked": "blocked"}
348
-
349
-
350
- def _e(value) -> str:
351
- return html.escape("" if value is None else str(value), quote=True)
352
-
353
-
354
- @functools.lru_cache(maxsize=1)
355
- def _sprite() -> str:
356
- """The Lucide sprite (`roadmap_assets/icons.svg`, made by build_roadmap_icons.py, with its licence comment), put
357
- inline once per page: Chrome and Edge do not let a `file://` page `<use>` a symbol from another file. Empty when
358
- the file is not shipped: the page then shows no icons, and nothing else changes."""
359
- try:
360
- return (ASSET_DIR / "icons.svg").read_text(encoding="utf-8").strip()
361
- except OSError:
362
- return ""
363
-
364
-
365
- def _icon(name: str, label: str | None = None, cls: str = "") -> str:
366
- """One Lucide icon from the inline sprite, tinted by `currentColor`. Decorative by default (hidden from screen
367
- readers); with `label` it is an image with that name, for an icon whose meaning no text beside it gives."""
368
- attrs = f'role="img" aria-label="{_e(label)}"' if label else 'aria-hidden="true" focusable="false"'
369
- return f'<svg class="ic{" " + cls if cls else ""}" {attrs}><use href="#ic-{name}"/></svg>'
370
-
371
-
372
- _STATUS_ICON = {"done": "circle-check", "todo": "circle", "in-progress": "circle-dot", "blocked": "octagon-alert",
373
- "moved": "arrow-right-left", "not-needed": "circle-minus", "code-done/data-pending": "hourglass",
374
- "running": "play", "owner-gate": "user-check"}
375
-
376
-
377
- def _pill(status: str) -> str:
378
- return (f'<span class="pill s-{_e(status)}">{_icon(_STATUS_ICON.get(status, "circle"))}'
379
- f'{_e(_LABEL.get(status, status))}</span>')
380
-
381
-
382
- def _kind(kind: str) -> str:
383
- """A blocker type chip: owner gates get their own colour and icon."""
384
- icon = "user-check" if kind == "owner-gate" else "shield-alert"
385
- return f'<span class="kind k-{_e(kind)}">{_icon(icon)}{_e(kind)}</span>'
386
-
387
-
388
- def _h2(icon: str, text: str) -> str:
389
- return f"<h2>{_icon(icon)}{_e(text)}</h2>"
390
-
391
-
392
- def _kpi(icon: str, tone: str, value: str, label: str) -> str:
393
- """A KPI tile: `value` and `label` are already safe text."""
394
- return f'<div class="kpi"><span class="{f"kpi-ic {tone}".strip()}">{_icon(icon)}</span><b>{value}</b>{label}</div>'
395
-
396
-
397
- def _theme_button() -> str:
398
- return ('<button type="button" class="theme-btn" onclick="caddisTheme()" aria-label="Switch between light and dark '
399
- 'theme" title="Switch between light and dark theme">' + _icon("moon", cls="t-moon") + _icon("sun", cls="t-sun")
400
- + "</button>")
401
-
402
-
403
- def _app_bar(base: str, crumbs: str, generated: str) -> str:
404
- """The top bar of every page: the phone menu button, the logo and name (a link to the inbox), the crumbs of the
405
- shown view (the script keeps them current on the hub), the search box, the generated time and the theme button."""
406
- home = f"{base}index.html#inbox" if base else "#inbox"
407
- gen = f'<span class="gen">{_icon("clock")}generated {_e(generated)}</span>' if generated else ""
408
- return ('<header class="top"><label for="nav-cb" class="nav-btn" aria-label="Open the menu">' + _icon("menu")
409
- + f'</label><a class="ab-brand" href="{_e(home)}"><span class="logo">{_icon("route")}</span>'
410
- '<span class="ab-name">caddis Roadmaps</span></a>'
411
- f'<div class="crumbs" id="ab-crumbs" role="navigation" aria-label="Breadcrumb">{crumbs}</div>'
412
- f'<div class="search" role="search">{_icon("search")}<input type="search" id="q" '
413
- 'placeholder="Search roadmaps, milestones, phases" title="Press / to search" '
414
- 'aria-label="Search roadmaps, milestones and phases" '
415
- 'autocomplete="off" spellcheck="false"></div><span class="q-n" id="q-n" role="status" aria-live="polite"></span>'
416
- f"{gen}{_theme_button()}</header>")
417
-
418
-
419
- def _shell(*, title: str, base: str, nav: str, crumbs: str, body: str, css: str = "",
420
- script: str | None = None, generated: str = "") -> str:
421
- """The app frame around every page: head, the icon sprite, the app bar, the left nav and the body.
422
- `nav`, `crumbs`, `body` and `css` are text the caller has already made safe; `title` and `generated` are plain
423
- text."""
424
- return "".join([
425
- '<!doctype html><html lang="en"><head><meta charset="utf-8">',
426
- '<meta name="viewport" content="width=device-width,initial-scale=1">',
427
- f"<title>{_e(title)}</title>{_fonts_link(base)}<style>{_CSS}{_SHELL_CSS}{css}</style>{script or _THEME_SCRIPT}</head>",
428
- f'<body>{_sprite()}<input type="checkbox" id="nav-cb" class="nav-cb" aria-label="Toggle the navigation menu"><div class="app">',
429
- _app_bar(base, crumbs, generated),
430
- f'{nav}<label for="nav-cb" class="nav-scrim" aria-hidden="true"></label><div class="main">',
431
- f"<main>{body}</main></div></div></body></html>\n"])
432
-
433
-
434
- def _crumbs(folder: str, slug: str) -> str:
435
- """`Roadmaps › <repo> › <slug>` for a roadmap page; the repo is the folder name without its `-<6hex>` tag."""
436
- repo = re.sub(r"-[0-9a-f]{6}$", "", folder or "")
437
- mid = f"{_e(repo)} › " if repo else ""
438
- return f'<a href="../index.html">Roadmaps</a> › {mid}<strong>{_e(slug)}</strong>'
439
-
440
-
441
- def _sessions_of(group: list[dict]) -> list[dict]:
442
- """The newest summary of a checkout has its newest session marks."""
443
- return max(group, key=lambda r: str(r.get("generated_utc", ""))).get("sessions") or []
444
-
445
-
446
- def _group_rows(rows: list[dict]) -> tuple[list[tuple[str, list[dict]]], list[tuple[str, list, list]], int]:
447
- """(order, need, count): the summaries per repo folder in repo-name order; per repo the asking sessions and the
448
- owner gates (repo, asking, gates), only for repos that have any; and how many items need the owner."""
449
- by_repo: dict[str, list[dict]] = {}
450
- for r in rows:
451
- by_repo.setdefault(r["folder"], []).append(r)
452
- order = sorted(by_repo.items(), key=lambda kv: (str(kv[1][0].get("repo", "")).lower(), kv[0]))
453
- need = []
454
- for _folder, group in order:
455
- asking = [s for s in _sessions_of(group) if s.get("asking")]
456
- gates = [(r, g) for r in group for g in r.get("owner_gates") or []]
457
- if asking or gates:
458
- need.append((group[0].get("repo"), asking, gates))
459
- count = sum(len(a) + len(g) for _, a, g in need)
460
- return order, need, count
461
-
462
-
463
- def _nav(rows: list[dict], base: str, site: bool = False) -> str:
464
- """The left nav: Needs you (inbox, gates, sessions, runners), then every repo with its roadmaps. Every link opens a
465
- view of `index.html` (`#inbox`, `#<rid>`, ...); on the hub itself (`base` "") the link is the bare `#view`. The
466
- active item and its sub-links are shown by `_view_css`, so the nav needs no per-page copy. A `site` (shared copy)
467
- nav has no Sessions or Runners item, no idle-session note and no Runner sub-link: those show only on the owner's
468
- machine."""
469
- order, _need, count = _group_rows(rows)
470
- counts = {"inbox": count, "gates": sum(len(r.get("blockers") or r.get("owner_gates") or []) for r in rows),
471
- "sessions": sum(len(_sessions_of(group)) for _f, group in order),
472
- "runners": sum(1 for r in rows if r.get("runner") == "running")}
473
- hub = f"{base}index.html" if base else ""
474
- out = ['<nav class="nav" aria-label="Roadmaps">'
475
- f'<label for="nav-cb" class="nav-close" aria-label="Close the menu">{_icon("x")}</label>',
476
- '<p class="nav-h">Needs you</p>']
477
- for key, label in _NAV_ITEMS:
478
- if site and key in _LOCAL_VIEWS:
479
- continue
480
- out.append(f'<a class="nav-i" href="{_e(hub)}#{key}" data-label="{_e(label)}">{_icon(_NAV_ICON[key])}{_e(label)}'
481
- f'<span class="n">{_e(counts[key])}</span></a>')
482
- out.append('<p class="nav-h">Repos</p>')
483
- for folder, group in order:
484
- idle = 0 if site else sum(1 for s in _sessions_of(group) if not s.get("asking"))
485
- idle_txt = f" · {idle} idle session(s)" if idle else ""
486
- out.append(f'<p class="nav-repo">{_icon("folder-git-2")}{_e(group[0].get("repo"))}{_e(idle_txt)}</p>')
487
- for r in sorted(group, key=lambda r: str(r["slug"])):
488
- rid = _rid(folder, r["slug"])
489
- if rid is None:
490
- continue
491
- total = _int(r.get("phases_total"))
492
- pct = int(round(100 * _int(r.get("phases_done")) / total)) if total else 0
493
- out.append(f'<a class="nav-i nav-rm" href="{_e(hub)}#{rid}" data-q="{_e(group[0].get("repo"))}" '
494
- f'data-label="{_e(r["slug"])}">{_icon("map")}{_e(r["slug"])}<span class="n">{pct}%</span></a>'
495
- f'<div class="nav-sub" data-rid="{rid}">'
496
- + "".join(f'<a href="{_e(hub)}#{rid}-{anchor}">{_e(label)}</a>' for anchor, label in _PAGE_ANCHORS
497
- if not (site and anchor in _LOCAL_ANCHORS))
498
- + "</div>")
499
- out.append("</nav>")
500
- return "".join(out)
501
-
502
-
503
- _NAV_ITEMS = (("inbox", "Inbox"), ("gates", "Gates"), ("sessions", "Sessions"), ("runners", "Runners"))
504
- _NAV_ICON = {"inbox": "inbox", "gates": "shield-alert", "sessions": "messages-square", "runners": "activity"}
505
- _LOCAL_VIEWS = ("sessions", "runners") # views of this machine's live state: a shared copy has neither
506
- _LOCAL_ANCHORS = ("runner",) # the section of a roadmap view that shows this machine's runner
507
-
508
- _ON = "{background:var(--prog-bg);color:var(--prog-fg);font-weight:600}"
509
-
510
-
511
- def _view_css(rids: list[str], site: bool = False) -> str:
512
- """Marks the nav item of the view that shows, and opens its sub-links. One rule per roadmap: CSS cannot take
513
- the target's id into a selector. Every rid comes from `_rid` (hex and slug characters only), so it is safe
514
- in a selector."""
515
- shown = ".view:target,.view :target"
516
- out = [f'body:not(:has({shown})) .nav a[href="#inbox"]{_ON}']
517
- for key, _label in _NAV_ITEMS:
518
- if site and key in _LOCAL_VIEWS:
519
- continue
520
- out.append(f'body:has(#{key}:target,#{key} :target) .nav a[href="#{key}"]{_ON}')
521
- for rid in rids:
522
- on = f"body:has(#{rid}:target,#{rid} :target)"
523
- out.append(f'{on} .nav a[href="#{rid}"]{_ON}{on} .nav-sub[data-rid="{rid}"]{{display:grid}}')
524
- return "".join(out)
525
-
526
-
527
- def _waiting_section(model: dict, site: bool = False) -> str:
528
- """Sessions that wait for input, then the open owner gates. A shared copy (`site`) has the owner gates only: its
529
- sessions are not on the reader's machine, so a table of them would be empty for a wrong reason."""
530
- out = [f'<section id="waiting" class="card wait">{_h2("bell-ring", "Waiting for you")}']
531
- sessions, gates = ([] if site else model["sessions"]), model["waiting"]
532
- if not sessions and not gates:
533
- out.append('<p class="empty">' + ("No owner gate is waiting." if site else "Nothing is waiting for you.")
534
- + "</p></section>")
535
- return "".join(out)
536
- # A question or a permission first; a session that only finished its turn and sits idle comes after it.
537
- asking = [s for s in sessions if not str(s.get("kind", "")).startswith("idle")]
538
- idle = [s for s in sessions if str(s.get("kind", "")).startswith("idle")]
539
- for title, group in (("Needs an answer", asking), ("Idle, waiting for your next message", idle)):
540
- if not group:
541
- continue
542
- out.append(f'<div class="scroll"><table><tr><th>{_e(title)}</th><th>Message</th><th>Since</th><th>Folder</th></tr>')
543
- for s in group:
544
- stale = " (stale?)" if s["stale"] else ""
545
- out.append(f"<tr><td><strong>{_e(s['session'])}</strong></td><td>{_e(s['message'])}</td>"
546
- f"<td>{_e(s['since'])}{_e(stale)}</td><td><code>{_e(s['cwd'])}</code></td></tr>")
547
- out.append("</table></div>")
548
- if gates:
549
- out.append('<div class="scroll"><table><tr><th>Owner gate</th><th>What it needs</th><th>Check</th></tr>')
550
- for g in gates:
551
- out.append(f"<tr><td><strong>{_e(g['milestone'])}</strong></td><td>{_e(g['reason'])}</td>"
552
- f"<td><code>{_e(g['check'])}</code></td></tr>")
553
- out.append("</table></div>")
554
- out.append("</section>")
555
- return "".join(out)
556
-
557
-
558
- def _swimlane(model: dict) -> str:
559
- milestones, lanes = model["milestones"], model["lanes"]
560
- cols = len(milestones)
561
- # The section has the class `timeline` as well as the id: the hub prefixes every id, so the phone CSS selects by class.
562
- out = ['<section class="card timeline" id="timeline"><div class="sec-h">' + _h2("chart-gantt", "Timeline") + '<span class="note">plans as '
563
- 'lanes, milestones as columns in roadmap order, one tile per phase</span></div><div class="scroll">',
564
- f'<div class="lanes" style="grid-template-columns:150px repeat({cols},minmax(110px,1fr));width:100%;'
565
- f'min-width:{150 + cols * 110}px">',
566
- '<div class="hd ln">Plan / milestone</div>']
567
- for ms in milestones:
568
- dep = f"after {', '.join(ms['depends'])}" if ms["depends"] else "starts first"
569
- n = len(ms["blockers"])
570
- count = f' <span class="bcount">{n} gate(s)</span>' if n else ""
571
- out.append(f'<div class="hd">{_e(ms["id"])} {_pill(ms["status"])}<div class="empty" style="font-weight:400;'
572
- f'font-size:11px">{_e(dep)}</div>{count}</div>')
573
- plan_lanes = lanes or ["-"]
574
- for i, lane in enumerate(plan_lanes):
575
- done = sum(1 for ms in milestones for ph in ms["phases"] if ph["plan"] == lane and ph["tile"] in ("done", "moved"))
576
- total = sum(1 for ms in milestones for ph in ms["phases"] if ph["plan"] == lane)
577
- out.append(f'<div class="ln" style="--lc:var(--c{i % 6})">{_e(lane)}<div class="empty" '
578
- f'style="font-weight:400;font-size:11px">{done}/{total} done</div></div>')
579
- for ms in milestones:
580
- tiles = []
581
- for ph in ms["phases"]:
582
- if ph["plan"] != lane:
583
- continue
584
- hi = " hi" if "high" in ph.get("risk", "").lower() else ""
585
- title = f"{ph['ref']} {ph['name']} | {ph['tracker'] or ph['state']}"
586
- tiles.append(f'<div class="tile {_e(ph["tile"])}{hi}" data-q="{_e(ms["id"])} {_e(ph["ref"])}" title="{_e(title)}">'
587
- f'{_tile_icon(ph["tile"])}<b>{_e(ph["num"])}</b>'
588
- f'<span>{_e(ph["name"] or ph["ref"])}</span></div>')
589
- out.append(f"<div>{''.join(tiles)}</div>")
590
- if any(ms["blockers"] for ms in milestones): # the blockers get their own lane, so the column headers stay short
591
- out.append('<div class="ln">Owner and outside</div>')
592
- for ms in milestones:
593
- cells = []
594
- for b in ms["blockers"]:
595
- reason = str(b["reason"])
596
- short = reason if len(reason) <= 60 else reason[:60] + "…"
597
- cells.append(f'<div class="gate" title="{_e(reason)}">{_e(b["type"])}: {_e(short)}</div>')
598
- out.append(f"<div>{''.join(cells)}</div>")
599
- out.append('</div></div><div class="lane-list">')
600
- for ms in milestones: # the phone list: the grid is hidden on a narrow screen
601
- out.append(f'<h3>{_e(ms["id"])} {_pill(ms["status"])}</h3>')
602
- for ph in ms["phases"]:
603
- hi = " hi" if "high" in ph.get("risk", "").lower() else ""
604
- out.append(f'<div class="ltile {_e(ph["tile"])}{hi}" data-q="{_e(ms["id"])} {_e(ph["ref"])}">{_tile_icon(ph["tile"])}'
605
- f'<b>{_e(ph["plan"])} {_e(ph["num"])}</b>'
606
- f'<span>{_e(ph["name"] or ph["ref"])}</span></div>')
607
- out.append('</div><div class="legend"><span>colour: to do · <b>in progress</b> · done · striped = moved · '
608
- 'amber = blocked</span><span>red dot = Risk high (stops for review)</span></div></section>')
609
- return "".join(out)
610
-
611
-
612
- def _summary(model: dict) -> str:
613
- phases = [ph for ms in model["milestones"] for ph in ms["phases"]]
614
- done = sum(1 for ph in phases if ph["tile"] in ("done", "moved"))
615
- building = [ph["ref"] for ph in phases if ph["tile"] == "in-progress"]
616
- high = sum(1 for ph in phases if "high" in ph.get("risk", "").lower())
617
- nxt = model.get("next") or {}
618
- nxt_txt = f"{nxt.get('milestone', '')} {nxt.get('plan', '')}#{nxt.get('phase', '')}" if nxt else "none ready"
619
- return ('<section class="kpis" id="overview" aria-label="Summary">'
620
- + _kpi("circle-check-big", "k-done", f"{_e(done)} / {_e(len(phases))}", "phases done")
621
- + _kpi("milestone", "k-done", f'{_e(model["done"])} / {_e(model["total"])}', "milestones done")
622
- + _kpi("loader-circle", "", _e(len(building)), f'in progress: {_e(", ".join(building) or "none")}')
623
- + _kpi("triangle-alert", "k-block" if high else "", _e(high), "high-risk phases")
624
- + _kpi("skip-forward", "", _e(nxt_txt), "next batch for the runner")
625
- + "</section>")
626
-
627
-
628
- def _tile_icon(state: str) -> str:
629
- """The state of a timeline tile as a named icon: the tile's colour is not the only cue."""
630
- return _icon(_STATUS_ICON.get(state, "circle"), _LABEL.get(state, state))
631
-
632
-
633
- def _ms_tone(ms: dict) -> str:
634
- """The accent of a milestone card: done, wait (an owner gate), block, prog or todo."""
635
- if ms["status"] in ("done", "not-needed"):
636
- return "done"
637
- if any(b.get("type") == "owner-gate" for b in ms["blockers"]):
638
- return "wait"
639
- if ms["blockers"] or ms["status"] == "blocked":
640
- return "block"
641
- return "prog" if ms["status"] == "in-progress" else "todo"
642
-
643
-
644
- def _done_phases(ms: dict) -> int:
645
- return sum(1 for ph in ms["phases"] if ph["tile"] in ("done", "moved"))
646
-
647
-
648
- def _flow(model: dict) -> str:
649
- """The milestones as a left-to-right chain in roadmap order; each node links to its milestone below."""
650
- nodes = []
651
- for ms in model["milestones"]:
652
- dep = f"after {', '.join(ms['depends'])}" if ms["depends"] else "starts first"
653
- nodes.append(f'<a class="fnode s-{_e(ms["status"])}" data-q="{_e(ms["id"])}" href="#ms-{_e(ms["id"])}"><b>{_e(ms["id"])}</b> '
654
- f'{_pill(ms["status"])}<span>{_e(dep)} · {_e(_done_phases(ms))}/{_e(len(ms["phases"]))} ph</span></a>')
655
- chain = '<span class="arrow" aria-hidden="true">→</span>'.join(nodes)
656
- return (f'<section id="flow"><div class="sec-h">{_h2("workflow", "Flow")}<span class="note">milestones in roadmap order</span></div>'
657
- f'<div class="card scroll"><div class="flow">{chain}</div></div></section>')
658
-
659
-
660
- def _now_next_later(model: dict) -> str:
661
- ms_all = model["milestones"]
662
- status = {ms["id"]: ms["status"] for ms in ms_all}
663
- groups: dict[str, list[dict]] = {"Now": [], "Next": [], "Later": []}
664
- for ms in ms_all:
665
- if ms["status"] in ("done", "not-needed"):
666
- continue
667
- ready = all(status.get(d) in ("done", "not-needed") for d in ms["depends"])
668
- if ms["status"] == "in-progress" or (ready and not ms["blockers"]):
669
- groups["Now"].append(ms)
670
- elif any(d in [m["id"] for m in groups["Now"]] for d in ms["depends"]):
671
- groups["Next"].append(ms)
672
- else:
673
- groups["Later"].append(ms)
674
- cols = []
675
- for title, items in groups.items():
676
- body = "".join(f'<a class="rcard" href="#ms-{_e(m["id"])}" data-q="{_e(m["id"])}" data-st="{_ms_tone(m)}">'
677
- f'<span><strong>{_e(m["id"])}</strong> {_pill(m["status"])}</span>'
678
- f'{_bar(_done_phases(m), len(m["phases"]))}'
679
- + "".join(f'<span class="note">{_e(b["type"])}</span>' for b in m["blockers"])
680
- + "</a>" for m in items)
681
- cols.append(f'<div><h3>{_e(title)}</h3>{body or "<p class=empty>none</p>"}</div>')
682
- return ('<section id="board"><div class="sec-h">' + _h2("square-kanban", "Now, next, later") +
683
- '<span class="note">which milestones can start</span></div>'
684
- f'<div class="cols">{"".join(cols)}</div></section>')
685
-
686
-
687
- def _gates(model: dict) -> str:
688
- rows = [(ms["id"], b) for ms in model["milestones"] for b in ms["blockers"]]
689
- body = "".join(f"<tr><td><strong>{_e(mid)}</strong></td>"
690
- f"<td>{_kind(str(b['type']))}</td><td>{_e(b['reason'])}</td>"
691
- f"<td><code>{_e(b['check'])}</code></td></tr>" for mid, b in rows)
692
- return (f'<section class="card" id="gates"><div class="sec-h">{_h2("shield-alert", "Gates and blockers")}'
693
- f'<span class="note">{_e(len(rows))} open</span></div>'
694
- + (f'<div class="scroll"><table><tr><th>Milestone</th><th>Type</th><th>Reason</th><th>Check</th></tr>{body}'
695
- "</table></div>" if rows else '<p class="empty">No blockers.</p>') + "</section>")
696
-
697
-
698
- def _milestones(model: dict) -> str:
699
- out = ['<section id="milestones"><div class="sec-h">' + _h2("milestone", "Milestones and phases") + '<span class="note">every phase with '
700
- 'model, lane, risk and Tracker status</span></div>']
701
- for ms in model["milestones"]:
702
- rows = "".join(
703
- f"<tr data-q=\"{_e(ms['id'])} {_e(ph['ref'])}\" data-qn=\"1\"><td><code>{_e(ph['ref'])}</code></td><td>{_e(ph['name'])}</td>"
704
- f"<td>{_e(_short_model(ph['model']))}</td>"
705
- f"<td>{_e(ph['lane'].split(' ', 1)[0] if ph['lane'] else '-')}</td>"
706
- f"<td>{_e(ph['risk'] or '-')}</td><td>{_pill(ph['tile'])} {_e(ph['tracker'])}</td></tr>"
707
- for ph in ms["phases"])
708
- target = f" · target {_e(ms['target'])}" if ms.get("target") else ""
709
- out.append(f'<details class="card" id="ms-{_e(ms["id"])}" data-q="{_e(ms["id"])}" data-qn="1"><summary>{_e(ms["id"])} '
710
- f'{_pill(ms["status"])} <span class="note">owner {_e(ms["owner"])}{target} · '
711
- f'after {_e(", ".join(ms["depends"]) or "-")}</span></summary>'
712
- '<div class="scroll"><table><tr><th>Phase</th><th>Name</th><th>Model</th><th>Lane</th><th>Risk</th>'
713
- f'<th>Tracker</th></tr>{rows or "<tr><td colspan=6 class=empty>no build phases</td></tr>"}'
714
- "</table></div></details>")
715
- out.append("</section>")
716
- return "".join(out)
717
-
718
-
719
- def _runner(model: dict) -> str:
720
- r = model["runner"]
721
- parts = []
722
- if r["lock"]:
723
- lk = r["lock"]
724
- parts.append(f"<p>Running batch <code>{_e(lk.get('batch'))}</code> since {_e(lk.get('started_utc'))} "
725
- f"(host {_e(lk.get('host'))}, pid {_e(lk.get('pid'))}).</p>")
726
- else:
727
- parts.append('<p class="empty">No runner holds this roadmap now.</p>')
728
- if r["stale_lock"]:
729
- parts.append(f"<p>A stale runner lock remains (batch <code>{_e(r['stale_lock'].get('batch'))}</code>): "
730
- "the runner that held it is gone.</p>")
731
- stop = r["last_stop"]
732
- if stop:
733
- if str(stop.get("reason")) == "running":
734
- parts.append("<p>Last stop record: running now.</p>")
735
- else:
736
- code = f" (exit {_e(stop.get('exit'))})" if stop.get("exit") is not None else ""
737
- parts.append(f"<p>Last stop {_e(stop.get('utc'))}: {_e(stop.get('reason'))}{code}.</p>")
738
- for err in r["errors"]:
739
- parts.append(f"<p>Could not read {_e(err)}.</p>")
740
- nxt = model.get("next")
741
- if nxt:
742
- parts.append(f"<p>Next batch: <code>{_e(nxt.get('milestone'))} {_e(nxt.get('plan'))}#{_e(nxt.get('phase'))}"
743
- "</code></p>")
744
- return ('<section class="card" id="runner"><div class="sec-h">' + _h2("cpu", "Runner") +
745
- '<span class="note">roadmap-run state on this machine</span></div>' + "".join(parts) + "</section>")
746
-
747
-
748
- # The sections of a roadmap view, in page order: the nav sub-links. `render_body` writes them in this order.
749
- _PAGE_ANCHORS = [("waiting", "Waiting"), ("overview", "Overview"), ("flow", "Flow"), ("board", "Board"),
750
- ("timeline", "Timeline"), ("gates", "Gates"), ("milestones", "Milestones"), ("runner", "Runner")]
751
-
752
- def _rid(folder, slug) -> str | None:
753
- """The view id of a roadmap in `index.html`: `rm-<the folder's 6 hex>-<slug>` (the 6 hex keep two clones with
754
- one repo name apart), or None when the folder has no `-<6hex>` tag or the slug breaks the
755
- slug rule (such a row gets no view: its name is not safe in an id or a selector)."""
756
- m = re.fullmatch(r".+-([0-9a-f]{6})", str(folder or ""))
757
- if not m or not isinstance(slug, str) or not _SLUG_RE.fullmatch(slug):
758
- return None
759
- return f"rm-{m.group(1)}-{slug}"
760
-
761
-
762
- def _prefix_ids(body: str, rid: str) -> str:
763
- """Every `id="x"` and `href="#x"` in a roadmap body becomes `<rid>-x`, so two roadmaps in one file never share an
764
- id. Safe on rendered HTML: every value from the files is escaped, so a `"` in it is `&quot;`."""
765
- body = re.sub(r' id="([A-Za-z][\w-]*)"', lambda m: f' id="{rid}-{m.group(1)}"', body)
766
- return re.sub(r' href="#(?!ic-)([A-Za-z][\w-]*)"', lambda m: f' href="#{rid}-{m.group(1)}"', body)
767
-
768
-
769
- def _stub(rid: str, slug: str) -> str:
770
- """`<slug>.html`: one line that opens the roadmap's view in the hub, so an old link or bookmark still works."""
771
- target = f"../index.html#{rid}"
772
- return ('<!doctype html><html lang="en"><head><meta charset="utf-8">'
773
- f'<meta http-equiv="refresh" content="0;url={_e(target)}"><title>Roadmap {_e(slug)}</title></head>'
774
- f'<body><p><a href="{_e(target)}">Open roadmap {_e(slug)}</a></p></body></html>\n')
775
-
776
-
777
- def render_html(model: dict) -> str:
778
- """One self-contained roadmap page (an `--out` copy): the app shell with an empty repo tree, one theme script,
779
- one local font link, no network. Every value from the files is escaped."""
780
- slug = model["roadmap"]
781
- return _shell(title=f"Roadmap {slug}", base="../", nav=_nav([], "../"), crumbs=_crumbs("", slug),
782
- body=render_body(model), generated=model.get("generated", ""))
783
-
784
-
785
- def render_body(model: dict, site: bool = False) -> str:
786
- """Everything inside `<main>`: the header and the sections. `write_page` keeps it as `<slug>.body.html`; the
787
- hub puts it, with its ids prefixed, in `index.html` as the roadmap's view. A shared copy (`site`) leaves out the
788
- session tables and the Runner section."""
789
- title = f"Roadmap {model['roadmap']}"
790
- phases = [ph for ms in model["milestones"] for ph in ms["phases"]]
791
- done = sum(1 for ph in phases if ph["tile"] in ("done", "moved"))
792
- commit = f" · origin <code>{_e(model.get('origin_commit'))}</code>" if model.get("origin_commit") else ""
793
- chips = "".join(
794
- f'<span class="chip" style="--lc:var(--c{i % 6})"><b>{_e(plan)}</b> <span>'
795
- f'{_e(sum(1 for ph in phases if ph["plan"] == plan and ph["tile"] in ("done", "moved")))}/'
796
- f'{_e(sum(1 for ph in phases if ph["plan"] == plan))} phases</span></span>'
797
- for i, plan in enumerate(model["lanes"]))
798
- return "".join([
799
- f'<header class="hdr"><div><h1>{_e(title)}</h1><p class="sub">{_e(model["done"])} of {_e(model["total"])} '
800
- f'milestones · {_e(done)} of {_e(len(phases))} phases done · branch <code>{_e(model["branch"])}</code>'
801
- f'{commit} · generated {_e(model["generated"])}</p>'
802
- + (f'<div class="chips">{chips}</div>' if chips else "") + "</div></header>",
803
- _waiting_section(model, site), _summary(model), _flow(model), _now_next_later(model), _swimlane(model),
804
- _gates(model), _milestones(model), "" if site else _runner(model),
805
- '<p class="empty">Built from roadmap.md and the plan Trackers and headers on origin.</p>' if site else
806
- '<p class="empty">Built from roadmap.md, the plan Trackers and headers on origin, the runner state and the '
807
- "session-state folder. Re-rendered by the runner, /handoff, /pr-merge, /catchup and the waiting hooks.</p>"])
808
-
809
-
810
- def default_page_path(root: Path, slug: str, home: Path | None = None, base: Path | None = None) -> Path:
811
- """`~/.caddis/roadmap-pages/<repo folder>-<6 hex>/<slug>.html`: outside every checkout, so a render never makes a
812
- repo dirty (17 Oct: the in-repo `.local/` folder is not gitignored in every repo). The folder is the MAIN
813
- checkout (a worktree shares its page); the 6 hex of its path keep two clones with one name apart. `base` (the
814
- shared copy's build folder) stands in for the pages root."""
815
- main = main_checkout(root)
816
- tag = hashlib.sha1(str(main).lower().encode("utf-8")).hexdigest()[:6]
817
- return (base if base is not None else pages_root(home)) / f"{main.name}-{tag}" / f"{slug}.html"
818
-
819
-
820
- def write_page(root: Path, slug: str, out: Path | None, roadmap_mod, *, site_dir: Path | None = None) -> Path | None:
821
- """At the default path: `<slug>.body.html` (the page body, which the hub shows as a view of `index.html`), a
822
- one-line `<slug>.html` that opens that view, and `<slug>.json` (the one-row summary the hub is built from). An
823
- `--out` page is a one-off self-contained copy and stays out of the hub. None: a newer caddis wrote this page,
824
- so it is kept. `site_dir` (the shared copy's build folder) writes there instead, with no version gate, and
825
- leaves this machine's waiting sessions and runner out of the model before anything is rendered."""
826
- path = Path(out) if out else default_page_path(root, slug, base=site_dir)
827
- if out is None and site_dir is None and _owned_by_newer(slug, path.with_suffix(".json")): # a skip does no work
828
- return None
829
- model = build(root, slug, roadmap_mod)
830
- if site_dir is not None: # a CI run has no session marks and no runner: hide them, never show them as empty
831
- model["sessions"] = []
832
- model["runner"] = {"lock": None, "stale_lock": None, "last_stop": None, "errors": []}
833
- path.parent.mkdir(parents=True, exist_ok=True)
834
- if out is not None:
835
- _write_atomic(path, render_html(model))
836
- return path
837
- _write_atomic(path.with_suffix(".body.html"), render_body(model, site=site_dir is not None))
838
- rid = _rid(path.parent.name, model["roadmap"])
839
- _write_atomic(path, _stub(rid, model["roadmap"]) if rid else render_html(model))
840
- try: # the summary feeds the hub only: the page is written, so a failure here never fails the render
841
- _write_atomic(path.with_suffix(".json"),
842
- json.dumps(page_summary(model, main_checkout(root), path), indent=1))
843
- except Exception as exc:
844
- print(f"[ROADMAP] hub summary not written: {exc}", file=sys.stderr)
845
- return path
846
-
847
-
848
- # ---- the version gate: a session on an old plugin never overwrites what a newer caddis wrote (robustness #8) -------
849
-
850
- @functools.lru_cache(maxsize=8)
851
- def generator_version(here: Path | None = None) -> str:
852
- """This caddis's version: the Claude plugin's `.claude-plugin/plugin.json` or the agy plugin's root
853
- `plugin.json` (both beside `scripts/`), else the source checkout's `caddis` entry in
854
- `.github/runtime-targets.json`, else "dev"."""
855
- base = Path(here or Path(__file__).resolve().parent).parent
856
- for manifest in (base / ".claude-plugin" / "plugin.json", base / "plugin.json"):
857
- data, _ = _read_json(manifest)
858
- if data and data.get("version"):
859
- return str(data["version"])
860
- data, _ = _read_json(base / ".github" / "runtime-targets.json")
861
- for target in (data or {}).get("targets") or []:
862
- plugin = target.get("plugin") if isinstance(target, dict) else None
863
- if isinstance(plugin, dict) and plugin.get("name") == "caddis" and plugin.get("version"):
864
- return str(plugin["version"])
865
- return "dev"
866
-
867
-
868
- def _version_key(text) -> tuple[int, ...] | None:
869
- parts = str(text or "").strip().split(".")
870
- return tuple(int(p) for p in parts) if all(p.isdigit() for p in parts) else None
871
-
872
-
873
- def is_newer(theirs, mine) -> bool:
874
- """True only when both are numeric versions and `theirs` is the higher one; "dev" or "" never blocks."""
875
- a, b = _version_key(theirs), _version_key(mine)
876
- return a is not None and b is not None and a > b
877
-
878
-
879
- GENERATOR_OWNERSHIP_S = 1800 # a newer caddis owns a page only while it keeps writing it (review of #71)
880
- # While the newer version is still INSTALLED on this machine, it owns the page much longer: an older session that is
881
- # still open must not undo a release (20 Oct 2026: a 1.3.145 session re-rendered the 1.3.147 hub in the old layout
882
- # 30 minutes after the release). A real downgrade removes the newer version, and the 30 minutes apply again.
883
- INSTALLED_OWNERSHIP_S = 24 * 3600
884
-
885
-
886
- def installed_versions(home: Path | None = None) -> set[str]:
887
- """The caddis versions installed on this machine: the Claude Code plugin cache folders and agy's plugin
888
- manifest. Empty when none can be read."""
889
- base = Path(home or Path.home())
890
- found: set[str] = set()
891
- try:
892
- for d in (base / ".claude" / "plugins" / "cache" / "caddis" / "caddis").iterdir():
893
- if d.is_dir() and _version_key(d.name) is not None:
894
- found.add(d.name)
895
- except OSError:
896
- pass
897
- data, _ = _read_json(base / ".gemini" / "config" / "plugins" / "caddis" / "plugin.json")
898
- if isinstance(data, dict) and _version_key(data.get("version")) is not None:
899
- found.add(str(data["version"]))
900
- return found
901
-
902
-
903
- def _ownership_s(theirs: str, home: Path | None = None) -> int:
904
- """How long a newer caddis owns what it wrote: a day while it is installed under `home`, else
905
- GENERATOR_OWNERSHIP_S."""
906
- return INSTALLED_OWNERSHIP_S if theirs in installed_versions(home) else GENERATOR_OWNERSHIP_S
907
-
908
-
909
- def _newer_owner(summary: Path) -> tuple[str, bool]:
910
- """(version, live): the newer caddis that wrote `summary` ("" when it is not newer), and whether it wrote it
911
- within its ownership window (`_ownership_s`). An unreadable time is not live: a downgrade must never freeze a
912
- page."""
913
- data, _ = _read_json(summary)
914
- theirs = str((data or {}).get("generator") or "")
915
- if not is_newer(theirs, generator_version()):
916
- return "", False
917
- age_h = _age_h(str((data or {}).get("generated_utc") or ""), datetime.datetime.now(datetime.timezone.utc))
918
- return theirs, age_h is not None and age_h * 3600 <= _ownership_s(theirs)
919
-
920
-
921
- def _gate(label: str, theirs: str, live: bool) -> bool:
922
- """True: skip the write. Prints one line when a newer caddis owns it, or when this one takes it over."""
923
- if theirs and live:
924
- print(f"[ROADMAP] {label}: a newer caddis ({theirs}) owns this page; skipped")
925
- return True
926
- if theirs:
927
- print(f"[ROADMAP] {label}: taking over from caddis {theirs} (it has not written for "
928
- f"{_ownership_s(theirs) // 60} min)")
929
- return False
930
-
931
-
932
- def _owned_by_newer(slug: str, summary: Path) -> bool:
933
- return _gate(slug, *_newer_owner(summary))
934
-
935
-
936
- # ---- the hub: one page over every roadmap page on this machine, grouped per repo ---------------------------------
937
-
938
- HUB_STALE_H = 24 # a summary older than this is marked "not refreshed"
939
-
940
-
941
- def _write_atomic(path: Path, text: str) -> None:
942
- """Write then rename, so a reader (a browser, nginx, a second render) never sees half a file."""
943
- tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
944
- try:
945
- tmp.write_text(text, encoding="utf-8")
946
- for attempt in range(5): # Windows: a reader (browser, nginx, another render) can hold the target briefly
947
- try:
948
- os.replace(tmp, path)
949
- return
950
- except PermissionError:
951
- if attempt == 4:
952
- raise
953
- time.sleep(0.1 * (attempt + 1))
954
- finally:
955
- try:
956
- tmp.unlink()
957
- except FileNotFoundError:
958
- pass
959
-
960
-
961
- ASSET_DIR = Path(__file__).resolve().parent / "roadmap_assets"
962
- ASSET_FILES = ("fonts.css", "OFL-MapleMono.txt", "OFL-Atkinson.txt", "LICENSE-Lucide.txt")
963
- # icons.svg is shipped beside them but not copied: the sprite goes inline into each page (`_sprite`).
964
-
965
-
966
- def install_assets(root_dir: Path) -> int:
967
- """Copy the bundled fonts (and their licences) to `<root_dir>/_assets/` when missing or changed. Text is compared
968
- as text, not bytes: `_write_atomic` writes CRLF on Windows, so a byte compare would rewrite every time. A source
969
- file that is not shipped is skipped. Returns the number of files written."""
970
- written = 0
971
- target_dir = root_dir / "_assets"
972
- for name in ASSET_FILES:
973
- src = ASSET_DIR / name
974
- if not src.exists():
975
- continue
976
- text = src.read_text(encoding="utf-8")
977
- dst = target_dir / name
978
- try:
979
- if dst.read_text(encoding="utf-8") == text:
980
- continue
981
- except FileNotFoundError:
982
- pass
983
- target_dir.mkdir(parents=True, exist_ok=True)
984
- _write_atomic(dst, text)
985
- written += 1
986
- return written
987
-
988
-
989
- def pages_root(home: Path | None = None) -> Path:
990
- return Path(home or Path.home()) / ".caddis" / "roadmap-pages"
991
-
992
-
993
- def page_summary(model: dict, main: Path, path: Path) -> dict:
994
- """The hub's row for one roadmap. Waiting sessions belong to the checkout, not to one roadmap, so the hub shows
995
- them once per repo."""
996
- phases = [ph for ms in model["milestones"] for ph in ms["phases"]]
997
- r = model["runner"]
998
- stop = r.get("last_stop") or {}
999
- runner = ("running" if r.get("lock") or str(stop.get("reason")) == "running"
1000
- else f"stopped: {stop.get('reason')}" if stop.get("reason") else "")
1001
- nxt = model.get("next") or {}
1002
- return {
1003
- "version": 2, "generator": generator_version(), "repo": main.name, "checkout": str(main), "folder": path.parent.name, "slug": model["roadmap"],
1004
- "branch": model["branch"], "origin_commit": model.get("origin_commit", ""),
1005
- "generated_utc": model["generated"],
1006
- "milestones_done": model["done"], "milestones_total": model["total"],
1007
- "phases_done": sum(1 for ph in phases if ph["tile"] in ("done", "moved")), "phases_total": len(phases),
1008
- "in_progress": [ph["ref"] for ph in phases if ph["tile"] == "in-progress"],
1009
- "blocked": sum(1 for ph in phases if ph["tile"] == "blocked"),
1010
- "owner_gates": [{"milestone": g["milestone"], "reason": g["reason"]} for g in model["waiting"]],
1011
- "sessions": [{"session": s["session"], "message": s["message"], "since": s["since"],
1012
- "asking": not str(s.get("kind", "")).startswith("idle"), "stale": s["stale"]}
1013
- for s in model["sessions"]],
1014
- "runner": runner,
1015
- "next": f"{nxt.get('milestone', '')} {nxt.get('plan', '')}#{nxt.get('phase', '')}" if nxt else "",
1016
- "milestones": [{"id": ms["id"], "status": ms["status"]} for ms in model["milestones"]],
1017
- "blockers": [{"milestone": ms["id"], "type": b["type"], "reason": b["reason"], "check": b["check"]}
1018
- for ms in model["milestones"] for b in ms["blockers"]
1019
- if ms["status"] not in ("done", "not-needed")],
1020
- "runner_detail": {"lock": r.get("lock"), "stale_lock": bool(r.get("stale_lock")),
1021
- "last_stop": r.get("last_stop"), "errors": r.get("errors", [])},
1022
- }
1023
-
1024
-
1025
- # The roadmap slug rule, copied from caddis_roadmap.SLUG_RE_TEXT (a test keeps the two equal): this module stays
1026
- # importable on its own, without the roadmap module and its git helpers. A slug never holds a dot, so `<slug>.body.html` can never be another
1027
- # roadmap's `<slug>.html`; files whose name breaks the rule are never pruned or shown as a view.
1028
- _SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,62}$")
1029
-
1030
-
1031
- def prune_folder(folder: Path, keep: set[str]) -> int:
1032
- """Remove the page, body and summary of each roadmap that is no longer on origin. Only `<slug>.json` files and
1033
- their `<slug>.html` and `<slug>.body.html` files are touched. Returns how many roadmaps were removed."""
1034
- removed = 0
1035
- if not folder.is_dir():
1036
- return removed
1037
- for js in folder.glob("*.json"):
1038
- # a live newer caddis may know a roadmap this one cannot list
1039
- if js.stem in keep or not _SLUG_RE.fullmatch(js.stem) or _newer_owner(js)[1]:
1040
- continue
1041
- for f in (js, js.with_suffix(".html"), js.with_suffix(".body.html")):
1042
- try:
1043
- f.unlink()
1044
- except FileNotFoundError:
1045
- pass
1046
- removed += 1
1047
- return removed
1048
-
1049
-
1050
- def read_summaries(root_dir: Path) -> tuple[list[dict], list[str]]:
1051
- """Every `<repo>-<hex>/<slug>.json` whose page still exists. An unreadable summary is named, not hidden."""
1052
- rows, errors = [], []
1053
- if not root_dir.is_dir():
1054
- return rows, errors
1055
- for js in sorted(root_dir.glob("*/*.json")):
1056
- if not js.with_suffix(".html").exists():
1057
- continue
1058
- data, err = _read_json(js)
1059
- if not isinstance(data, dict) or not data.get("slug"):
1060
- errors.append(err or f"{js.parent.name}/{js.name}: not a roadmap summary")
1061
- continue
1062
- data["page"] = f"{js.parent.name}/{js.with_suffix('.html').name}" # the link comes from the disk, not the file
1063
- data["folder"] = js.parent.name
1064
- data.setdefault("repo", js.parent.name.rsplit("-", 1)[0])
1065
- for key in ("sessions", "owner_gates", "milestones", "blockers"): # a hand-edited summary must not stop the hub for every repo
1066
- items = data.get(key)
1067
- data[key] = [i for i in items if isinstance(i, dict)] if isinstance(items, list) else []
1068
- if not isinstance(data.get("in_progress"), list):
1069
- data["in_progress"] = []
1070
- if not isinstance(data.get("runner_detail"), dict):
1071
- data["runner_detail"] = {}
1072
- rows.append(data)
1073
- return rows, errors
1074
-
1075
-
1076
- def read_bodies(root_dir: Path, rows: list[dict]) -> dict[str, str]:
1077
- """{rid: body} for every row with a view id and a `<slug>.body.html`, read only. The path comes from
1078
- `row["page"]` (set from the disk by `read_summaries`), never from the summary's own text, and only a file
1079
- directly in a `<root_dir>/<folder>/` is read. One row that fails never stops the others."""
1080
- root = Path(root_dir).resolve()
1081
- bodies: dict[str, str] = {}
1082
- for row in rows:
1083
- rel, slug = row.get("page"), row.get("slug")
1084
- rid = _rid(row.get("folder"), slug)
1085
- if rid is None or not isinstance(rel, str) or slug != Path(rel).stem:
1086
- continue
1087
- try:
1088
- page = (root / rel).resolve()
1089
- body_file = page.with_suffix(".body.html")
1090
- if page.parent.parent != root or page.suffix != ".html" or not body_file.is_file():
1091
- continue
1092
- bodies[rid] = body_file.read_text(encoding="utf-8")
1093
- except Exception as exc: # noqa: BLE001 - one bad row never stops the others (docstring)
1094
- print(f"[ROADMAP] {Path(rel).with_suffix('').as_posix()}: body not read: {exc}", file=sys.stderr)
1095
- return bodies
1096
-
1097
-
1098
- def _age_h(utc_text: str, now: datetime.datetime) -> float | None:
1099
- try:
1100
- when = datetime.datetime.strptime(utc_text, "%Y-%m-%d %H:%M UTC").replace(tzinfo=datetime.timezone.utc)
1101
- except (ValueError, TypeError):
1102
- return None
1103
- return (now - when).total_seconds() / 3600
1104
-
1105
-
1106
- def _bar(done: int, total: int) -> str:
1107
- pct = int(round(100 * done / total)) if total else 0
1108
- return (f'<div class="bar" title="{_e(done)} of {_e(total)} phases done"><i style="width:{pct}%"></i></div>'
1109
- f'<span class="empty">{_e(done)}/{_e(total)} phases · {pct}%</span>')
1110
-
1111
-
1112
- def _int(value) -> int:
1113
- try:
1114
- return int(value)
1115
- except (TypeError, ValueError):
1116
- return 0
1117
-
1118
-
1119
- def _row_tone(r: dict) -> str:
1120
- """The accent of a roadmap card on the inbox: wait (an owner gate), block, done, prog or todo."""
1121
- total, done = _int(r.get("phases_total")), _int(r.get("phases_done"))
1122
- if r.get("owner_gates"):
1123
- return "wait"
1124
- if _int(r.get("blocked")):
1125
- return "block"
1126
- if total and done >= total:
1127
- return "done"
1128
- return "prog" if r.get("in_progress") or done else "todo"
1129
-
1130
-
1131
- def _roadmap_link(r: dict, label=None) -> str:
1132
- """The roadmap's name linked to its view; plain text for a row that has no view."""
1133
- rid = _rid(r.get("folder"), r.get("slug"))
1134
- text = _e(r.get("slug") if label is None else label)
1135
- return f'<a href="#{rid}">{text}</a>' if rid else text
1136
-
1137
-
1138
- def _repo_slug_key(r: dict) -> tuple[str, str, str]:
1139
- return (str(r.get("repo", "")).lower(), str(r.get("folder", "")), str(r.get("slug", "")))
1140
-
1141
-
1142
- def _table(head: list[str], body: list[str]) -> str:
1143
- return ('<div class="scroll"><table><tr>' + "".join(f"<th>{_e(h)}</th>" for h in head) + "</tr>"
1144
- + "".join(body) + "</table></div>")
1145
-
1146
-
1147
- def _gates_view(rows: list[dict]) -> str:
1148
- items = []
1149
- for r in rows:
1150
- for b in r.get("blockers") or r.get("owner_gates") or []: # a v1 summary has owner_gates only
1151
- items.append((r, b))
1152
- items.sort(key=lambda rb: (str(rb[1].get("type") or "owner-gate") != "owner-gate", *_repo_slug_key(rb[0]),
1153
- str(rb[1].get("milestone", ""))))
1154
- body = []
1155
- for r, b in items:
1156
- rid, ms = _rid(r.get("folder"), r.get("slug")), str(b.get("milestone", ""))
1157
- ms_text = _e(ms)
1158
- if rid and re.fullmatch(r"[A-Za-z][\w-]*", ms): # the id is prefixed by `_prefix_ids` only when it is plain
1159
- ms_text = f'<a href="#{rid}-ms-{ms_text}">{ms_text}</a>'
1160
- kind = str(b.get("type") or "owner-gate")
1161
- body.append(f'<tr><td><strong>{_e(r.get("repo"))}</strong></td><td>{_roadmap_link(r)}</td><td>{ms_text}</td>'
1162
- f'<td>{_kind(kind)}</td><td>{_e(b.get("reason"))}</td>'
1163
- f'<td><code>{_e(b.get("check") or "-")}</code></td></tr>')
1164
- if not body:
1165
- return '<p class="empty">No open gates or blockers.</p>'
1166
- return _table(["Repo", "Roadmap", "Milestone", "Type", "Reason", "Check"], body)
1167
-
1168
-
1169
- def _sessions_view(rows: list[dict]) -> str:
1170
- out = []
1171
- for _folder, group in _group_rows(rows)[0]:
1172
- sessions = sorted(_sessions_of(group), key=lambda s: not s.get("asking")) # asking first, then by mark order
1173
- if not sessions:
1174
- continue
1175
- body = []
1176
- for s in sessions:
1177
- stale = " (stale?)" if s.get("stale") else ""
1178
- body.append(f'<tr><td><code>{_e(s.get("session"))}</code></td>'
1179
- f'<td>{"asking" if s.get("asking") else "idle"}</td><td>{_e(s.get("message"))}</td>'
1180
- f'<td>{_e(s.get("since"))}{_e(stale)}</td></tr>')
1181
- out.append(f'<div class="card"><h3>{_icon("folder-git-2")}{_e(group[0].get("repo"))}</h3>'
1182
- + _table(["Session", "Asking or idle", "Message", "Since"], body) + "</div>")
1183
- return "".join(out) or '<p class="empty">No session is waiting.</p>'
1184
-
1185
-
1186
- def _runners_view(rows: list[dict]) -> str:
1187
- body = []
1188
- for r in sorted(rows, key=lambda r: (r.get("runner") != "running", *_repo_slug_key(r))):
1189
- detail = r.get("runner_detail") if isinstance(r.get("runner_detail"), dict) else {}
1190
- lock, stop = detail.get("lock"), detail.get("last_stop")
1191
- batch = lock.get("batch") if isinstance(lock, dict) else None
1192
- stop_text = " · ".join(str(v) for v in ((stop or {}).get("reason"), (stop or {}).get("utc")) if v) if isinstance(stop, dict) else ""
1193
- runner = str(r.get("runner") or "")
1194
- pill, icon = (("s-in-progress", "play") if runner == "running" else ("s-blocked", "octagon-alert") if runner
1195
- else ("s-todo", "circle"))
1196
- body.append(f'<tr><td><strong>{_e(r.get("repo"))}</strong></td><td>{_roadmap_link(r)}</td>'
1197
- f'<td><span class="pill {pill}">{_icon(icon)}{_e(runner or "idle")}</span></td><td>{_e(batch or "-")}</td>'
1198
- f'<td>{_e(stop_text or "-")}</td><td>{_e(r.get("next") or "-")}</td></tr>')
1199
- if not body:
1200
- return '<p class="empty">No roadmap pages yet.</p>'
1201
- return _table(["Repo", "Roadmap", "Runner", "Batch", "Last stop", "Next"], body)
1202
-
1203
-
1204
- _VIEWS = {"gates": ("Gates", "Every open owner gate and blocker, across all repos. Owner gates come first.", _gates_view),
1205
- "sessions": ("Sessions", "The newest session marks of each repo.", _sessions_view),
1206
- "runners": ("Runners", "The roadmap runner of every roadmap on this machine.", _runners_view)}
1207
-
1208
-
1209
- def render_view(kind: str, rows: list[dict]) -> str:
1210
- """`<section class="view" id="gates|sessions|runners">`: a cross-repo table over the page summaries. These sections
1211
- sit outside any roadmap body, so their ids are not prefixed; links into a roadmap use its prefixed ids."""
1212
- title, note, fn = _VIEWS[kind]
1213
- return f'<section class="view" id="{kind}">{_h2(_NAV_ICON[kind], title)}<p class="sub">{_e(note)}</p>{fn(rows)}</section>'
1214
-
1215
-
1216
- _SITE_NOTE = "Shared copy — built by CI. Live sessions and runners show only on the owner's machine."
1217
- _SITE_CSS = (".site-banner{margin:0 0 12px;padding:8px 12px;border:1px solid var(--line);border-radius:8px;"
1218
- "border-left:4px solid var(--accent);background:var(--panel2);color:var(--fg);font-size:13px}")
1219
-
1220
-
1221
- def render_hub(rows: list[dict], errors: list[str], now: datetime.datetime,
1222
- bodies: dict[str, str] | None = None, *, site: bool = False, banner: str = "") -> str:
1223
- """The whole app in one file: the inbox and overview view, then one view per roadmap (its body from `bodies`,
1224
- ids prefixed). CSS shows one view at a time, so the nav is the same for every view and is never stale. While the
1225
- inbox shows, the page reloads itself every 60 s (the script), so an open tab follows the renders. A shared copy
1226
- (`site`, built by CI) shows `banner` and leaves out everything of this machine: the sessions and the runners,
1227
- in the nav, the inbox and the views. Owner gates stay: they come from git."""
1228
- bodies = bodies or {}
1229
- errors = list(errors)
1230
- if site: # whatever a summary holds of live state is dropped here too, not only at the writer
1231
- rows = [{**r, "sessions": [], "runner": "", "runner_detail": {}} for r in rows]
1232
- order, need, count = _group_rows(rows)
1233
- phases_done = sum(_int(r.get("phases_done")) for r in rows)
1234
- phases_total = sum(_int(r.get("phases_total")) for r in rows)
1235
- live = sum(1 for r in rows if r.get("runner") == "running")
1236
- blocked = sum(_int(r.get("blocked")) for r in rows)
1237
- out = [f'<p class="site-banner" role="note">{_e(banner or _SITE_NOTE)}</p>' if site else "",
1238
- '<section class="view" id="inbox"><section class="kpis">',
1239
- _kpi("bell-ring", "k-wait" if count else "", _e(count), "Needs you"),
1240
- _kpi("circle-check-big", "k-done", f"{_e(phases_done)} / {_e(phases_total)}",
1241
- "Phases done" + _bar(phases_done, phases_total)),
1242
- _kpi("octagon-alert", "k-block" if blocked else "", _e(blocked), "Blocked phases"),
1243
- "" if site else _kpi("activity", "", _e(live), "Runners live"), "</section>",
1244
- f'<p class="sub">{_e(len(order))} repos · {_e(len(rows))} roadmaps · {_e(count)} item(s) need you · '
1245
- f'generated {_e(now.strftime("%Y-%m-%d %H:%M UTC"))}'
1246
- + ("" if site else " · the inbox reloads every minute") + "</p>",
1247
- f'<section id="needs" class="card wait">{_h2("bell-ring", "Needs you")}']
1248
- if not need:
1249
- out.append('<p class="empty">Nothing is waiting for you.</p>')
1250
- else:
1251
- out.append('<div class="scroll"><table><tr><th>Repo</th><th>What</th><th>Detail</th></tr>')
1252
- for repo, asking, gates in need:
1253
- for s in asking:
1254
- stale = " (stale?)" if s.get("stale") else ""
1255
- out.append(f"<tr><td><strong>{_e(repo)}</strong></td><td>session {_e(s.get('session'))}</td>"
1256
- f"<td>{_e(s.get('message'))} · since {_e(s.get('since'))}{_e(stale)}</td></tr>")
1257
- for r, g in gates:
1258
- out.append(f"<tr><td><strong>{_e(repo)}</strong></td><td>owner gate {_e(r.get('slug'))} "
1259
- f"{_e(g.get('milestone'))}</td><td>{_e(g.get('reason'))}</td></tr>")
1260
- out.append("</table></div>")
1261
- out.append("</section>" + _h2("map", "Roadmaps"))
1262
- if not rows:
1263
- out.append('<p class="card empty">No roadmap page has been rendered on this machine yet. Run '
1264
- "<code>caddis_roadmap.py render --all</code> in a repo that has <code>.caddis/roadmaps/</code>.</p>")
1265
- out.append('<div class="cards">')
1266
- for r in sorted(rows, key=lambda r: (str(r.get("repo", "")).lower(), str(r["folder"]), str(r["slug"]))):
1267
- age = _age_h(str(r.get("generated_utc", "")), now)
1268
- old = " (not refreshed)" if age is not None and age > HUB_STALE_H else ""
1269
- dots = "".join(f'<span class="dot s-{_e(m.get("status"))}">{_e(m.get("id"))}</span>'
1270
- for m in r.get("milestones") or [])
1271
- rid = _rid(r.get("folder"), r.get("slug"))
1272
- if rid is None:
1273
- errors.append(f"{r.get('folder')}/{r.get('slug')}: the folder or slug name breaks the naming rule")
1274
- continue
1275
- ids = " ".join(str(m.get("id")) for m in r.get("milestones") or [])
1276
- out.append(f'<a class="rcard" href="#{rid}" data-q="{_e(r["slug"])} {_e(r.get("repo"))} {_e(ids)}" data-qn="1" '
1277
- f'data-st="{_row_tone(r)}">'
1278
- f'<div><strong>{_icon("map")}{_e(r["slug"])}</strong> <span class="empty">{_e(r.get("repo"))} · '
1279
- f'{_icon("git-branch")}{_e(r.get("branch"))} · {_e(r.get("origin_commit"))}</span></div>'
1280
- f'<div>{_bar(_int(r.get("phases_done")), _int(r.get("phases_total")))} '
1281
- f'{_e(r.get("milestones_done"))}/{_e(r.get("milestones_total"))} milestones</div>'
1282
- f'<div class="dots">{dots}</div>'
1283
- f'<div class="empty">next: {_e(r.get("next") or "-")}'
1284
- + ("" if site else f' · runner: {_e(r.get("runner") or "idle")}') + f'{_e(old)}</div></a>')
1285
- out.append("</div>")
1286
- for err in errors:
1287
- out.append(f'<p class="empty">Could not read {_e(err)}.</p>')
1288
- out.append('<p class="empty">' + ("Built by CI from the roadmaps on origin." if site else
1289
- "Built from the page summaries in this folder. Every roadmap page render rebuilds it.") + "</p></section>")
1290
- rids = []
1291
- for r in sorted(rows, key=lambda r: (str(r.get("repo", "")).lower(), str(r["folder"]), str(r["slug"]))):
1292
- rid = _rid(r.get("folder"), r.get("slug"))
1293
- if rid is None:
1294
- continue
1295
- rids.append(rid)
1296
- body = bodies.get(rid)
1297
- inner = (_prefix_ids(body, rid) if body is not None else
1298
- f'<p class="card empty">No page body yet for {_e(r["slug"])}: run <code>caddis_roadmap.py render</code> '
1299
- "in its repo.</p>")
1300
- out.append(f'<section class="view" id="{rid}"><p class="view-crumbs"><a href="#inbox">Roadmaps</a> › '
1301
- f'{_e(r.get("repo"))} › <strong>{_e(r["slug"])}</strong></p>{inner}</section>')
1302
- for kind in _VIEWS:
1303
- if not (site and kind in _LOCAL_VIEWS):
1304
- out.append(render_view(kind, rows))
1305
- return _shell(title="Roadmaps", base="", nav=_nav(rows, "", site), body="".join(out),
1306
- crumbs='<a href="#inbox">Roadmaps</a> › <strong>Inbox</strong>',
1307
- generated=now.strftime("%Y-%m-%d %H:%M UTC"),
1308
- css=_view_css(rids, site) + (_SITE_CSS if site else ""),
1309
- script=_SITE_THEME_SCRIPT if site else None)
1310
-
1311
-
1312
- def write_hub(home: Path | None = None, now: datetime.datetime | None = None, *,
1313
- site_dir: Path | None = None, banner: str = "") -> Path | None:
1314
- """`~/.caddis/roadmap-pages/index.html`: every roadmap page on this machine, grouped per repo. None: a newer
1315
- caddis wrote the hub (its version is in `.hub-generator`), so it is kept. `site_dir` (the shared copy's build
1316
- folder) is written instead, with `banner`, with no live sessions or runners, and with no version gate and no
1317
- stamp: CI is the only writer of that folder."""
1318
- root_dir = pages_root(home) if site_dir is None else Path(site_dir)
1319
- root_dir.mkdir(parents=True, exist_ok=True)
1320
- stamp = root_dir / ".hub-generator"
1321
- if site_dir is None:
1322
- try:
1323
- theirs = stamp.read_text(encoding="utf-8").strip()
1324
- if not is_newer(theirs, generator_version()):
1325
- theirs = ""
1326
- live = bool(theirs) and time.time() - stamp.stat().st_mtime <= _ownership_s(theirs, home)
1327
- except (OSError, UnicodeDecodeError):
1328
- theirs, live = "", False
1329
- if _gate("hub", theirs, live):
1330
- return None
1331
- try:
1332
- install_assets(root_dir)
1333
- except Exception as exc: # a missing font file must never stop the hub
1334
- print(f"[ROADMAP] assets not installed: {exc}", file=sys.stderr)
1335
- rows, errors = read_summaries(root_dir)
1336
- try: # a hub without the roadmap bodies is better than no hub
1337
- bodies = read_bodies(root_dir, rows)
1338
- except Exception as exc:
1339
- print(f"[ROADMAP] page bodies not read: {exc}", file=sys.stderr)
1340
- bodies = {}
1341
- path = root_dir / "index.html"
1342
- now = now or datetime.datetime.now(datetime.timezone.utc)
1343
- if site_dir is not None:
1344
- _write_atomic(path, render_hub(rows, errors, now, bodies, site=True, banner=banner))
1345
- return path
1346
- _write_atomic(path, render_hub(rows, errors, now, bodies))
1347
- _write_atomic(stamp, generator_version() + "\n")
1348
- return path
1349
-
1350
-
1351
- # ---- the shared copy: `render --site <dir>` builds in <dir>/build and publishes an allow-list to <dir>/public -----
1352
-
1353
- def _short_sha(root: Path) -> str:
1354
- try:
1355
- done = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=root, capture_output=True, text=True,
1356
- stdin=subprocess.DEVNULL, timeout=15,
1357
- creationflags=0x08000000 if os.name == "nt" else 0)
1358
- except (OSError, subprocess.SubprocessError):
1359
- return "unknown"
1360
- return done.stdout.strip() or "unknown" if done.returncode == 0 else "unknown"
1361
-
1362
-
1363
- def site_banner(root: Path, now: datetime.datetime | None = None, env=None) -> str:
1364
- """The shared copy's banner (plain text; `render_hub` escapes it). CI names the repo and commit in
1365
- `GITHUB_REPOSITORY` and `GITHUB_SHA`; on a local run they are the checkout's folder name and `git rev-parse`."""
1366
- env = os.environ if env is None else env
1367
- repo = (env.get("GITHUB_REPOSITORY") or "").strip() or main_checkout(Path(root)).name
1368
- sha = (env.get("GITHUB_SHA") or "").strip()[:7] or _short_sha(Path(root))
1369
- when = (now or datetime.datetime.now(datetime.timezone.utc)).strftime("%Y-%m-%d %H:%M UTC")
1370
- return (f"Shared copy — built by CI from {repo} at {sha}, {when}. "
1371
- "Live sessions and runners show only on the owner's machine.")
1372
-
1373
-
1374
- def _is_link(path: Path) -> bool:
1375
- """A symlink or a Windows junction: never followed by the export."""
1376
- if path.is_symlink():
1377
- return True
1378
- try:
1379
- return bool(os.lstat(path).st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT) # Windows only
1380
- except (AttributeError, OSError):
1381
- return False
1382
-
1383
-
1384
- def _plain_file(path: Path) -> bool:
1385
- return path.is_file() and not _is_link(path)
1386
-
1387
-
1388
- def export_site(build: Path, public: Path) -> list[str]:
1389
- """Copy the allow-list of `build` to a fresh `public` and return the published paths (sorted, `/` separated):
1390
- `index.html`, every file under `_assets/` except `*.json`, `*.body.html` and dot files, and each
1391
- `<folder>/<slug>.html` whose `<slug>.json` sits beside it and whose slug passes the slug rule. Nothing else is
1392
- published: not a `*.json` (the local checkout path and session data), not a `*.body.html`, not `.locks/`, not
1393
- `.hub-generator`, not a dot file or folder, and not a link. `public` is wiped first, but only a folder this
1394
- function made (a marker beside it says so), or an empty one; a link, a file, `build` itself and a folder that
1395
- holds `build` or sits in it are refused (ValueError)."""
1396
- build, public = Path(build), Path(public)
1397
- if public.name in ("", ".", ".."):
1398
- raise ValueError(f"the public folder needs a plain folder name, not {str(public)!r}")
1399
- if not build.is_dir() or _is_link(build):
1400
- raise ValueError(f"the build folder is not a plain folder: {build}")
1401
- b = build.resolve()
1402
- p = public.parent.resolve() / public.name
1403
- if _is_link(public) or (public.exists() and not public.is_dir()):
1404
- raise ValueError(f"the public folder is a link or a file: {public}")
1405
- if p == b or b in p.parents or p in b.parents:
1406
- raise ValueError(f"the public folder and the build folder overlap: {public}")
1407
- marker = public.parent / f".{public.name}.created-by-caddis"
1408
- if public.exists():
1409
- if not marker.exists() and any(public.iterdir()):
1410
- raise ValueError(f"{public} exists and was not made by this command; remove it or choose another folder")
1411
- shutil.rmtree(public)
1412
- public.mkdir(parents=True)
1413
- marker.write_text("made by caddis_roadmap.py render --site; wiped on each run\n", encoding="utf-8")
1414
- out: list[str] = []
1415
-
1416
- def put(src: Path, rel: str) -> None:
1417
- dst = public / rel
1418
- dst.parent.mkdir(parents=True, exist_ok=True)
1419
- shutil.copyfile(src, dst)
1420
- out.append(rel)
1421
-
1422
- if _plain_file(build / "index.html"):
1423
- put(build / "index.html", "index.html")
1424
- assets = build / "_assets"
1425
- if assets.is_dir() and not _is_link(assets):
1426
- for dirpath, dirnames, filenames in os.walk(assets, followlinks=False):
1427
- here = Path(dirpath)
1428
- dirnames[:] = sorted(d for d in dirnames if not d.startswith(".") and not _is_link(here / d))
1429
- for name in sorted(filenames):
1430
- if name.startswith(".") or name.endswith((".json", ".body.html")) or not _plain_file(here / name):
1431
- continue
1432
- put(here / name, (here / name).relative_to(build).as_posix())
1433
- for folder in sorted(build.iterdir()):
1434
- if folder.name.startswith(".") or folder.name == "_assets" or not folder.is_dir() or _is_link(folder):
1435
- continue
1436
- for page_file in sorted(folder.glob("*.html")):
1437
- slug = page_file.stem
1438
- if (page_file.suffix == ".html" and _SLUG_RE.fullmatch(slug) and _plain_file(page_file)
1439
- and _plain_file(folder / f"{slug}.json")):
1440
- put(page_file, f"{folder.name}/{page_file.name}")
1441
- return sorted(out)