agent-manifesto-kit 1.7.0 → 1.8.0

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.
@@ -0,0 +1,852 @@
1
+ #!/usr/bin/env python3
2
+ """Roadmap: a Gantt chart of the TaskPilot epics, features and tasks, one self-contained HTML page (no network).
3
+
4
+ python3 roadmap.py init [--project DIR] [--title T] [--lang en|ru] write a skeleton plan file (never overwrites)
5
+ python3 roadmap.py build [--project DIR] [--out PATH] [--now ISO] [--open]
6
+ python3 roadmap.py check [--project DIR] [--json] [--template-from PATH] exit 1 on any problem
7
+ python3 roadmap.py path [--project DIR] print the output path (relative to the project)
8
+
9
+ --project defaults to the git top level of the working directory (else the working directory itself).
10
+ The output is tracked and deterministic: "now" is the latest roadmap event (an item update, a status commit or a
11
+ commit naming an item id), so a rebuild without new events changes nothing; rows are one JSON line each for small
12
+ diffs. assets/post-commit.sh rebuilds it after commits on main that touch items or name an id.
13
+ Format, plan keys and the output contract: references/format.md.
14
+
15
+ Sources, all read-only:
16
+ - <items_dir>/*.yaml (default .taskpilot/items, working tree): type, parent_id, status, links (blocks, relates_to),
17
+ created_at, updated_at. Id prefixes (AV-12, LM-7, ...) come from the item ids.
18
+ - The git history of those files: every committed status with that version's updated_at. A segment opens on
19
+ in_progress (or at the last earlier sighting when an item jumps straight to done) and closes on done/cancelled;
20
+ a done item set back to work opens a rework bar in the same row.
21
+ - Commit messages naming item ids (all local branches; commits touching only .taskpilot/ or review/ are bookkeeping
22
+ and skipped, as are the roadmap's own "Roadmap: ..." commits): ticks under the bar, and work committed 3 h or more
23
+ after an item closed (merges aside) becomes a rework bar.
24
+ - The plan file (default docs/roadmap_plan.json, hand-edited): "title", "lang" (en | ru), "output", "items_dir",
25
+ "phases" (blocks of item ids and/or an estimated "size" in tasks, drawn as progress bars above the chart:
26
+ phase_progress), "plan" {id: {start, end} | {estimate_days} | {started} | {finished}} (the real start of work done
27
+ elsewhere, e.g. in a squashed branch; the real end of work whose item was closed later), "rework_of" {id: [ids]},
28
+ "milestones" [{date, label, since?}] (since: true adds a "only since this milestone" filter), "default_estimate_days".
29
+ TaskPilot has no date fields.
30
+
31
+ Cancelled items are left out (their other children move up to the nearest shown ancestor).
32
+ Unfinished leaves without a plan get an estimate bar: from now (or after their blockers' ends) for
33
+ default_estimate_days; in_progress ones get a 0.5-day remainder. Epics and features show a summary bracket.
34
+ """
35
+ import argparse
36
+ import contextlib
37
+ import datetime as dt
38
+ import hashlib
39
+ import io
40
+ import json
41
+ import re
42
+ import subprocess
43
+ import sys
44
+ import webbrowser
45
+ from pathlib import Path
46
+
47
+ SKILL = Path(__file__).resolve().parents[1]
48
+ TEMPLATE = SKILL / "assets" / "template.html"
49
+ SCHEMA = 1
50
+ TEMPLATE_VERSION = "1"
51
+ DEFAULT_ITEMS = ".taskpilot/items"
52
+ DEFAULT_PLAN = "docs/roadmap_plan.json"
53
+ DEFAULT_OUT = "docs/roadmap.html"
54
+ LANGS = ("en", "ru")
55
+ STRINGS = {
56
+ "en": {"loose": "No epic: standalone tasks", "page": "{title}: roadmap"},
57
+ "ru": {"loose": "Без эпика: отдельные задачи", "page": "{title}: роадмап"},
58
+ }
59
+ OPEN, CLOSED = {"in_progress"}, {"done", "cancelled"}
60
+ REWORK_GAP_H = 3 # commits this long after an item closed count as rework
61
+ CLUSTER_GAP_H = 6 # commits further apart than this start a new rework bar
62
+ STALE_DAYS = 3 # in_progress with no activity for this long is drawn as stalled
63
+
64
+
65
+ def parse_time(s):
66
+ t = dt.datetime.fromisoformat(s.replace("Z", "+00:00"))
67
+ return t if t.tzinfo else t.replace(tzinfo=dt.timezone.utc)
68
+
69
+
70
+ def iso(t):
71
+ return t.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") if t else None
72
+
73
+
74
+ def idnum(iid):
75
+ """The number of an item id: AV-12 -> 12 (ids sort by number, not text)."""
76
+ m = re.search(r"(\d+)$", iid)
77
+ return int(m.group(1)) if m else 0
78
+
79
+
80
+ def prefixes(ids):
81
+ """Sorted id prefixes: ["AV-1", "LM-3"] -> ["AV", "LM"]."""
82
+ return sorted({m.group(1) for i in ids for m in [re.match(r"^(.*)-\d+$", i)] if m})
83
+
84
+
85
+ def template_id(path=None):
86
+ """The template contract id "1-<12 hex of sha256>" (line endings normalised): all roadmaps built from the same
87
+ template share it."""
88
+ data = Path(path or TEMPLATE).read_bytes().replace(b"\r\n", b"\n")
89
+ return f"{TEMPLATE_VERSION}-{hashlib.sha256(data).hexdigest()[:12]}"
90
+
91
+
92
+ def load_yaml(text):
93
+ try:
94
+ import yaml
95
+ return yaml.safe_load(text)
96
+ except ImportError:
97
+ return mini_yaml(text)
98
+
99
+
100
+ def mini_yaml(text):
101
+ """The TaskPilot item subset: top-level scalars (plain or quoted, folded over indented lines), lists (tags:) and
102
+ one level of mappings of lists (links:)."""
103
+ def closed(v):
104
+ q, rest = v[0], v[1:]
105
+ return q in (rest.replace("''", "") if q == "'" else re.sub(r'\\.', "", rest))
106
+
107
+ def unquote(v):
108
+ v = v.strip()
109
+ if v[:1] == "'":
110
+ return v[1:-1].replace("''", "'")
111
+ return json.loads(v) if v[:1] == '"' else v
112
+
113
+ out, key, sub, lines, i = {}, None, None, text.splitlines(), 0
114
+ while i < len(lines):
115
+ line, i = lines[i], i + 1
116
+ if not line.strip():
117
+ continue
118
+ if not line[0].isspace() and not line.startswith("- "):
119
+ key, _, val = line.partition(":")
120
+ val, sub = val.strip(), None
121
+ if val[:1] in ("'", '"'):
122
+ while not closed(val) and i < len(lines):
123
+ part, i = lines[i].strip(), i + 1
124
+ val += "\n" if not part else ("" if val.endswith("\n") else " ") + part
125
+ out[key] = unquote(val) if val else None
126
+ elif line.lstrip().startswith("- "):
127
+ value = unquote(line.lstrip()[2:])
128
+ if sub:
129
+ out[key][sub].append(value)
130
+ else:
131
+ out[key] = (out[key] or []) + [value]
132
+ else:
133
+ sub = line.strip().rstrip(":")
134
+ if not isinstance(out.get(key), dict):
135
+ out[key] = {}
136
+ out[key][sub] = []
137
+ return out
138
+
139
+
140
+ # ---------------------------------------------------------------------------------------------- project paths
141
+
142
+ def find_root(project=None):
143
+ if project:
144
+ return Path(project).resolve()
145
+ try:
146
+ top = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True, check=True)
147
+ return Path(top.stdout.strip()).resolve()
148
+ except (subprocess.CalledProcessError, FileNotFoundError):
149
+ return Path.cwd().resolve()
150
+
151
+
152
+ def plan_path(root, plan_arg=None):
153
+ return Path(plan_arg).resolve() if plan_arg else root / DEFAULT_PLAN
154
+
155
+
156
+ def load_plan(path):
157
+ """The plan dict, {} when the file is missing; raises ValueError on invalid JSON."""
158
+ if not path.exists():
159
+ return {}
160
+ try:
161
+ return json.loads(path.read_text(encoding="utf-8"))
162
+ except json.JSONDecodeError as e:
163
+ raise ValueError(f"{path.name}: {e}")
164
+
165
+
166
+ def items_dir(root, plan):
167
+ return root / (plan.get("items_dir") or DEFAULT_ITEMS)
168
+
169
+
170
+ def output_path(root, plan, out_arg=None):
171
+ return Path(out_arg).resolve() if out_arg else root / (plan.get("output") or DEFAULT_OUT)
172
+
173
+
174
+ def show(root, path):
175
+ try:
176
+ return path.resolve().relative_to(root).as_posix()
177
+ except ValueError:
178
+ return str(path)
179
+
180
+
181
+ # ---------------------------------------------------------------------------------------------- git sources
182
+
183
+ def git(root, *args):
184
+ try:
185
+ return subprocess.run(["git", *args], cwd=root, capture_output=True, text=True, check=True).stdout
186
+ except (subprocess.CalledProcessError, FileNotFoundError):
187
+ return "" # not a git repository: no history, no commit ticks
188
+
189
+
190
+ def status_history(root, rel_items):
191
+ """{id: [(time, status)]} from every committed version of the item files, oldest first."""
192
+ hist, commit_t, cur = {}, None, None
193
+ pending = {}
194
+ header = f"+++ b/{rel_items}/"
195
+
196
+ def flush():
197
+ for iid, (st, upd) in pending.items():
198
+ if st:
199
+ hist.setdefault(iid, []).append((upd or commit_t, st))
200
+ pending.clear()
201
+
202
+ for line in git(root, "log", "--reverse", "-p", "-U0", "--format=@@C %aI", "--", rel_items).splitlines():
203
+ if line.startswith("@@C "):
204
+ flush()
205
+ commit_t = parse_time(line[4:])
206
+ elif line.startswith(header):
207
+ cur = Path(line).stem
208
+ pending.setdefault(cur, [None, None])
209
+ elif cur and line.startswith("+status:"):
210
+ pending[cur][0] = line.split(":", 1)[1].strip()
211
+ elif cur and line.startswith("+updated_at:"):
212
+ pending[cur][1] = parse_time(line.split(":", 1)[1].strip().strip("'\""))
213
+ flush()
214
+ for v in hist.values():
215
+ v.sort(key=lambda e: e[0])
216
+ return hist
217
+
218
+
219
+ def commit_mentions(root, prefix_list):
220
+ """{id: [(time, short hash, subject)]} for work commits naming an id with one of the prefixes."""
221
+ out = {}
222
+ if not prefix_list:
223
+ return out
224
+ pattern = re.compile(r"\b(?:" + "|".join(re.escape(p) for p in prefix_list) + r")-\d+\b")
225
+ raw = git(root, "log", "--branches", "--name-only", "--format=%x1e%h%x1f%aI%x1f%s%x1f%b%x1f")
226
+ for rec in raw.split("\x1e")[1:]:
227
+ h, t, subj, body, files = (rec.split("\x1f") + [""] * 5)[:5]
228
+ files = [f for f in files.split("\n") if f.strip()]
229
+ if files and all(f.startswith((".taskpilot/", "review/")) for f in files) or subj.startswith("Roadmap:"):
230
+ continue # bookkeeping, or the roadmap's own commits (their messages name ids as examples)
231
+ for iid in set(pattern.findall(subj + "\n" + body)):
232
+ out.setdefault(iid, []).append((parse_time(t), h, subj[:140]))
233
+ for v in out.values():
234
+ v.sort()
235
+ return out
236
+
237
+
238
+ # ---------------------------------------------------------------------------------------------- algorithms
239
+
240
+ def segments(item, hist, now):
241
+ """Actual work bars [{s, e, kind}] from the status history (or created/updated when there is none)."""
242
+ created, updated, status = parse_time(item["created_at"]), parse_time(item["updated_at"]), item["status"]
243
+ seen = [(created, None)] + list(hist)
244
+ if not hist or hist[-1][1] != status: # uncommitted change, or no history at all
245
+ seen.append((updated, status))
246
+ bars, start, closed_once, last_seen, prev = [], None, False, created, None
247
+ for t, st in seen:
248
+ if st in OPEN and start is None:
249
+ start = created if prev is None else t # first sighting already open: started when created
250
+ elif st in CLOSED:
251
+ if prev in CLOSED and start is None: # re-committed unchanged
252
+ continue
253
+ if start is None:
254
+ start = last_seen
255
+ bars.append({"s": start, "e": max(t, start), "closed": True,
256
+ "kind": ("rework" if closed_once else "work") if st == "done" else "cancelled"})
257
+ start, closed_once = None, True
258
+ elif st and st not in OPEN and start is not None: # back to backlog/ready while open
259
+ bars.append({"s": start, "e": t, "kind": "rework" if closed_once else "work"})
260
+ start = None
261
+ last_seen, prev = t, st or prev
262
+ if start is not None:
263
+ bars.append({"s": start, "e": now, "kind": "rework" if closed_once else "ongoing"})
264
+ return bars
265
+
266
+
267
+ def commit_rework(bars, ticks):
268
+ """Rework bars from work commits (merges aside) that land in a closed gap: 3 h or more after any closing bar
269
+ and outside every existing bar; commits within CLUSTER_GAP_H of each other make one bar."""
270
+ closes = sorted(b["e"] for b in bars if b.get("closed")) # done/cancelled, not a pause back to backlog
271
+ if not closes:
272
+ return []
273
+ grace = dt.timedelta(hours=REWORK_GAP_H)
274
+
275
+ def in_gap(t):
276
+ return t > closes[0] + grace and not any(b["s"] <= t <= b["e"] + grace for b in bars)
277
+
278
+ late = [c for c in ticks if in_gap(c[0]) and not c[2].startswith("Merge")]
279
+ out, cluster = [], []
280
+ for c in late + [None]:
281
+ if cluster and (c is None or c[0] - cluster[-1][0] > dt.timedelta(hours=CLUSTER_GAP_H)):
282
+ out.append({"s": cluster[0][0] - dt.timedelta(minutes=30), "e": cluster[-1][0], "kind": "rework", "from": "commits"})
283
+ cluster = []
284
+ if c:
285
+ cluster.append(c)
286
+ return out
287
+
288
+
289
+ def schedule(rows, plan, now):
290
+ """Append plan/estimate bars to unfinished leaves, blockers (their own and their ancestors') first; a parent
291
+ finishes with its last descendant. Returns the blocks cycles met (each breaks at the edge that closes it)."""
292
+ default_est = float(plan.get("default_estimate_days", 1))
293
+ blockers = {iid: [] for iid in rows}
294
+ for iid, r in rows.items():
295
+ for t in r["blocks"]:
296
+ blockers[t].append(iid)
297
+ done_end, cycles = {}, []
298
+
299
+ def ancestors_blockers(iid):
300
+ out, p = [], rows[iid]
301
+ while p:
302
+ out += blockers[p["id"]]
303
+ p = rows.get(p["parent"]) if p["parent"] else None
304
+ return out
305
+
306
+ def finish(iid, stack=()):
307
+ if iid in done_end:
308
+ return done_end[iid]
309
+ if iid in stack:
310
+ cycles.append(list(stack[stack.index(iid):]) + [iid])
311
+ return None
312
+ r, stack = rows[iid], stack + (iid,)
313
+ actual_end = max((b["e"] for b in r["bars"]), default=None)
314
+ if r["children"]:
315
+ ends = [actual_end] + [finish(c, stack) for c in r["children"]]
316
+ done_end[iid] = max([e for e in ends if e] or [r["updated"]])
317
+ return done_end[iid]
318
+ if r["status"] in CLOSED:
319
+ done_end[iid] = actual_end or r["updated"]
320
+ return done_end[iid]
321
+ p = plan.get("plan", {}).get(iid, {})
322
+ if p.get("start") and p.get("end"):
323
+ s, e, kind = parse_time(p["start"]), parse_time(p["end"]), "plan"
324
+ else:
325
+ after = [finish(b, stack) for b in ancestors_blockers(iid)]
326
+ s = max([now] + [a for a in after if a])
327
+ days = float(p.get("estimate_days", 0.5 if r["status"] in OPEN else default_est))
328
+ e, kind = s + dt.timedelta(days=days), "estimate"
329
+ r["bars"].append({"s": s, "e": e, "kind": kind})
330
+ done_end[iid] = e
331
+ return e
332
+
333
+ for iid in sorted(rows, key=idnum):
334
+ finish(iid)
335
+ return cycles
336
+
337
+
338
+ def phase_progress(rows, phases):
339
+ """Progress of the plan's phases (pre-alpha, alpha, beta) from TaskPilot leaves.
340
+
341
+ A block counts the leaves under its items (a leaf item counts itself): done ones against all; "size" (estimated
342
+ tasks) raises the total for work not yet split into items, so a block with no items is size open tasks; "done":
343
+ true marks a block finished outside TaskPilot (counted as all done).
344
+ Returns (phases with done/total per block and phase, problems: unknown or cancelled ids, ids in two blocks)."""
345
+ out, problems, seen = [], [], {}
346
+
347
+ def leaves(iid):
348
+ r = rows[iid]
349
+ return [iid] if not r["children"] else [x for c in r["children"] for x in leaves(c)]
350
+
351
+ for ph in phases:
352
+ blocks = []
353
+ for b in ph.get("blocks", []):
354
+ ids = b.get("items", [])
355
+ for i in ids:
356
+ if i not in rows:
357
+ problems.append(f"{ph['title']} / {b['title']}: {i} is unknown or cancelled")
358
+ elif i in seen:
359
+ problems.append(f"{i} is in two blocks: {seen[i]} and {b['title']}")
360
+ else:
361
+ seen[i] = b["title"]
362
+ lv = sorted({x for i in ids if i in rows for x in leaves(i)}, key=idnum)
363
+ total = max(len(lv), int(b.get("size", 0)))
364
+ done = total if b.get("done") else sum(rows[x]["status"] == "done" for x in lv)
365
+ blocks.append({"title": b["title"], "note": b.get("note", ""), "items": [i for i in ids if i in rows],
366
+ "done": done, "total": total,
367
+ "open": [] if b.get("done") else [x for x in lv if rows[x]["status"] != "done"]})
368
+ out.append({"id": ph.get("id", ""), "title": ph["title"], "goal": ph.get("goal", ""), "blocks": blocks,
369
+ "done": sum(b["done"] for b in blocks), "total": sum(b["total"] for b in blocks)})
370
+ return out, problems
371
+
372
+
373
+ def phase_of(rows, phases):
374
+ """{id: phase id} for the page's release filter: an item takes the phase of the block listing it or its nearest
375
+ listed ancestor; items under no block get none (shown under "outside the plan")."""
376
+ listed = {i: ph.get("id", "") for ph in phases for b in ph.get("blocks", []) for i in b.get("items", [])}
377
+ out = {}
378
+ for iid in rows:
379
+ p = iid
380
+ while p and p not in listed:
381
+ p = rows[p]["parent"]
382
+ if p:
383
+ out[iid] = listed[p]
384
+ return out
385
+
386
+
387
+ # ---------------------------------------------------------------------------------------------- build
388
+
389
+ def load_items(root, plan):
390
+ items = {}
391
+ for f in sorted(items_dir(root, plan).glob("*.yaml")):
392
+ d = load_yaml(f.read_text(encoding="utf-8"))
393
+ if d and d.get("id") and not d.get("deleted_at"):
394
+ items[d["id"]] = d
395
+ return items
396
+
397
+
398
+ def build(root, plan, now=None, items=None, out_path=None):
399
+ """The page data (see references/format.md) for the project at root."""
400
+ items = items if items is not None else load_items(root, plan)
401
+ prefix_list = prefixes(items)
402
+ lang = plan.get("lang") if plan.get("lang") in LANGS else "en"
403
+ title = plan.get("title") or root.name
404
+ rel_items = items_dir(root, plan).relative_to(root).as_posix()
405
+ hist, mentions = status_history(root, rel_items), commit_mentions(root, prefix_list)
406
+ if now is None:
407
+ now = max([parse_time(d["updated_at"]) for d in items.values()]
408
+ + [t for v in hist.values() for t, _ in v] + [c[0] for v in mentions.values() for c in v]
409
+ or [dt.datetime(1970, 1, 1, tzinfo=dt.timezone.utc)])
410
+ # Cancelled items are off the roadmap; their open or done children move up to the nearest shown ancestor.
411
+ shown = {i: dict(d) for i, d in items.items() if d["status"] != "cancelled"}
412
+
413
+ def shown_parent(d):
414
+ p = d.get("parent_id")
415
+ while p in items and p not in shown:
416
+ p = items[p].get("parent_id")
417
+ return p if p in shown else None
418
+
419
+ for d in shown.values():
420
+ d["parent_id"] = shown_parent(d)
421
+ items = shown
422
+ children = {}
423
+ for iid, d in items.items():
424
+ if d.get("parent_id") in items:
425
+ children.setdefault(d["parent_id"], []).append(iid)
426
+
427
+ rows = {}
428
+ for iid, d in items.items():
429
+ bars = segments(d, hist.get(iid, []), now)
430
+ pp = plan.get("plan", {}).get(iid, {})
431
+ if pp.get("started") and bars:
432
+ bars[0]["s"] = min(bars[0]["s"], parse_time(pp["started"]))
433
+ if pp.get("finished") and bars and bars[-1].get("closed"): # closed later than the work really ended
434
+ bars[-1]["e"] = max(bars[-1]["s"], min(bars[-1]["e"], parse_time(pp["finished"])))
435
+ ticks = mentions.get(iid, [])
436
+ bars += commit_rework(bars, ticks)
437
+ last_activity = max([parse_time(d["updated_at"])] + [c[0] for c in ticks])
438
+ for b in bars:
439
+ if b["kind"] == "ongoing" and now - last_activity > dt.timedelta(days=STALE_DAYS):
440
+ b["kind"], b["e"], b["idle_from"] = "stalled", now, last_activity
441
+ links = d.get("links") or {}
442
+ rows[iid] = {
443
+ "id": iid, "title": d["title"], "type": d["type"], "status": d["status"], "priority": d.get("priority"),
444
+ "parent": d.get("parent_id") if d.get("parent_id") in items else None,
445
+ "children": sorted(children.get(iid, []), key=idnum),
446
+ "created": parse_time(d["created_at"]), "updated": parse_time(d["updated_at"]),
447
+ "desc": d.get("description") or "", "tags": d.get("tags") or [],
448
+ "blocks": [x for x in links.get("blocks", []) if x in items],
449
+ "relates": [x for x in links.get("relates_to", []) if x in items],
450
+ "rework_of": [x for x in plan.get("rework_of", {}).get(iid, []) if x in items],
451
+ "bars": sorted(bars, key=lambda b: b["s"]), "ticks": ticks,
452
+ "history": [(t, s) for t, s in hist.get(iid, [])],
453
+ }
454
+
455
+ for cyc in schedule(rows, plan, now):
456
+ print("roadmap: blocks cycle, one edge ignored:", " -> ".join(cyc), file=sys.stderr)
457
+
458
+ # Summary span for parents: own bars plus every descendant's.
459
+ def span(iid):
460
+ r = rows[iid]
461
+ # A parent spans its descendants; its own bars count only when it has none (closing an epic late
462
+ # must not stretch it).
463
+ pts = [] if r["children"] else [(b["s"], b["e"], b["kind"] in ("plan", "estimate")) for b in r["bars"]]
464
+ for c in r["children"]:
465
+ pts += span(c)
466
+ if r["children"]:
467
+ actual = [p for p in pts if not p[2]]
468
+ r["summary"] = {
469
+ "s": min(p[0] for p in pts), "e": max(p[1] for p in pts),
470
+ "actual_e": max((p[1] for p in actual), default=None),
471
+ }
472
+ return pts
473
+
474
+ for iid, r in rows.items():
475
+ if not r["parent"]:
476
+ span(iid)
477
+
478
+ def first_start(iid):
479
+ r = rows[iid]
480
+ return r["summary"]["s"] if r.get("summary") else min((b["s"] for b in r["bars"]), default=r["created"])
481
+
482
+ def counts(iid):
483
+ out = {}
484
+ for c in rows[iid]["children"]:
485
+ sub = rows[c]
486
+ if not sub["children"]:
487
+ out[sub["status"]] = out.get(sub["status"], 0) + 1
488
+ for k, v in counts(c).items():
489
+ out[k] = out.get(k, 0) + v
490
+ return out
491
+
492
+ leaf_counts = {}
493
+ for r in rows.values():
494
+ if not r["children"]:
495
+ leaf_counts[r["status"]] = leaf_counts.get(r["status"], 0) + 1
496
+
497
+ order = []
498
+
499
+ def walk(iid, depth):
500
+ r = rows[iid]
501
+ r["depth"] = depth
502
+ r["counts"] = counts(iid)
503
+ order.append(iid)
504
+ for c in sorted(r["children"], key=lambda c: (first_start(c), idnum(c))):
505
+ walk(c, depth + 1)
506
+
507
+ roots = [i for i, r in rows.items() if not r["parent"]]
508
+ groups = [i for i in roots if rows[i]["children"]]
509
+ loose = [i for i in roots if not rows[i]["children"]]
510
+ for g in sorted(groups, key=lambda g: (first_start(g), idnum(g))):
511
+ walk(g, 0)
512
+ # Parentless leaves go into one pseudo-group at the end.
513
+ if loose:
514
+ pseudo = "loose"
515
+ rows[pseudo] = {"id": pseudo, "title": STRINGS[lang]["loose"], "type": "group", "status": "",
516
+ "children": loose, "bars": [], "ticks": [], "blocks": [], "relates": [], "rework_of": [],
517
+ "history": [], "parent": None, "desc": "", "tags": [], "created": None, "updated": None}
518
+ span(pseudo)
519
+ rows[pseudo]["summary"]["s"] = min(first_start(i) for i in loose)
520
+ for i in loose:
521
+ rows[i]["parent"] = pseudo
522
+ walk(pseudo, 0)
523
+
524
+ for iid, ph in phase_of(rows, plan.get("phases", [])).items():
525
+ rows[iid]["phase"] = ph
526
+ phases, problems = phase_progress(rows, plan.get("phases", []))
527
+ for msg in problems:
528
+ print("roadmap:", msg, file=sys.stderr)
529
+
530
+ def ser(v):
531
+ if isinstance(v, dt.datetime):
532
+ return iso(v)
533
+ if isinstance(v, dict):
534
+ return {k: ser(x) for k, x in v.items()}
535
+ if isinstance(v, (list, tuple)):
536
+ return [ser(x) for x in v]
537
+ return v
538
+
539
+ return {
540
+ "schema": SCHEMA,
541
+ "title": title,
542
+ "lang": lang,
543
+ "now": iso(now),
544
+ "id_prefixes": prefix_list,
545
+ "milestones": plan.get("milestones", []),
546
+ "phases": phases,
547
+ "summary": {"leaves": leaf_counts, "done": leaf_counts.get("done", 0), "total": sum(leaf_counts.values())},
548
+ "rows": [ser(rows[i]) for i in order],
549
+ }
550
+
551
+
552
+ def render(data, template=None):
553
+ """The page: the template with the meta marker, the title and the data (rows one JSON line each)."""
554
+ def dump(v):
555
+ return json.dumps(v, ensure_ascii=False, sort_keys=True).replace("<", "\\u003c")
556
+
557
+ head = {k: v for k, v in data.items() if k != "rows"}
558
+ text = dump(head)[:-1] + ',\n"rows": [\n' + ",\n".join(dump(r) for r in data["rows"]) + "\n]}"
559
+ path = Path(template or TEMPLATE)
560
+ page = STRINGS[data["lang"]]["page"].format(title=data["title"])
561
+ html = path.read_text(encoding="utf-8")
562
+ for key, value in (("/*TEMPLATE*/", template_id(path)), ("/*TITLE*/", page.replace("&", "&amp;").replace("<", "&lt;")),
563
+ ("/*LANG*/", data["lang"]), ("/*DATA*/null", text)):
564
+ html = html.replace(key, value)
565
+ return html
566
+
567
+
568
+ def build_page(root, plan, now=None):
569
+ data = build(root, plan, now)
570
+ return data, render(data)
571
+
572
+
573
+ # ---------------------------------------------------------------------------------------------- check
574
+
575
+ def _is_time(v):
576
+ try:
577
+ parse_time(v)
578
+ return isinstance(v, str)
579
+ except (ValueError, AttributeError, TypeError):
580
+ return False
581
+
582
+
583
+ def validate_plan(plan, shown_ids):
584
+ """Problems [(code, message)] in a plan dict, given the ids of the non-cancelled items."""
585
+ out = []
586
+
587
+ def bad(code, msg):
588
+ out.append((code, msg))
589
+
590
+ if not isinstance(plan, dict):
591
+ return [("plan-schema", "the plan file must hold a JSON object")]
592
+ for key in ("title", "output", "items_dir"):
593
+ if key in plan and (not isinstance(plan[key], str) or not plan[key].strip()):
594
+ bad("plan-schema", f'"{key}" must be a non-empty string')
595
+ if "lang" in plan and plan["lang"] not in LANGS:
596
+ bad("plan-schema", f'"lang" must be one of {", ".join(LANGS)}')
597
+ if "default_estimate_days" in plan:
598
+ v = plan["default_estimate_days"]
599
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or v <= 0:
600
+ bad("bad-estimate", '"default_estimate_days" must be a positive number')
601
+ phases = plan.get("phases", [])
602
+ if not isinstance(phases, list):
603
+ bad("plan-schema", '"phases" must be a list')
604
+ phases = []
605
+ seen_ph, seen_item = set(), {}
606
+ for n, ph in enumerate(phases, 1):
607
+ if not isinstance(ph, dict):
608
+ bad("plan-schema", f"phase {n} must be an object")
609
+ continue
610
+ pid, ptitle = ph.get("id"), ph.get("title")
611
+ if not isinstance(pid, str) or not pid.strip():
612
+ bad("plan-schema", f"phase {n}: \"id\" must be a non-empty string")
613
+ elif pid in seen_ph:
614
+ bad("plan-schema", f'phase id "{pid}" is used twice')
615
+ else:
616
+ seen_ph.add(pid)
617
+ if not isinstance(ptitle, str) or not ptitle.strip():
618
+ bad("plan-schema", f"phase {n}: \"title\" must be a non-empty string")
619
+ blocks = ph.get("blocks", [])
620
+ if not isinstance(blocks, list):
621
+ bad("plan-schema", f"phase {n}: \"blocks\" must be a list")
622
+ continue
623
+ for m, b in enumerate(blocks, 1):
624
+ where = f"phase {pid or n} / block {m}"
625
+ if not isinstance(b, dict):
626
+ bad("plan-schema", f"{where} must be an object")
627
+ continue
628
+ if not isinstance(b.get("title"), str) or not b["title"].strip():
629
+ bad("plan-schema", f"{where}: \"title\" must be a non-empty string")
630
+ ids = b.get("items", [])
631
+ if not isinstance(ids, list) or not all(isinstance(i, str) for i in ids):
632
+ bad("plan-schema", f"{where}: \"items\" must be a list of item ids")
633
+ ids = []
634
+ size = b.get("size", 0)
635
+ if isinstance(size, bool) or not isinstance(size, int) or size < 0:
636
+ bad("plan-schema", f"{where}: \"size\" must be a whole number of tasks, 0 or more")
637
+ if "done" in b and not isinstance(b["done"], bool):
638
+ bad("plan-schema", f"{where}: \"done\" must be true or false")
639
+ for i in ids:
640
+ if i not in shown_ids:
641
+ bad("unknown-id", f"{where}: {i} is unknown or cancelled")
642
+ elif i in seen_item:
643
+ bad("duplicate-item", f"{i} is in two blocks: {seen_item[i]} and {b.get('title')}")
644
+ else:
645
+ seen_item[i] = b.get("title")
646
+ entries = plan.get("plan", {})
647
+ if not isinstance(entries, dict):
648
+ bad("plan-schema", '"plan" must be an object {id: {...}}')
649
+ entries = {}
650
+ for iid, e in entries.items():
651
+ if iid.startswith("_"): # notes
652
+ continue
653
+ if iid not in shown_ids:
654
+ bad("unknown-id", f'"plan": {iid} is unknown or cancelled')
655
+ if not isinstance(e, dict):
656
+ bad("plan-schema", f'"plan": {iid} must be an object')
657
+ continue
658
+ for key in ("start", "end", "started", "finished"):
659
+ if key in e and not _is_time(e[key]):
660
+ bad("bad-date", f'"plan": {iid}.{key} is not an ISO date-time: {e[key]!r}')
661
+ if "estimate_days" in e:
662
+ v = e["estimate_days"]
663
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or v <= 0:
664
+ bad("bad-estimate", f'"plan": {iid}.estimate_days must be a positive number')
665
+ rework = plan.get("rework_of", {})
666
+ if not isinstance(rework, dict):
667
+ bad("plan-schema", '"rework_of" must be an object {id: [ids]}')
668
+ rework = {}
669
+ for iid, targets in rework.items():
670
+ if iid.startswith("_"): # notes
671
+ continue
672
+ if iid not in shown_ids:
673
+ bad("unknown-id", f'"rework_of": {iid} is unknown or cancelled')
674
+ if not isinstance(targets, list) or not all(isinstance(t, str) for t in targets):
675
+ bad("plan-schema", f'"rework_of": {iid} must map to a list of item ids')
676
+ continue
677
+ for t in targets:
678
+ if t not in shown_ids:
679
+ bad("unknown-id", f'"rework_of": {iid} -> {t} is unknown or cancelled')
680
+ miles = plan.get("milestones", [])
681
+ if not isinstance(miles, list):
682
+ bad("plan-schema", '"milestones" must be a list')
683
+ miles = []
684
+ for n, m in enumerate(miles, 1):
685
+ if not isinstance(m, dict) or not isinstance(m.get("label"), str) or not m["label"].strip():
686
+ bad("plan-schema", f"milestone {n} needs a \"label\"")
687
+ continue
688
+ if not _is_time(m.get("date")):
689
+ bad("bad-date", f'milestone "{m["label"]}": date is not an ISO date-time: {m.get("date")!r}')
690
+ if "since" in m and not isinstance(m["since"], bool):
691
+ bad("plan-schema", f'milestone "{m["label"]}": "since" must be true or false')
692
+ return out
693
+
694
+
695
+ def read_page(path):
696
+ """(template id, data) of a generated page, or None when it lacks the contract."""
697
+ text = Path(path).read_text(encoding="utf-8")
698
+ meta = re.search(r'<meta name="roadmap-template" content="([^"]+)">', text)
699
+ data = re.search(r'<script type="application/json" id="roadmap-data">(.*?)</script>', text, re.S)
700
+ if not meta or not data:
701
+ return None
702
+ try:
703
+ return meta.group(1), json.loads(data.group(1))
704
+ except json.JSONDecodeError:
705
+ return None
706
+
707
+
708
+ def check(root, plan_arg=None, out_arg=None, template_from=None):
709
+ """Problems [(code, message)]: plan schema, output present and fresh, template id and drift."""
710
+ problems = []
711
+ ppath = plan_path(root, plan_arg)
712
+ plan, plan_ok = {}, True
713
+ if not ppath.exists():
714
+ problems.append(("plan-missing", f"{show(root, ppath)} does not exist: run roadmap.py init"))
715
+ plan_ok = False
716
+ else:
717
+ try:
718
+ plan = load_plan(ppath)
719
+ except ValueError as e:
720
+ problems.append(("plan-json", str(e)))
721
+ plan_ok = False
722
+ items = {}
723
+ if plan_ok:
724
+ try:
725
+ items = load_items(root, plan) if isinstance(plan, dict) else {}
726
+ except Exception as e: # unreadable item files
727
+ problems.append(("plan-schema", f"cannot read the items: {e}"))
728
+ plan_ok = False
729
+ schema_problems = validate_plan(plan, {i for i, d in items.items() if d.get("status") != "cancelled"}) if plan_ok else []
730
+ problems += schema_problems
731
+ here = template_id()
732
+ if template_from is not None:
733
+ other = template_id(template_from)
734
+ if other != here:
735
+ problems.append(("template-drift", f"the local template ({here}) differs from {template_from} ({other}): "
736
+ "copy the canonical template and rebuild"))
737
+ out = output_path(root, plan if isinstance(plan, dict) else {}, out_arg)
738
+ if not out.exists():
739
+ problems.append(("output-missing", f"{show(root, out)} does not exist: run roadmap.py build"))
740
+ return problems
741
+ page = read_page(out)
742
+ if page is None:
743
+ problems.append(("output-invalid", f"{show(root, out)} is not a generated roadmap page (no template marker or data)"))
744
+ return problems
745
+ if page[0] != here:
746
+ problems.append(("template-mismatch", f"{show(root, out)} was built from template {page[0]}, the local one is "
747
+ f"{here}: rebuild"))
748
+ return problems
749
+ if plan_ok and not schema_problems:
750
+ try:
751
+ with contextlib.redirect_stderr(io.StringIO()):
752
+ _, html = build_page(root, plan)
753
+ fresh = html == out.read_text(encoding="utf-8")
754
+ except Exception as e:
755
+ problems.append(("build-failed", f"cannot rebuild to compare: {e}"))
756
+ return problems
757
+ if not fresh:
758
+ problems.append(("output-stale", f"{show(root, out)} differs from a rebuild: run roadmap.py build"))
759
+ return problems
760
+
761
+
762
+ # ---------------------------------------------------------------------------------------------- commands
763
+
764
+ def cmd_init(a):
765
+ root = find_root(a.project)
766
+ ppath = plan_path(root, a.plan)
767
+ if ppath.exists():
768
+ print(f"{show(root, ppath)} exists, left untouched")
769
+ else:
770
+ skeleton = {
771
+ "_note": "Sidecar for roadmap.py (TaskPilot has no date fields). Keys: references/format.md of the roadmap skill.",
772
+ "title": a.title or root.name, "lang": a.lang or "en", "phases": [], "plan": {}, "rework_of": {},
773
+ "milestones": [], "default_estimate_days": 1,
774
+ }
775
+ ppath.parent.mkdir(parents=True, exist_ok=True)
776
+ ppath.write_text(json.dumps(skeleton, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
777
+ print(f"wrote {show(root, ppath)}")
778
+ script = Path(__file__).resolve()
779
+ print(f"next: python3 {script} build (then check; hook: assets/post-commit.sh; register the output in Astro Preview)")
780
+ return 0
781
+
782
+
783
+ def cmd_build(a):
784
+ root = find_root(a.project)
785
+ plan = load_plan(plan_path(root, a.plan))
786
+ data, html = build_page(root, plan, parse_time(a.now) if a.now else None)
787
+ out = output_path(root, plan, a.out)
788
+ out.parent.mkdir(parents=True, exist_ok=True)
789
+ out.write_text(html, encoding="utf-8")
790
+ n = {}
791
+ for r in data["rows"]:
792
+ n[r["status"]] = n.get(r["status"], 0) + 1
793
+ print(f"{show(root, out)}: {len(data['rows'])} rows", json.dumps(n))
794
+ if a.open:
795
+ webbrowser.open(out.resolve().as_uri())
796
+ return 0
797
+
798
+
799
+ def cmd_check(a):
800
+ root = find_root(a.project)
801
+ problems = check(root, a.plan, a.out, a.template_from)
802
+ if a.json:
803
+ print(json.dumps({"ok": not problems, "problems": [{"code": c, "message": m} for c, m in problems]},
804
+ ensure_ascii=False))
805
+ elif problems:
806
+ for c, m in problems:
807
+ print(f"{c}: {m}")
808
+ else:
809
+ print("roadmap ok")
810
+ return 1 if problems else 0
811
+
812
+
813
+ def cmd_path(a):
814
+ root = find_root(a.project)
815
+ print(show(root, output_path(root, load_plan(plan_path(root, a.plan)), getattr(a, "out", None))))
816
+ return 0
817
+
818
+
819
+ def main(argv=None):
820
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
821
+ sub = ap.add_subparsers(dest="cmd", required=True)
822
+
823
+ def common(p):
824
+ p.add_argument("--project", help="project directory (default: git top level of the working directory)")
825
+ p.add_argument("--plan", help=f"plan file (default {DEFAULT_PLAN})")
826
+
827
+ p = sub.add_parser("init", help="write a skeleton plan file")
828
+ common(p)
829
+ p.add_argument("--title")
830
+ p.add_argument("--lang", choices=LANGS)
831
+ p.set_defaults(fn=cmd_init)
832
+ p = sub.add_parser("build", help="write the roadmap page")
833
+ common(p)
834
+ p.add_argument("--out", help=f"output file (default: plan 'output' or {DEFAULT_OUT})")
835
+ p.add_argument("--now", help="ISO time to treat as now (tests)")
836
+ p.add_argument("--open", action="store_true")
837
+ p.set_defaults(fn=cmd_build)
838
+ p = sub.add_parser("check", help="verify the plan, the output and the template; exit 1 on problems")
839
+ common(p)
840
+ p.add_argument("--out")
841
+ p.add_argument("--json", action="store_true")
842
+ p.add_argument("--template-from", help="canonical template to compare the local one with")
843
+ p.set_defaults(fn=cmd_check)
844
+ p = sub.add_parser("path", help="print the output path relative to the project")
845
+ common(p)
846
+ p.set_defaults(fn=cmd_path)
847
+ a = ap.parse_args(argv)
848
+ return a.fn(a)
849
+
850
+
851
+ if __name__ == "__main__":
852
+ sys.exit(main())