wakechart 0.2.0__py3-none-any.whl
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.
- wakechart/__init__.py +2 -0
- wakechart/__main__.py +5 -0
- wakechart/cli.py +668 -0
- wakechart/prompts/AGENT.md +41 -0
- wakechart/prompts/NEW_PROJECT.md +15 -0
- wakechart/schema/roadmap.schema.json +246 -0
- wakechart/templates/project.json +64 -0
- wakechart/templates/roadmap.json +41 -0
- wakechart/viewer/template.html +858 -0
- wakechart-0.2.0.dist-info/METADATA +201 -0
- wakechart-0.2.0.dist-info/RECORD +15 -0
- wakechart-0.2.0.dist-info/WHEEL +5 -0
- wakechart-0.2.0.dist-info/entry_points.txt +2 -0
- wakechart-0.2.0.dist-info/licenses/LICENSE +21 -0
- wakechart-0.2.0.dist-info/top_level.txt +1 -0
wakechart/__init__.py
ADDED
wakechart/__main__.py
ADDED
wakechart/cli.py
ADDED
|
@@ -0,0 +1,668 @@
|
|
|
1
|
+
"""wakechart: phase roadmaps reconstructed from git history, with an interactive Gantt viewer.
|
|
2
|
+
|
|
3
|
+
The target repository is only read: `git log`, `git tag`, `git branch`, `git rev-parse`
|
|
4
|
+
and `git status`. Everything wakechart writes goes to the workspace directory.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import datetime as dt
|
|
10
|
+
import fnmatch
|
|
11
|
+
import hashlib
|
|
12
|
+
import html
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
from importlib import resources
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from . import __version__
|
|
21
|
+
|
|
22
|
+
SCHEMA_VERSION = 1
|
|
23
|
+
EXTRACT_CACHE_VERSION = 2
|
|
24
|
+
SEP = "\x1e" # between commits
|
|
25
|
+
FS = "\x1f" # between header fields
|
|
26
|
+
ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class WakeError(Exception):
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# ---------------------------------------------------------------- io helpers
|
|
34
|
+
|
|
35
|
+
def load_json(p: Path):
|
|
36
|
+
try:
|
|
37
|
+
with p.open(encoding="utf-8") as f:
|
|
38
|
+
return json.load(f)
|
|
39
|
+
except json.JSONDecodeError as e:
|
|
40
|
+
raise WakeError(f"{p.name} is not valid JSON (line {e.lineno}, column {e.colno}): {e.msg}")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def save_json(p: Path, data) -> None:
|
|
44
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
45
|
+
with p.open("w", encoding="utf-8", newline="\n") as f:
|
|
46
|
+
json.dump(data, f, ensure_ascii=False, indent=1)
|
|
47
|
+
f.write("\n")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def write_text(p: Path, text: str) -> None:
|
|
51
|
+
with p.open("w", encoding="utf-8", newline="\n") as f: # Path.write_text(newline=) needs 3.10
|
|
52
|
+
f.write(text)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def asset(*parts: str) -> str:
|
|
56
|
+
return resources.files("wakechart").joinpath(*parts).read_text(encoding="utf-8")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def git(repo: Path, *args: str, stdin: str | None = None) -> str:
|
|
60
|
+
try:
|
|
61
|
+
r = subprocess.run(["git", "-C", str(repo), "-c", "core.quotePath=false", *args],
|
|
62
|
+
input=stdin, capture_output=True, text=True,
|
|
63
|
+
encoding="utf-8", errors="replace")
|
|
64
|
+
except FileNotFoundError:
|
|
65
|
+
raise WakeError("git is not installed or not in PATH")
|
|
66
|
+
if r.returncode != 0:
|
|
67
|
+
shown = " ".join(a for a in args if SEP not in a and FS not in a)
|
|
68
|
+
raise WakeError(f"git {shown} failed in {repo}: {r.stderr.strip()}")
|
|
69
|
+
return r.stdout
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Workspace:
|
|
73
|
+
def __init__(self, root: Path):
|
|
74
|
+
self.root = root.resolve()
|
|
75
|
+
|
|
76
|
+
def project_dir(self, pid: str) -> Path:
|
|
77
|
+
if not ID_RE.match(pid):
|
|
78
|
+
raise WakeError(f"invalid project id {pid!r}: use lowercase letters, digits and dashes")
|
|
79
|
+
return self.root / "projects" / pid
|
|
80
|
+
|
|
81
|
+
def files(self, pid: str):
|
|
82
|
+
d = self.project_dir(pid)
|
|
83
|
+
return d / "project.json", d / "git.json", d / "roadmap.json"
|
|
84
|
+
|
|
85
|
+
def repo_path(self, cfg: dict) -> Path:
|
|
86
|
+
p = Path(cfg["repo"])
|
|
87
|
+
return p if p.is_absolute() else (self.root / p).resolve()
|
|
88
|
+
|
|
89
|
+
def projects(self) -> list[str]:
|
|
90
|
+
d = self.root / "projects"
|
|
91
|
+
return sorted(p.name for p in d.iterdir() if (p / "roadmap.json").exists()) if d.exists() else []
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ---------------------------------------------------------------- extract
|
|
95
|
+
|
|
96
|
+
def match_discipline_path(path: str, pattern: str) -> bool:
|
|
97
|
+
"""Like fnmatch, with a whole **/ segment matching zero or more directories."""
|
|
98
|
+
recursive = re.search(r"(?:^|(?<=/))\*\*/", pattern)
|
|
99
|
+
if recursive is None:
|
|
100
|
+
return fnmatch.fnmatchcase(path, pattern)
|
|
101
|
+
prefix, rest = pattern[:recursive.start()], pattern[recursive.end():]
|
|
102
|
+
for end in range(len(path) + 1):
|
|
103
|
+
if end and path[end - 1] != "/":
|
|
104
|
+
continue
|
|
105
|
+
if fnmatch.fnmatchcase(path[:end], prefix + "*") and match_discipline_path(path[end:], rest):
|
|
106
|
+
return True
|
|
107
|
+
return False
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def classify(path: str, rules: list[dict]) -> str:
|
|
111
|
+
path = path.casefold()
|
|
112
|
+
for rule in rules:
|
|
113
|
+
for pat in rule["paths"]:
|
|
114
|
+
if match_discipline_path(path, pat.casefold()):
|
|
115
|
+
return rule["name"]
|
|
116
|
+
return "Other"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def commit_hash(repo: Path, ref: str) -> str | None:
|
|
120
|
+
r = subprocess.run(["git", "-C", str(repo), "rev-parse", "--verify", "--quiet",
|
|
121
|
+
f"{ref}^{{commit}}"], capture_output=True, text=True)
|
|
122
|
+
return r.stdout.strip() if r.returncode == 0 else None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def resolve_ref(repo: Path, ref: str) -> str:
|
|
126
|
+
"""A ref must not look like an option; in CI checkouts only origin/<ref> may exist."""
|
|
127
|
+
if not isinstance(ref, str) or not ref or ref.startswith("-"):
|
|
128
|
+
raise WakeError(f"invalid ref {ref!r} in project.json (refs cannot start with '-')")
|
|
129
|
+
for cand in (ref, f"origin/{ref}"):
|
|
130
|
+
if commit_hash(repo, cand):
|
|
131
|
+
return cand
|
|
132
|
+
raise WakeError(f"ref {ref!r} not found in {repo} (nor origin/{ref})")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def tag_reachability(repo: Path, tags: list[dict], commit_tips: set[str], selected: set[str]) -> dict[str, str]:
|
|
136
|
+
"""Record which tags reach each selected commit in a single ancestry walk."""
|
|
137
|
+
pending: dict[str, int] = {}
|
|
138
|
+
for i, tag in enumerate(tags):
|
|
139
|
+
tip = tag["commit"]
|
|
140
|
+
if tip in commit_tips:
|
|
141
|
+
pending[tip] = pending.get(tip, 0) | (1 << i)
|
|
142
|
+
if not pending:
|
|
143
|
+
return {}
|
|
144
|
+
history = git(repo, "log", "--topo-order", "--no-patch", "--stdin", f"--format=%H{FS}%P", "--",
|
|
145
|
+
stdin="\n".join(pending) + "\n")
|
|
146
|
+
contained = {}
|
|
147
|
+
# Topological order puts every child before its parents, even with skewed dates.
|
|
148
|
+
for line in history.splitlines():
|
|
149
|
+
h, parents = line.split(FS)
|
|
150
|
+
mask = pending.pop(h)
|
|
151
|
+
if h in selected:
|
|
152
|
+
contained[h] = format(mask, "x")
|
|
153
|
+
for parent in parents.split():
|
|
154
|
+
pending[parent] = pending.get(parent, 0) | mask
|
|
155
|
+
return contained
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def extract(ws: Workspace, pid: str, out=print) -> dict:
|
|
159
|
+
pj, gj, _ = ws.files(pid)
|
|
160
|
+
if not pj.exists():
|
|
161
|
+
raise WakeError(f"{pj} does not exist (run: wakechart new {pid} <repo>)")
|
|
162
|
+
cfg = load_json(pj)
|
|
163
|
+
merges = cfg.get("merges", "skip")
|
|
164
|
+
if merges not in ("skip", "follow-parent", "classify"):
|
|
165
|
+
raise WakeError("merges in project.json must be skip, follow-parent or classify")
|
|
166
|
+
repo = ws.repo_path(cfg)
|
|
167
|
+
refs = [resolve_ref(repo, r) for r in cfg.get("refs") or ["HEAD"]]
|
|
168
|
+
rules = cfg.get("disciplines", [])
|
|
169
|
+
|
|
170
|
+
old = load_json(gj) if gj.exists() else {}
|
|
171
|
+
reusable = old.get("cache_version") == EXTRACT_CACHE_VERSION and old.get("rules") == rules
|
|
172
|
+
known = {c["hash"]: c for c in old.get("commits", [])} if reusable else {}
|
|
173
|
+
|
|
174
|
+
fmt = FS.join(["%H", "%h", "%aI", "%an", "%s", "%P", "%ae"])
|
|
175
|
+
merge_args = ["--no-merges"] if merges == "skip" else []
|
|
176
|
+
stats_args = ["--no-renames", "--numstat", "--no-color", f"--format={SEP}{fmt}"]
|
|
177
|
+
if known:
|
|
178
|
+
hashes = git(repo, "log", "--no-patch", "--format=%H", *merge_args, *refs, "--").splitlines()
|
|
179
|
+
missing = [h for h in hashes if h not in known]
|
|
180
|
+
log = ""
|
|
181
|
+
if missing:
|
|
182
|
+
log = git(repo, "log", "--no-walk=unsorted", "--stdin", *stats_args, "--",
|
|
183
|
+
stdin="\n".join(missing) + "\n")
|
|
184
|
+
else:
|
|
185
|
+
# With nothing to reuse, collect hashes and stats in one Git call.
|
|
186
|
+
hashes = []
|
|
187
|
+
log = git(repo, "log", *stats_args, *merge_args, *refs, "--")
|
|
188
|
+
|
|
189
|
+
fresh = {}
|
|
190
|
+
for chunk in log.split(SEP)[1:]:
|
|
191
|
+
head, _, body = chunk.partition("\n")
|
|
192
|
+
h, short, date, author, subject, parents, email = head.split(FS)
|
|
193
|
+
disc: dict[str, list[int]] = {}
|
|
194
|
+
files = 0
|
|
195
|
+
for line in body.strip().splitlines():
|
|
196
|
+
parts = line.split("\t")
|
|
197
|
+
if len(parts) != 3:
|
|
198
|
+
continue
|
|
199
|
+
a, d, path = parts
|
|
200
|
+
cur = disc.setdefault(classify(path, rules), [0, 0])
|
|
201
|
+
cur[0] += 0 if a == "-" else int(a)
|
|
202
|
+
cur[1] += 0 if d == "-" else int(d)
|
|
203
|
+
files += 1
|
|
204
|
+
parents = parents.split()
|
|
205
|
+
commit = {"hash": h, "short": short, "date": date, "author": author,
|
|
206
|
+
"subject": subject, "merge": len(parents) > 1,
|
|
207
|
+
"files": files, "disciplines": disc}
|
|
208
|
+
if email:
|
|
209
|
+
commit["author_id"] = hashlib.sha256(email.casefold().encode("utf-8")).hexdigest()
|
|
210
|
+
if commit["merge"]:
|
|
211
|
+
commit["first_parent"] = parents[0]
|
|
212
|
+
fresh[h] = commit
|
|
213
|
+
known.update(fresh)
|
|
214
|
+
# Reverse the current Git order so equal timestamps retain the same order
|
|
215
|
+
# whether their records came from the cache or from the numstat query.
|
|
216
|
+
commits = [known[h] for h in reversed(hashes or list(fresh))]
|
|
217
|
+
commits.sort(key=lambda c: parse(c["date"])) # stable: compares the instant, not the text
|
|
218
|
+
|
|
219
|
+
tags, commit_tips = [], set()
|
|
220
|
+
tag_fmt = FS.join(["%(refname:lstrip=2)", "%(creatordate:iso-strict)", "%(*objectname)",
|
|
221
|
+
"%(objectname)", "%(*objecttype)", "%(objecttype)"])
|
|
222
|
+
for line in git(repo, "tag", f"--format={tag_fmt}").splitlines():
|
|
223
|
+
name, date, peeled, obj, peeled_type, obj_type = line.split(FS)
|
|
224
|
+
if peeled_type == "tag":
|
|
225
|
+
# Nested tags can ultimately point at trees or blobs as well.
|
|
226
|
+
target = commit_hash(repo, f"refs/tags/{name}")
|
|
227
|
+
if target:
|
|
228
|
+
peeled, peeled_type = target, "commit"
|
|
229
|
+
if not date:
|
|
230
|
+
continue # Lightweight tags on trees or blobs have no creation date.
|
|
231
|
+
if (peeled_type or obj_type) == "commit":
|
|
232
|
+
commit_tips.add(peeled or obj)
|
|
233
|
+
tags.append({"name": name, "date": date, "commit": peeled or obj})
|
|
234
|
+
tags.sort(key=lambda t: parse(t["date"]))
|
|
235
|
+
|
|
236
|
+
branches = []
|
|
237
|
+
br_fmt = FS.join(["%(refname:short)", "%(objectname:short)", "%(committerdate:iso-strict)", "%(HEAD)"])
|
|
238
|
+
for line in git(repo, "branch", f"--format={br_fmt}").splitlines():
|
|
239
|
+
name, obj, date, cur = line.split(FS)
|
|
240
|
+
branches.append({"name": name, "commit": obj, "date": date, "current": cur == "*"})
|
|
241
|
+
|
|
242
|
+
data = {
|
|
243
|
+
"schema": SCHEMA_VERSION,
|
|
244
|
+
"cache_version": EXTRACT_CACHE_VERSION,
|
|
245
|
+
"project": pid,
|
|
246
|
+
"extracted_at": dt.datetime.now().astimezone().isoformat(timespec="seconds"),
|
|
247
|
+
"refs": refs,
|
|
248
|
+
"rules": rules,
|
|
249
|
+
"merges": merges,
|
|
250
|
+
"head": git(repo, "rev-parse", "--short", "HEAD").strip(),
|
|
251
|
+
"dirty_files": len(git(repo, "status", "--porcelain").splitlines()),
|
|
252
|
+
"branches": branches,
|
|
253
|
+
"tags": tags,
|
|
254
|
+
"tag_reachability": tag_reachability(repo, tags, commit_tips, {c["hash"] for c in commits}),
|
|
255
|
+
"commits": commits,
|
|
256
|
+
}
|
|
257
|
+
save_json(gj, data)
|
|
258
|
+
out(f"{pid}: {len(commits)} commits ({len(fresh)} new), {len(tags)} tags, {len(branches)} branches")
|
|
259
|
+
return data
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
# ---------------------------------------------------------------- build
|
|
263
|
+
|
|
264
|
+
def parse(d: str) -> dt.datetime:
|
|
265
|
+
v = dt.datetime.fromisoformat(d.replace("Z", "+00:00"))
|
|
266
|
+
return v if v.tzinfo else v.astimezone()
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
ITEM_ID_RE = re.compile(r"^T[0-9]{3,}$")
|
|
270
|
+
STATUSES = ("done", "in_progress", "committed", "provisional")
|
|
271
|
+
PRIORITIES = ("high", "medium", "low")
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _date_ok(v) -> bool:
|
|
275
|
+
try:
|
|
276
|
+
parse(v)
|
|
277
|
+
return True
|
|
278
|
+
except (ValueError, TypeError, AttributeError):
|
|
279
|
+
return False
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def validation_errors(roadmap) -> list[str]:
|
|
283
|
+
"""Every problem of a roadmap, so an agent can fix them all in one pass."""
|
|
284
|
+
if not isinstance(roadmap, dict):
|
|
285
|
+
return ["roadmap must be a JSON object"]
|
|
286
|
+
errs: list[str] = []
|
|
287
|
+
if roadmap.get("schema") != SCHEMA_VERSION:
|
|
288
|
+
errs.append(f"schema is {roadmap.get('schema')!r}, expected {SCHEMA_VERSION}")
|
|
289
|
+
if roadmap.get("session_scope", "global") not in ("global", "author"):
|
|
290
|
+
errs.append("session_scope must be global or author")
|
|
291
|
+
for key in ("project", "phases", "deliverables"):
|
|
292
|
+
if key not in roadmap:
|
|
293
|
+
errs.append(f"missing {key!r}")
|
|
294
|
+
project = roadmap.get("project")
|
|
295
|
+
if isinstance(project, dict):
|
|
296
|
+
url = project.get("repo_url")
|
|
297
|
+
if url and not re.match(r"^https?://", str(url)):
|
|
298
|
+
errs.append(f"project.repo_url must start with http:// or https:// (got {url!r})")
|
|
299
|
+
phases_l = roadmap.get("phases") if isinstance(roadmap.get("phases"), list) else []
|
|
300
|
+
items = roadmap.get("deliverables") if isinstance(roadmap.get("deliverables"), list) else []
|
|
301
|
+
phase_ids = [p.get("id") if isinstance(p, dict) else None for p in phases_l]
|
|
302
|
+
for i, pid in enumerate(phase_ids):
|
|
303
|
+
if not pid:
|
|
304
|
+
errs.append(f"phases[{i}]: missing 'id'")
|
|
305
|
+
dup_p = sorted({x for x in phase_ids if x and phase_ids.count(x) > 1})
|
|
306
|
+
if dup_p:
|
|
307
|
+
errs.append(f"duplicate phase ids: {dup_p}")
|
|
308
|
+
ids = [it.get("id") if isinstance(it, dict) else None for it in items]
|
|
309
|
+
dup = sorted({x for x in ids if x and ids.count(x) > 1})
|
|
310
|
+
if dup:
|
|
311
|
+
errs.append(f"duplicate deliverable ids: {dup}")
|
|
312
|
+
teams = {t.get("id") for t in roadmap.get("teams", []) if isinstance(t, dict)}
|
|
313
|
+
for n, it in enumerate(items):
|
|
314
|
+
if not isinstance(it, dict):
|
|
315
|
+
errs.append(f"deliverables[{n}]: must be an object")
|
|
316
|
+
continue
|
|
317
|
+
where = it.get("id") or f"deliverables[{n}]"
|
|
318
|
+
for k in ("id", "phase", "status", "title"):
|
|
319
|
+
if not it.get(k):
|
|
320
|
+
errs.append(f"{where}: missing {k!r}")
|
|
321
|
+
if it.get("id") and not ITEM_ID_RE.match(str(it["id"])):
|
|
322
|
+
errs.append(f"{where}: id must look like T001")
|
|
323
|
+
if it.get("phase") and it["phase"] not in phase_ids:
|
|
324
|
+
errs.append(f"{where}: unknown phase {it['phase']!r}")
|
|
325
|
+
if it.get("team") and teams and it["team"] not in teams:
|
|
326
|
+
errs.append(f"{where}: unknown team {it['team']!r}")
|
|
327
|
+
if it.get("status") and it["status"] not in STATUSES:
|
|
328
|
+
errs.append(f"{where}: status must be one of {sorted(STATUSES)}")
|
|
329
|
+
if it.get("priority") and it["priority"] not in PRIORITIES:
|
|
330
|
+
errs.append(f"{where}: priority must be one of {list(PRIORITIES)}")
|
|
331
|
+
for dep in it.get("depends", []):
|
|
332
|
+
if dep not in ids:
|
|
333
|
+
errs.append(f"{where}: unknown dependency {dep!r}")
|
|
334
|
+
m = it.get("match")
|
|
335
|
+
if m:
|
|
336
|
+
if m.get("subject"):
|
|
337
|
+
try:
|
|
338
|
+
re.compile(m["subject"])
|
|
339
|
+
except re.error as e:
|
|
340
|
+
errs.append(f"{where}: bad match.subject regex: {e}")
|
|
341
|
+
for k in ("from", "to"):
|
|
342
|
+
if m.get(k) and not _date_ok(m[k]):
|
|
343
|
+
errs.append(f"{where}: match.{k} is not an ISO date ({m[k]!r})")
|
|
344
|
+
est = it.get("estimate")
|
|
345
|
+
if est:
|
|
346
|
+
ok = True
|
|
347
|
+
for k in ("start", "end"):
|
|
348
|
+
if not est.get(k) or not _date_ok(est[k]):
|
|
349
|
+
errs.append(f"{where}: estimate.{k} is not an ISO date ({est.get(k)!r})")
|
|
350
|
+
ok = False
|
|
351
|
+
if ok and parse(est["start"]) > parse(est["end"]):
|
|
352
|
+
errs.append(f"{where}: estimate.start is after estimate.end")
|
|
353
|
+
graph = {it["id"]: [d for d in it.get("depends", []) if d in ids]
|
|
354
|
+
for it in items if isinstance(it, dict) and it.get("id")}
|
|
355
|
+
state: dict[str, int] = {}
|
|
356
|
+
cycles: list[str] = []
|
|
357
|
+
|
|
358
|
+
def visit(node: str, trail: list[str]) -> None:
|
|
359
|
+
state[node] = 1
|
|
360
|
+
for nxt in graph.get(node, []):
|
|
361
|
+
if state.get(nxt) == 1:
|
|
362
|
+
cycles.append(" -> ".join(trail[trail.index(nxt):] + [nxt]))
|
|
363
|
+
elif nxt not in state:
|
|
364
|
+
visit(nxt, trail + [nxt])
|
|
365
|
+
state[node] = 2
|
|
366
|
+
|
|
367
|
+
for node in graph:
|
|
368
|
+
if node not in state:
|
|
369
|
+
visit(node, [node])
|
|
370
|
+
errs.extend(f"dependency cycle: {c}" for c in cycles)
|
|
371
|
+
return errs
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def validate(roadmap) -> None:
|
|
375
|
+
errs = validation_errors(roadmap)
|
|
376
|
+
if errs:
|
|
377
|
+
raise WakeError(f"roadmap has {len(errs)} problem(s):\n - " + "\n - ".join(errs))
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def resolve(roadmap: dict, gitdata: dict, out=print) -> dict:
|
|
381
|
+
"""Attach commits to deliverables and derive dates. Mutates roadmap; returns stats."""
|
|
382
|
+
commits = gitdata.get("commits", [])
|
|
383
|
+
when = {c["hash"]: parse(c["date"]) for c in commits} # parse every date once
|
|
384
|
+
|
|
385
|
+
owner: dict[str, str] = {}
|
|
386
|
+
items = roadmap["deliverables"]
|
|
387
|
+
for it in items: # 1) explicit hashes win
|
|
388
|
+
for h in it.get("commits", []):
|
|
389
|
+
hits = [c for c in commits if c["hash"].startswith(str(h).lower())] if len(str(h)) >= 4 else []
|
|
390
|
+
if not hits:
|
|
391
|
+
out(f" warning: {it['id']} lists unknown commit {h}")
|
|
392
|
+
elif len(hits) > 1:
|
|
393
|
+
out(f" warning: {it['id']} lists ambiguous commit prefix {h} ({len(hits)} matches); use more characters")
|
|
394
|
+
else:
|
|
395
|
+
owner.setdefault(hits[0]["hash"], it["id"])
|
|
396
|
+
for it in items: # 2) match rules, in roadmap order
|
|
397
|
+
m = it.get("match")
|
|
398
|
+
if not m:
|
|
399
|
+
continue
|
|
400
|
+
rx = re.compile(m["subject"], re.I) if m.get("subject") else None
|
|
401
|
+
lo = parse(m["from"]) if m.get("from") else None
|
|
402
|
+
hi = parse(m["to"]) if m.get("to") else None
|
|
403
|
+
for c in commits:
|
|
404
|
+
if c["hash"] in owner:
|
|
405
|
+
continue
|
|
406
|
+
d = when[c["hash"]]
|
|
407
|
+
if (lo and d < lo) or (hi and d > hi) or (rx and not rx.search(c["subject"])):
|
|
408
|
+
continue
|
|
409
|
+
owner[c["hash"]] = it["id"]
|
|
410
|
+
|
|
411
|
+
if gitdata.get("merges") == "follow-parent":
|
|
412
|
+
# Walk first parents independently of author-date order. Explicit hashes
|
|
413
|
+
# and match rules already assigned above take precedence.
|
|
414
|
+
first_parent = {c["hash"]: c["first_parent"] for c in commits if c.get("first_parent")}
|
|
415
|
+
for h, parent in first_parent.items():
|
|
416
|
+
if h in owner:
|
|
417
|
+
continue
|
|
418
|
+
while parent in first_parent and parent not in owner:
|
|
419
|
+
parent = first_parent[parent]
|
|
420
|
+
if parent in owner:
|
|
421
|
+
owner[h] = owner[parent]
|
|
422
|
+
|
|
423
|
+
# Reconstructed interval of each commit: from the previous commit when the gap is short
|
|
424
|
+
# (same work session), otherwise a fixed lead-in. An approximation, not effort.
|
|
425
|
+
gap_max = dt.timedelta(minutes=roadmap.get("session_gap_minutes", 90))
|
|
426
|
+
lead = dt.timedelta(minutes=roadmap.get("lead_in_minutes", 20))
|
|
427
|
+
by_author = roadmap.get("session_scope") == "author"
|
|
428
|
+
span, last_commit = {}, {}
|
|
429
|
+
for c in commits:
|
|
430
|
+
d = when[c["hash"]]
|
|
431
|
+
key = None
|
|
432
|
+
if by_author:
|
|
433
|
+
key = c.get("author_id") or ("name", c.get("author"))
|
|
434
|
+
prev = last_commit.get(key)
|
|
435
|
+
start = prev if prev is not None and dt.timedelta(0) <= d - prev <= gap_max else d - lead
|
|
436
|
+
span[c["hash"]] = (start, d)
|
|
437
|
+
last_commit[key] = d
|
|
438
|
+
|
|
439
|
+
per_item: dict[str, list[dict]] = {}
|
|
440
|
+
for c in commits:
|
|
441
|
+
if c["hash"] in owner:
|
|
442
|
+
per_item.setdefault(owner[c["hash"]], []).append(c)
|
|
443
|
+
|
|
444
|
+
for it in items:
|
|
445
|
+
cs = per_item.get(it["id"], [])
|
|
446
|
+
it.pop("_version", None)
|
|
447
|
+
if cs and it["status"] == "done" and "tag_reachability" in gitdata:
|
|
448
|
+
reach = gitdata["tag_reachability"]
|
|
449
|
+
common = int(reach.get(cs[0]["hash"], "0"), 16)
|
|
450
|
+
for c in cs[1:]:
|
|
451
|
+
common &= int(reach.get(c["hash"], "0"), 16)
|
|
452
|
+
# Tags were indexed by date; the lowest common bit is the first release.
|
|
453
|
+
it["_version"] = gitdata["tags"][(common & -common).bit_length() - 1]["name"] if common else None
|
|
454
|
+
it["_commits"] = [{"hash": c["short"], "date": c["date"], "subject": c["subject"],
|
|
455
|
+
"author": c.get("author"), "start": span[c["hash"]][0].isoformat(),
|
|
456
|
+
"disciplines": c["disciplines"]} for c in cs]
|
|
457
|
+
if cs:
|
|
458
|
+
tot: dict[str, list[int]] = {}
|
|
459
|
+
for c in cs:
|
|
460
|
+
for k, (a, dl) in c["disciplines"].items():
|
|
461
|
+
t = tot.setdefault(k, [0, 0])
|
|
462
|
+
t[0] += a
|
|
463
|
+
t[1] += dl
|
|
464
|
+
it["_lines"] = tot
|
|
465
|
+
it["_dates"] = {"kind": "reconstructed",
|
|
466
|
+
"start": min(span[c["hash"]][0] for c in cs).isoformat(),
|
|
467
|
+
"end": max(when[c["hash"]] for c in cs).isoformat(),
|
|
468
|
+
"first_commit": cs[0]["date"], "last_commit": cs[-1]["date"]}
|
|
469
|
+
elif it.get("estimate"):
|
|
470
|
+
it["_dates"] = {"kind": "estimate", "start": it["estimate"]["start"], "end": it["estimate"]["end"]}
|
|
471
|
+
else:
|
|
472
|
+
it["_dates"] = {"kind": "unknown"}
|
|
473
|
+
|
|
474
|
+
unclassified = [{"hash": c["short"], "date": c["date"], "subject": c["subject"]}
|
|
475
|
+
for c in commits if c["hash"] not in owner]
|
|
476
|
+
return {"classified": len(owner), "total": len(commits), "unclassified": unclassified}
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
STANDALONE_HEAD = (
|
|
480
|
+
'<!doctype html>\n<html lang="{lang}">\n<head>\n<meta charset="utf-8">\n'
|
|
481
|
+
'<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">\n'
|
|
482
|
+
'<style>body{{margin:0}}[hidden]{{display:none!important}}</style>\n</head>\n<body>\n')
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def build(ws: Workspace, pid: str, out_dir: Path | None = None, index: bool = False, out=print) -> dict:
|
|
486
|
+
_, gj, rj = ws.files(pid)
|
|
487
|
+
if not rj.exists():
|
|
488
|
+
raise WakeError(f"{rj} does not exist")
|
|
489
|
+
roadmap = load_json(rj)
|
|
490
|
+
validate(roadmap)
|
|
491
|
+
gitdata = load_json(gj) if gj.exists() else {}
|
|
492
|
+
stats = resolve(roadmap, gitdata, out)
|
|
493
|
+
bundle = {
|
|
494
|
+
"wakechart": __version__,
|
|
495
|
+
"roadmap": roadmap,
|
|
496
|
+
"git": {k: gitdata.get(k) for k in ("extracted_at", "head", "dirty_files", "branches", "tags", "refs")},
|
|
497
|
+
"stats": stats,
|
|
498
|
+
"built_at": dt.datetime.now().astimezone().isoformat(timespec="seconds"),
|
|
499
|
+
}
|
|
500
|
+
payload = json.dumps(bundle, ensure_ascii=False).replace("<", "\\u003c")
|
|
501
|
+
page = asset("viewer", "template.html").replace("/*__WAKECHART_DATA__*/null", payload)
|
|
502
|
+
dest = (out_dir or ws.root / "dist").resolve()
|
|
503
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
504
|
+
lang = roadmap["project"].get("lang", "en")
|
|
505
|
+
name = "index" if index else pid
|
|
506
|
+
write_text(dest / f"{name}.html", STANDALONE_HEAD.format(lang=lang) + page + "\n</body>\n</html>\n")
|
|
507
|
+
write_text(dest / f"{pid}.fragment.html", page)
|
|
508
|
+
save_json(dest / f"{pid}.bundle.json", bundle)
|
|
509
|
+
out(f"{pid}: {stats['classified']}/{stats['total']} commits classified -> {dest / (name + '.html')}")
|
|
510
|
+
if stats["unclassified"]:
|
|
511
|
+
out(f" {len(stats['unclassified'])} unclassified commits:")
|
|
512
|
+
for u in stats["unclassified"][:20]:
|
|
513
|
+
out(f" ? {u['hash']} {u['date'][:16]} {u['subject'][:90]}")
|
|
514
|
+
if len(stats["unclassified"]) > 20:
|
|
515
|
+
out(f" ... and {len(stats['unclassified']) - 20} more (see the Notes view)")
|
|
516
|
+
return bundle
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def write_workspace_index(dest: Path, pages: list[tuple[str, dict]]) -> None:
|
|
520
|
+
lang = "es" if pages[0][1].get("lang") == "es" else "en"
|
|
521
|
+
title = "Proyectos de wakechart" if lang == "es" else "wakechart projects"
|
|
522
|
+
links = []
|
|
523
|
+
for href, project in pages:
|
|
524
|
+
name = project.get("name") or Path(href).stem
|
|
525
|
+
links.append(f'<li><a href="{html.escape(href)}">{html.escape(str(name))}</a></li>')
|
|
526
|
+
entries = "\n".join(links)
|
|
527
|
+
write_text(dest / "index.html", f"""<!doctype html>
|
|
528
|
+
<html lang="{lang}">
|
|
529
|
+
<head>
|
|
530
|
+
<meta charset="utf-8">
|
|
531
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
532
|
+
<title>{title}</title>
|
|
533
|
+
<style>
|
|
534
|
+
:root {{ color-scheme: light dark; font: 1rem system-ui, sans-serif; }}
|
|
535
|
+
main {{ max-width: 42rem; margin: 3rem auto; padding: 0 1.25rem; }}
|
|
536
|
+
ul {{ padding-inline-start: 1.25rem; }}
|
|
537
|
+
li {{ margin-block: .75rem; overflow-wrap: anywhere; }}
|
|
538
|
+
</style>
|
|
539
|
+
</head>
|
|
540
|
+
<body>
|
|
541
|
+
<main>
|
|
542
|
+
<h1>{title}</h1>
|
|
543
|
+
<ul>
|
|
544
|
+
{entries}
|
|
545
|
+
</ul>
|
|
546
|
+
</main>
|
|
547
|
+
</body>
|
|
548
|
+
</html>
|
|
549
|
+
""")
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
# ---------------------------------------------------------------- scaffolding
|
|
553
|
+
|
|
554
|
+
def new(ws: Workspace, pid: str, repo: str, name: str | None = None, lang: str = "en", out=print) -> None:
|
|
555
|
+
pj, _, rj = ws.files(pid)
|
|
556
|
+
if pj.exists():
|
|
557
|
+
raise WakeError(f"{pj} already exists")
|
|
558
|
+
repo_p = Path(repo)
|
|
559
|
+
abs_repo = repo_p if repo_p.is_absolute() else (Path.cwd() / repo_p).resolve()
|
|
560
|
+
git(abs_repo, "rev-parse", "--git-dir") # fails early if it is not a repository
|
|
561
|
+
try: # store the path relative to the workspace when possible (portable, no personal paths)
|
|
562
|
+
stored = Path(abs_repo).relative_to(ws.root).as_posix() or "."
|
|
563
|
+
except ValueError:
|
|
564
|
+
import os
|
|
565
|
+
try:
|
|
566
|
+
stored = Path(os.path.relpath(abs_repo, ws.root)).as_posix()
|
|
567
|
+
except ValueError: # different drive on Windows
|
|
568
|
+
stored = str(abs_repo)
|
|
569
|
+
cfg = json.loads(asset("templates", "project.json"))
|
|
570
|
+
cfg["id"], cfg["repo"] = pid, stored
|
|
571
|
+
save_json(pj, cfg)
|
|
572
|
+
if not rj.exists():
|
|
573
|
+
r = json.loads(asset("templates", "roadmap.json"))
|
|
574
|
+
r["project"].update({"id": pid, "name": name or pid, "lang": lang})
|
|
575
|
+
save_json(rj, r)
|
|
576
|
+
out(f"created {pj.parent}")
|
|
577
|
+
out(f"next: wakechart -w {ws.root} all {pid}")
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def init(repo: Path, lang: str, out=print) -> None:
|
|
581
|
+
"""Set up a .wakechart workspace inside the current repository (for CI / GitHub Pages)."""
|
|
582
|
+
top = Path(git(repo, "rev-parse", "--show-toplevel").strip())
|
|
583
|
+
ws = Workspace(top / ".wakechart")
|
|
584
|
+
pid = re.sub(r"[^a-z0-9-]+", "-", top.name.lower()).strip("-") or "project"
|
|
585
|
+
new(ws, pid, str(top), name=top.name, lang=lang, out=out)
|
|
586
|
+
gi = ws.root / ".gitignore"
|
|
587
|
+
if not gi.exists():
|
|
588
|
+
gi.write_text("dist/\nprojects/*/git.json\n", encoding="utf-8")
|
|
589
|
+
out(f"commit .wakechart/projects/{pid}/roadmap.json; git.json and dist/ are rebuilt")
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def prompt(kind: str) -> str:
|
|
593
|
+
return asset("prompts", "AGENT.md") if kind == "agent" else asset("prompts", "NEW_PROJECT.md")
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
# ---------------------------------------------------------------- cli
|
|
597
|
+
|
|
598
|
+
def main(argv: list[str] | None = None) -> int:
|
|
599
|
+
ap = argparse.ArgumentParser(prog="wakechart", description=__doc__.splitlines()[0])
|
|
600
|
+
ap.add_argument("--version", action="version", version=f"wakechart {__version__}")
|
|
601
|
+
ap.add_argument("-w", "--workspace", default=".", help="folder with projects/ and dist/ (default: current)")
|
|
602
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
603
|
+
|
|
604
|
+
s = sub.add_parser("new", help="create projects/<id> for a repository")
|
|
605
|
+
s.add_argument("id"); s.add_argument("repo")
|
|
606
|
+
s.add_argument("--name"); s.add_argument("--lang", default="en", choices=["en", "es"])
|
|
607
|
+
s = sub.add_parser("init", help="create a .wakechart workspace inside the current repository")
|
|
608
|
+
s.add_argument("--lang", default="en", choices=["en", "es"])
|
|
609
|
+
for c in ("extract", "build", "all"):
|
|
610
|
+
s = sub.add_parser(c, help={"extract": "read git history (read-only) into git.json",
|
|
611
|
+
"build": "roadmap.json + git.json -> dist/<id>.html",
|
|
612
|
+
"all": "extract + build"}[c])
|
|
613
|
+
s.add_argument("id", nargs="?", help="project id (default: every project in the workspace)")
|
|
614
|
+
if c != "extract":
|
|
615
|
+
s.add_argument("--out", type=Path, help="output folder (default: <workspace>/dist)")
|
|
616
|
+
s.add_argument("--index", action="store_true", help="write index.html for a project or the workspace")
|
|
617
|
+
s.add_argument("--strict", action="store_true", help="fail if any commit is unclassified")
|
|
618
|
+
s.add_argument("--json", action="store_true", help="print classification stats as JSON to stdout")
|
|
619
|
+
sub.add_parser("list", help="list projects in the workspace")
|
|
620
|
+
s = sub.add_parser("prompt", help="print the instructions for an AI agent")
|
|
621
|
+
s.add_argument("kind", nargs="?", default="agent", choices=["agent", "new"])
|
|
622
|
+
|
|
623
|
+
a = ap.parse_args(argv)
|
|
624
|
+
for stream in (sys.stdout, sys.stderr): # commit subjects may hold any character
|
|
625
|
+
if hasattr(stream, "reconfigure"):
|
|
626
|
+
stream.reconfigure(errors="replace")
|
|
627
|
+
ws = Workspace(Path(a.workspace))
|
|
628
|
+
try:
|
|
629
|
+
if a.cmd == "new":
|
|
630
|
+
new(ws, a.id, a.repo, a.name, a.lang)
|
|
631
|
+
elif a.cmd == "init":
|
|
632
|
+
init(Path.cwd(), a.lang)
|
|
633
|
+
elif a.cmd == "list":
|
|
634
|
+
for p in ws.projects():
|
|
635
|
+
print(p)
|
|
636
|
+
elif a.cmd == "prompt":
|
|
637
|
+
sys.stdout.write(prompt(a.kind))
|
|
638
|
+
else:
|
|
639
|
+
ids = [a.id] if a.id else ws.projects()
|
|
640
|
+
if not ids:
|
|
641
|
+
raise WakeError(f"no projects in {ws.root / 'projects'}")
|
|
642
|
+
if a.cmd == "extract":
|
|
643
|
+
for pid in ids:
|
|
644
|
+
extract(ws, pid)
|
|
645
|
+
else:
|
|
646
|
+
out = (lambda line: print(line, file=sys.stderr)) if a.json else print
|
|
647
|
+
dest = (a.out or ws.root / "dist").resolve()
|
|
648
|
+
multi_index = a.index and len(ids) > 1
|
|
649
|
+
pages, stats = [], {}
|
|
650
|
+
for pid in ids:
|
|
651
|
+
if a.cmd == "all":
|
|
652
|
+
extract(ws, pid, out=out)
|
|
653
|
+
# Reserve workspace index.html even if a project is named "index".
|
|
654
|
+
page = Path("index/index.html") if multi_index and pid == "index" else Path(f"{pid}.html")
|
|
655
|
+
b = build(ws, pid, dest / page.parent, a.index and not multi_index, out=out)
|
|
656
|
+
pages.append((page.as_posix(), b["roadmap"]["project"]))
|
|
657
|
+
stats[pid] = b["stats"]
|
|
658
|
+
if multi_index:
|
|
659
|
+
write_workspace_index(dest, pages)
|
|
660
|
+
out(f"workspace index -> {dest / 'index.html'}")
|
|
661
|
+
if a.json:
|
|
662
|
+
print(json.dumps({"projects": stats}))
|
|
663
|
+
if a.strict and any(s["unclassified"] for s in stats.values()):
|
|
664
|
+
raise WakeError("unclassified commits (--strict)")
|
|
665
|
+
except WakeError as e:
|
|
666
|
+
print(f"wakechart: error: {e}", file=sys.stderr)
|
|
667
|
+
return 1
|
|
668
|
+
return 0
|