@antoneeo/course-creator 0.1.0-beta.2 → 0.1.0-beta.20

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,1462 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """The docs site (F-072): what the agent reads, made visible to the user.
4
+
5
+ python <skill_dir>/scripts/docs_site.py [--root <project>] [--docs-dir <name>]
6
+ [--out <folder>] [--open]
7
+
8
+ Turns a project's docs root into a static website opened from disk: what the
9
+ project is, what was done and when, what is open with its next step, and what is
10
+ known -- the same sources the agent reads to orient itself and resume work, no
11
+ more and no less. Read-only on the docs root, stdlib only, no network.
12
+
13
+ Shared spine file: byte-identical in every distribution of the family. It imports
14
+ sdlc_core and knowledge and changes neither. Listing documents, workstreams,
15
+ analyses, topics, claims, locators and the catalog goes through their readers; the
16
+ site adds what they do not offer -- a frontmatter split that keeps continuation
17
+ lines for display, the Vision's status line, and the `derived_from` ladder of
18
+ `kb_time_cycle` (a closure there), restated here with the inside-the-root rule. It is not named `site.py` -- that would shadow
19
+ Python's `site` module.
20
+
21
+ What it writes, outside the docs root: the page files (index.html, app.js,
22
+ style.css, strings.js) copied from `../docs_site/`, and `data/*.js` -- classic
23
+ scripts, because a page opened from disk cannot fetch JSON. All wording lives in
24
+ strings.js; this file emits codes, never interface text.
25
+ """
26
+ import argparse
27
+ import html
28
+ import json
29
+ import math
30
+ import os
31
+ import posixpath
32
+ import re
33
+ import shutil
34
+ import subprocess
35
+ import sys
36
+ import zipfile
37
+ import unicodedata
38
+ import urllib.parse
39
+ from datetime import datetime
40
+ from pathlib import Path
41
+
42
+ HERE = Path(__file__).resolve().parent
43
+ sys.path.insert(0, str(HERE))
44
+
45
+ import sdlc_core # noqa: E402
46
+ import knowledge # noqa: E402
47
+
48
+ PAGE_DIR = HERE.parent / "docs_site"
49
+ PAGE_FILES = ("index.html", "app.js", "style.css", "strings.js")
50
+ MARKER = ".docs-site-generated"
51
+ DEFAULT_OUT = ".docs-site"
52
+
53
+ # Status words -> group (Vision v9). A value marking a unit as available or next to
54
+ # take (READY, NEXT) is NOT a group: it falls under "other status", as written.
55
+ STATUS_GROUPS = {"BLOCKED": 1, "PLANNED": 2, "TODO": 2, "IN_PROGRESS": 3, "PROGRESS": 3,
56
+ "PAUSED": 4, "ON_HOLD": 4, "COMPLETED": 5, "DONE": 5, "CANCELLED": 6,
57
+ "ARCHIVED": 7}
58
+ OTHER_STATUS = 8
59
+
60
+ HEX12 = re.compile(r"^[0-9a-f]{12}$")
61
+ DASHES = re.compile("[‐-―−﹘﹣-]")
62
+ INVISIBLE = re.compile("[­​-‏⁠-⁤]")
63
+
64
+
65
+ class SiteError(Exception):
66
+ """A refusal: printed as one line, exit 2."""
67
+
68
+
69
+ # ------------------------------------------------------------------ reading
70
+
71
+ _UNREADABLE = []
72
+
73
+
74
+ def _text(path):
75
+ """The file's text, or None when it cannot be read (recorded, reported, exit 1)."""
76
+ try:
77
+ text = sdlc_core.read_text(path)
78
+ except OSError as exc:
79
+ _note_unreadable(path, exc)
80
+ return None
81
+ if any(Path(p) == Path(path) for p, _e in _UNREADABLE):
82
+ return None # the guard already read it as empty
83
+ return text
84
+
85
+
86
+ def _note_unreadable(path, exc):
87
+ if all(Path(p) != Path(path) for p, _e in _UNREADABLE):
88
+ _UNREADABLE.append((Path(path), exc))
89
+
90
+
91
+ class _GuardedReads:
92
+ """For one run, every read the shared readers make goes through one guard: an
93
+ unreadable file is recorded and read as empty, so the run reports it by name
94
+ and still writes the site. The shared modules' code is untouched; only the
95
+ function their callers look up is wrapped, and restored on exit."""
96
+
97
+ def __enter__(self):
98
+ self.original = sdlc_core.read_text
99
+ original = self.original
100
+
101
+ def guarded(path):
102
+ try:
103
+ return original(path)
104
+ except OSError as exc:
105
+ _note_unreadable(path, exc)
106
+ return ""
107
+ sdlc_core.read_text = guarded
108
+ return self
109
+
110
+ def __exit__(self, *exc):
111
+ sdlc_core.read_text = self.original
112
+ return False
113
+
114
+
115
+ def split_frontmatter(text):
116
+ """(meta pairs as written, body). Pairs keep continuation lines, joined."""
117
+ lines = text.split("\n")
118
+ if not lines or lines[0].strip() != "---":
119
+ return [], text
120
+ end = next((i for i in range(1, min(len(lines), 200)) if lines[i].strip() == "---"), None)
121
+ if end is None:
122
+ return [], text
123
+ pairs = []
124
+ for ln in lines[1:end]:
125
+ m = re.match(r"^([A-Za-z_][\w-]*):\s*(.*)$", ln)
126
+ if m:
127
+ pairs.append([m.group(1), m.group(2).strip()])
128
+ elif pairs and ln.strip():
129
+ item = ln.strip()
130
+ item = item[2:].strip() if item.startswith("- ") else item
131
+ pairs[-1][1] = (pairs[-1][1] + ", " + item) if pairs[-1][1] else item
132
+ return pairs, "\n".join(lines[end + 1:])
133
+
134
+
135
+ def first_heading(body):
136
+ for ln in body.split("\n"):
137
+ if ln.startswith("# "):
138
+ return ln[2:].strip()
139
+ return None
140
+
141
+
142
+ def normalize(s):
143
+ """Search folding: case, accents, dash variants, invisible characters, spaces.
144
+ app.js carries the same function; the battery runs both on the same inputs."""
145
+ s = unicodedata.normalize("NFKD", s or "")
146
+ s = "".join(c for c in s if unicodedata.category(c) != "Mn")
147
+ s = s.lower()
148
+ s = DASHES.sub("-", s)
149
+ s = INVISIBLE.sub("", s)
150
+ return re.sub(r"\s+", " ", s).strip()
151
+
152
+
153
+ def status_group(value):
154
+ return STATUS_GROUPS.get(str(value or "").strip().upper(), OTHER_STATUS)
155
+
156
+
157
+ def _v(meta, key):
158
+ return str(meta.get(key) or "").strip()
159
+
160
+
161
+ # ---------------------------------------------------------------- markdown
162
+ # A formatter with its sanitizer built in: every byte of content is escaped, and
163
+ # the only markup in the output is the markup emitted here -- headings,
164
+ # paragraphs, lists, tables, emphasis, code, blockquotes, rules and links. A link
165
+ # survives only when relative, `#` or http(s); images become their alt text.
166
+
167
+ _SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
168
+ _LINK = re.compile(r"(!?)\[([^\]]*)\]\(\s*<?([^)\s>]*)>?(?:\s+\"[^\"]*\")?\s*\)")
169
+ _CODE = re.compile(r"(`+)(.+?)\1", re.S)
170
+ _AUTO = re.compile(r"&lt;(https?://[^\s&]+)&gt;")
171
+
172
+
173
+ class _Ctx:
174
+ def __init__(self, base="", facts=None, docs=None):
175
+ self.base = base # folder of the document, docs-root relative
176
+ self.facts = facts # set of fact ids, or None without a knowledge base
177
+
178
+
179
+ def _esc(s):
180
+ return html.escape(s, quote=True)
181
+
182
+
183
+ def _href(target, ctx):
184
+ """(href, external) for a link target, or None when it must not be a link."""
185
+ if target.startswith("#"):
186
+ return _esc(target), False
187
+ if re.match(r"^https?://", target, re.I):
188
+ return _esc(target), True
189
+ if _SCHEME.match(target) or target.startswith(("/", "\\")):
190
+ return None
191
+ path, _, _frag = target.partition("#")
192
+ if not path:
193
+ return None
194
+ rel = posixpath.normpath(posixpath.join(ctx.base, urllib.parse.unquote(path)))
195
+ if rel.startswith("..") or rel.startswith("/"):
196
+ return None
197
+ return "#/doc/" + urllib.parse.quote(rel, safe="/._-~"), False
198
+
199
+
200
+ def _inline(text, ctx, links=True):
201
+ out, pos = [], 0
202
+ for m in _CODE.finditer(text):
203
+ out.append(_inline_plain(text[pos:m.start()], ctx, links))
204
+ code = m.group(2).strip() if m.group(2).strip() else m.group(2)
205
+ if ctx.facts is not None and HEX12.match(code):
206
+ if code in ctx.facts:
207
+ out.append('<a class="factid" href="#/fact/%s"><code>%s</code></a>' % (code, code))
208
+ else:
209
+ out.append('<code class="notfact">%s</code>' % code)
210
+ else:
211
+ out.append("<code>%s</code>" % _esc(code))
212
+ pos = m.end()
213
+ out.append(_inline_plain(text[pos:], ctx, links))
214
+ return "".join(out)
215
+
216
+
217
+ def _emphasis(s):
218
+ s = re.sub(r"\*\*(?=\S)(.+?)(?<=\S)\*\*", r"<strong>\1</strong>", s)
219
+ s = re.sub(r"(?<![\w])__(?=\S)(.+?)(?<=\S)__(?![\w])", r"<strong>\1</strong>", s)
220
+ s = re.sub(r"(?<![\*\w])\*(?=[^\s*])(.+?)(?<=[^\s*])\*(?![\*\w])", r"<em>\1</em>", s)
221
+ s = re.sub(r"(?<![\w])_(?=\S)(.+?)(?<=\S)_(?![\w])", r"<em>\1</em>", s)
222
+ return s
223
+
224
+
225
+ def _inline_plain(text, ctx, links):
226
+ if not text:
227
+ return ""
228
+ text = text.replace("\x00", "") # content can never address a held piece of markup
229
+ held = []
230
+
231
+ def hold(markup):
232
+ held.append(markup)
233
+ return "\x00%d\x00" % (len(held) - 1)
234
+
235
+ def link(m):
236
+ image, label, target = m.group(1), m.group(2), m.group(3)
237
+ if image:
238
+ return hold(_esc(label))
239
+ inner = _emphasis(_esc(label))
240
+ h = _href(target, ctx) if links else None
241
+ if h is None:
242
+ return hold(inner)
243
+ href, external = h
244
+ extra = ' target="_blank" rel="noopener noreferrer"' if external else ""
245
+ return hold('<a href="%s"%s>%s</a>' % (href, extra, inner))
246
+
247
+ text = _LINK.sub(link, text)
248
+ s = _emphasis(_esc(text))
249
+ s = _AUTO.sub(lambda m: '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>'
250
+ % (m.group(1), m.group(1)), s)
251
+ return re.sub("\x00(\\d+)\x00", lambda m: held[int(m.group(1))], s)
252
+
253
+
254
+ def _slugify(text):
255
+ s = re.sub(r"[^\w\- ]", "", text.lower()).strip()
256
+ return re.sub(r"\s+", "-", s)
257
+
258
+
259
+ _LIST = re.compile(r"^(\s*)([-*+]|\d+[.)])\s+(.*)$")
260
+ _HR = re.compile(r"^\s{0,3}([-*_])(\s*\1){2,}\s*$")
261
+ _HEAD = re.compile(r"^(#{1,6})\s+(.*?)\s*#*\s*$")
262
+
263
+
264
+ def _cells(line):
265
+ s = line.strip()
266
+ if s.startswith("|"):
267
+ s = s[1:]
268
+ if s.endswith("|") and not s.endswith("\\|"):
269
+ s = s[:-1]
270
+ return [c.strip().replace("\\|", "|") for c in re.split(r"(?<!\\)\|", s)]
271
+
272
+
273
+ def _is_sep(line):
274
+ s = line.strip()
275
+ return s.startswith("|") and set(s) <= set("|-: ") and "-" in s
276
+
277
+
278
+ def _starts_block(lines, i):
279
+ ln = lines[i]
280
+ return (ln.strip().startswith("```") or _HEAD.match(ln) or _HR.match(ln)
281
+ or ln.lstrip().startswith(">") or _LIST.match(ln)
282
+ or (ln.strip().startswith("|") and i + 1 < len(lines) and _is_sep(lines[i + 1])))
283
+
284
+
285
+ def _blocks(lines, ctx):
286
+ out, i = [], 0
287
+ while i < len(lines):
288
+ ln = lines[i]
289
+ if not ln.strip():
290
+ i += 1
291
+ continue
292
+ if ln.strip().startswith("```"):
293
+ fence = ln.strip()[:3]
294
+ body, i = [], i + 1
295
+ while i < len(lines) and not lines[i].strip().startswith(fence):
296
+ body.append(lines[i])
297
+ i += 1
298
+ i += 1
299
+ out.append("<pre><code>%s</code></pre>" % _esc("\n".join(body)))
300
+ continue
301
+ m = _HEAD.match(ln)
302
+ if m:
303
+ n = len(m.group(1))
304
+ title = m.group(2)
305
+ out.append('<h%d id="%s">%s</h%d>' % (n, _esc(_slugify(title)), _inline(title, ctx), n))
306
+ i += 1
307
+ continue
308
+ if _HR.match(ln):
309
+ out.append("<hr>")
310
+ i += 1
311
+ continue
312
+ if ln.lstrip().startswith(">"):
313
+ quoted = []
314
+ while i < len(lines) and lines[i].lstrip().startswith(">"):
315
+ q = lines[i].lstrip()[1:]
316
+ quoted.append(q[1:] if q.startswith(" ") else q)
317
+ i += 1
318
+ out.append("<blockquote>%s</blockquote>" % _blocks(quoted, ctx))
319
+ continue
320
+ if ln.strip().startswith("|") and i + 1 < len(lines) and _is_sep(lines[i + 1]):
321
+ head = _cells(ln)
322
+ i += 2
323
+ rows = []
324
+ while i < len(lines) and lines[i].strip().startswith("|"):
325
+ rows.append(_cells(lines[i]))
326
+ i += 1
327
+ th = "".join("<th>%s</th>" % _inline(c, ctx) for c in head)
328
+ body = "".join("<tr>%s</tr>" % "".join("<td>%s</td>" % _inline(c, ctx) for c in r)
329
+ for r in rows)
330
+ out.append("<table><thead><tr>%s</tr></thead><tbody>%s</tbody></table>" % (th, body))
331
+ continue
332
+ if _LIST.match(ln):
333
+ i = _list(lines, i, ctx, out)
334
+ continue
335
+ para = [ln.strip()]
336
+ i += 1
337
+ while i < len(lines) and lines[i].strip() and not _starts_block(lines, i):
338
+ para.append(lines[i].strip())
339
+ i += 1
340
+ out.append("<p>%s</p>" % _inline(" ".join(para), ctx))
341
+ return "".join(out)
342
+
343
+
344
+ def _list(lines, i, ctx, out):
345
+ first = _LIST.match(lines[i])
346
+ indent = len(first.group(1))
347
+ ordered = first.group(2)[0].isdigit()
348
+ items = []
349
+ while i < len(lines):
350
+ m = _LIST.match(lines[i])
351
+ if m and len(m.group(1)) == indent:
352
+ items.append([m.group(3)])
353
+ i += 1
354
+ continue
355
+ if not lines[i].strip():
356
+ nxt = i + 1
357
+ if nxt < len(lines) and lines[nxt].strip() and (
358
+ len(lines[nxt]) - len(lines[nxt].lstrip()) > indent):
359
+ items[-1].append("")
360
+ i += 1
361
+ continue
362
+ break
363
+ lead = len(lines[i]) - len(lines[i].lstrip())
364
+ if lead > indent or (not m and not _starts_block(lines, i)):
365
+ items[-1].append(lines[i][min(lead, indent + 2):] if lead > indent else lines[i].strip())
366
+ i += 1
367
+ continue
368
+ break
369
+ tag = "ol" if ordered else "ul"
370
+ parts = []
371
+ for item in items:
372
+ head, rest = item[0], item[1:]
373
+ if any(_LIST.match(r) or not r.strip() for r in rest) or any(
374
+ r.strip().startswith(("```", ">", "|")) for r in rest):
375
+ cont = [head] + rest
376
+ k = 1
377
+ while k < len(cont) and cont[k].strip() and not _LIST.match(cont[k]):
378
+ k += 1
379
+ inner = "<span>%s</span>" % _inline(" ".join(c.strip() for c in cont[:k]), ctx)
380
+ inner += _blocks(cont[k:], ctx)
381
+ else:
382
+ inner = _inline(" ".join([head] + [r.strip() for r in rest]), ctx)
383
+ parts.append("<li>%s</li>" % inner)
384
+ out.append("<%s>%s</%s>" % (tag, "".join(parts), tag))
385
+ return i
386
+
387
+
388
+ def markdown(text, base="", facts=None):
389
+ """Markdown -> sanitized HTML. `base`: the document's folder, for relative links;
390
+ `facts`: the fact ids, when a knowledge base is present (12-hex tokens link)."""
391
+ return _blocks((text or "").replace("\r\n", "\n").split("\n"), _Ctx(base, facts))
392
+
393
+
394
+ # ------------------------------------------------------------ project facts
395
+
396
+ def resolve_root(args):
397
+ """(project, docs, name) as every entry point resolves them; SiteError otherwise."""
398
+ try:
399
+ discovered, name = sdlc_core.resolve_docs_dir(args, args.root)
400
+ except sdlc_core.AmbiguousDocsRoot as exc:
401
+ raise SiteError(str(exc))
402
+ sdlc_core.set_docs_dir(name)
403
+ project = Path(args.root).resolve() if args.root else (
404
+ discovered or sdlc_core.find_project_root())
405
+ docs = project / name
406
+ if not docs.is_dir():
407
+ raise SiteError("%s not found: refusing to generate a site here. Run the skill's "
408
+ "init first, or pass --root <project_root>." % docs)
409
+ return project, docs, name
410
+
411
+
412
+ def project_lens(project, name):
413
+ if name == "mkt_docs":
414
+ return "marketing"
415
+ return sdlc_core.project_default_domain(project)
416
+
417
+
418
+ def units_page(lens):
419
+ return {"marketing": None, "course": "courses"}.get(lens, "features")
420
+
421
+
422
+ def vision_status(pairs, body):
423
+ for k, v in pairs:
424
+ if k.lower() == "status":
425
+ return v
426
+ for ln in body.split("\n")[:20]:
427
+ m = re.match(r"^\**\s*status\s*:?\s*\**\s*:?\s*(.+?)\s*$", ln, re.I)
428
+ if m:
429
+ return m.group(1).strip()
430
+ return None
431
+
432
+
433
+ def first_section(body, named=None):
434
+ """(title, body) of the first `## ` section -- or of the first one whose title
435
+ starts with `named`, when given (None when there is no such section)."""
436
+ lines = body.split("\n")
437
+ for i, ln in enumerate(lines):
438
+ if ln.startswith("## ") and (named is None or ln[3:].strip().lower().startswith(named)):
439
+ rest = []
440
+ for nxt in lines[i + 1:]:
441
+ if nxt.startswith("## "):
442
+ break
443
+ rest.append(nxt)
444
+ return ln[3:].strip(), "\n".join(rest).strip()
445
+ return None, None
446
+
447
+
448
+ NORTH_STAR = "north star"
449
+
450
+
451
+ def vision_lead(body):
452
+ """(title, body, is_north_star): the Vision's North Star wherever it sits (R25),
453
+ else its first section, which is then not called a North Star."""
454
+ title, text = first_section(body, NORTH_STAR)
455
+ if title:
456
+ return title, text, True
457
+ title, text = first_section(body)
458
+ return title, text, False
459
+
460
+
461
+ def opening_paragraph(body):
462
+ lines = body.split("\n")
463
+ start = next((i + 1 for i, ln in enumerate(lines) if ln.startswith("# ")), 0)
464
+ para = []
465
+ for ln in lines[start:]:
466
+ if not ln.strip():
467
+ if para:
468
+ break
469
+ continue
470
+ if ln.startswith("#"):
471
+ if para:
472
+ break
473
+ continue
474
+ para.append(ln)
475
+ return "\n".join(para)
476
+
477
+
478
+ # ------------------------------------------------------------ knowledge base
479
+
480
+ def resolve_derived(docs, entry, inside_only=True):
481
+ """A `derived_from` entry -> docs-root-relative path, or None.
482
+
483
+ The resolution ladder of `knowledge.kb_time_cycle` (its `_resolve` closure):
484
+ normalize, then a path with `/` must exist as written, a bare name is looked
485
+ up in notes/ then given/. The site adds one rule: the result is followed only
486
+ if it ends inside the docs root."""
487
+ entry = posixpath.normpath(str(entry).strip())
488
+ found = None
489
+ if "/" in entry:
490
+ found = entry if (docs / entry).is_file() else None
491
+ else:
492
+ for base in ("corpus/notes/", "corpus/given/"):
493
+ if (docs / (base + entry)).is_file():
494
+ found = base + entry
495
+ break
496
+ if found is None or not inside_only:
497
+ return found
498
+ try:
499
+ return (docs / found).resolve().relative_to(docs.resolve()).as_posix()
500
+ except (ValueError, OSError):
501
+ return None
502
+
503
+
504
+ def _inside(docs, rel):
505
+ return sdlc_core.confine_under(docs, rel) is not None
506
+
507
+
508
+ class Passages:
509
+ """Reads the span a locator addresses exactly as `kb_check_locator` reads it,
510
+ one text per file (cached). Returns (where, before, passage, after) or a reason."""
511
+
512
+ CONTEXT = 160
513
+
514
+ def __init__(self, docs):
515
+ self.docs = docs
516
+ self.texts = {}
517
+ self.check_cache = {}
518
+
519
+ def _t(self, path):
520
+ if path not in self.texts:
521
+ self.texts[path] = _text(path)
522
+ return self.texts[path]
523
+
524
+ def read(self, rel, loc):
525
+ target = self.docs / rel
526
+ m = knowledge.LOC_PAGE_RE.match(loc)
527
+ if m:
528
+ page, a, b = map(int, m.groups())
529
+ ext = target if target.suffix == ".txt" else target.with_suffix(".txt")
530
+ if not ext.is_file():
531
+ return {"reason": "no_file" if not target.exists() else "no_extraction"}
532
+ errs = []
533
+ knowledge.kb_check_locator(target, loc, "site", errs, self.check_cache)
534
+ if errs:
535
+ return {"reason": "no_span", "where": {"page": page}}
536
+ text = self._t(ext)
537
+ if text is None:
538
+ return {"reason": "unreadable"}
539
+ body = text.split("\f")[page - 1]
540
+ return {"where": {"page": page}, "before": body[max(0, a - self.CONTEXT):a],
541
+ "passage": body[a:b], "after": body[b:b + self.CONTEXT]}
542
+ m = knowledge.LOC_LINE_RE.match(loc)
543
+ if m:
544
+ a, b = map(int, m.groups())
545
+ if not target.is_file():
546
+ return {"reason": "no_file"}
547
+ errs = []
548
+ knowledge.kb_check_locator(target, loc, "site", errs, self.check_cache)
549
+ if errs:
550
+ return {"reason": "no_span", "where": {"lines": [a, b]}}
551
+ text = self._t(target)
552
+ if text is None:
553
+ return {"reason": "unreadable"}
554
+ lines = text.split("\n")
555
+ return {"where": {"lines": [a, b]}, "before": "\n".join(lines[max(0, a - 3):a - 1]),
556
+ "passage": "\n".join(lines[a - 1:b]), "after": "\n".join(lines[b:b + 2])}
557
+ if knowledge.LOC_CELL_RE.match(loc):
558
+ return {"reason": "cell", "where": {"cell": loc}}
559
+ return {"reason": "unknown_form"}
560
+
561
+
562
+ def _kind(row):
563
+ parts = (row.get("state") or "").split(None, 1)
564
+ return (parts[0] if parts else "OK").upper(), (parts[1] if len(parts) > 1 else "")
565
+
566
+
567
+ def _ids(rest):
568
+ return [t.strip() for t in rest.split(",") if t.strip()]
569
+
570
+
571
+ def chain_ends(start, by_id):
572
+ """Every branch of a replacement chain, walked to its end: the current fact,
573
+ or a stated stop -- a loop or a missing id."""
574
+ ends = []
575
+
576
+ def walk(fid, seen):
577
+ if fid not in by_id:
578
+ end = {"stop": "missing", "id": fid}
579
+ elif fid in seen:
580
+ end = {"stop": "loop", "id": fid}
581
+ else:
582
+ kind, rest = _kind(by_id[fid])
583
+ if kind == "SUPERSEDED" and _ids(rest):
584
+ for nxt in _ids(rest):
585
+ walk(nxt, seen | {fid})
586
+ return
587
+ end = {"id": fid}
588
+ if end not in ends:
589
+ ends.append(end)
590
+
591
+ kind, rest = _kind(by_id[start])
592
+ for nxt in _ids(rest):
593
+ walk(nxt, frozenset({start}))
594
+ return ends
595
+
596
+
597
+ class Grounds:
598
+ """What an inferred fact rests on: the anti-echo walk of the probe, following a
599
+ path only when it stays inside the docs root."""
600
+
601
+ def __init__(self, docs):
602
+ self.docs = docs
603
+ self.meta = {}
604
+
605
+ def _meta(self, rel):
606
+ if rel not in self.meta:
607
+ t = _text(self.docs / rel)
608
+ self.meta[rel] = sdlc_core.load_frontmatter(t.splitlines()) if t else {}
609
+ return self.meta[rel]
610
+
611
+ def leaves(self, rel, seen=frozenset()):
612
+ if rel is None:
613
+ return [{"kind": "untraceable"}]
614
+ if rel in seen:
615
+ return [{"kind": "untraceable", "path": rel}]
616
+ seen = seen | {rel}
617
+ if rel.startswith("corpus/given/"):
618
+ # F-084: a document this project SENT is our own declaration, not
619
+ # ground for a fact about the product.
620
+ side = self._meta(rel + ".meta.md")
621
+ if _v(side, "provenance").upper() == "DECLARED":
622
+ return [{"kind": "declared", "path": rel}]
623
+ return [{"kind": "document", "path": rel}]
624
+ if not _inside(self.docs, rel) or not (self.docs / rel).is_file():
625
+ return [{"kind": "untraceable", "path": rel}]
626
+ meta = self._meta(rel)
627
+ origin = _v(meta, "origin").lower()
628
+ kind = {"elicited": "statement", "ruling": "decision", "imported": "kb"}.get(origin)
629
+ if kind:
630
+ return [{"kind": kind, "path": rel}]
631
+ entries = knowledge._kb_df_entries(meta.get("derived_from"))
632
+ if not entries:
633
+ return [{"kind": "decision" if meta.get("basis") else "untraceable", "path": rel}]
634
+ out = []
635
+ for e in entries:
636
+ target = resolve_derived(self.docs, e)
637
+ got = self.leaves(target, seen) if target else [{"kind": "untraceable", "path": rel,
638
+ "entry": str(e)}]
639
+ for g in got:
640
+ if g not in out:
641
+ out.append(g)
642
+ return out
643
+
644
+
645
+ def ground_class(leaves):
646
+ kinds = {g["kind"] for g in leaves}
647
+ if "statement" in kinds:
648
+ return "statement"
649
+ if "untraceable" in kinds:
650
+ return "untraceable"
651
+ if "declared" in kinds:
652
+ return "declared"
653
+ if "kb" in kinds:
654
+ return "imported"
655
+ return "documents"
656
+
657
+
658
+ def topic_area(slug, live, all_nodes):
659
+ """The root reached by first parents; a cycle, a missing or a merged parent -> None."""
660
+ seen, cur = set(), slug
661
+ while True:
662
+ if cur in seen or cur not in live:
663
+ return None
664
+ seen.add(cur)
665
+ parents = knowledge._as_list(live[cur]["meta"].get("parents"))
666
+ if not parents:
667
+ return cur
668
+ cur = parents[0]
669
+
670
+
671
+ def build_kb(docs):
672
+ all_nodes = knowledge.kb_load_topics(docs)
673
+ if not all_nodes:
674
+ return None
675
+ tomb = {s for s, n in all_nodes.items() if _v(n["meta"], "status") == "SUPERSEDED"}
676
+ live = {s: n for s, n in all_nodes.items() if s not in tomb}
677
+ topics, facts, rows_of = {}, {}, {}
678
+ by_id = {}
679
+ for slug in sorted(all_nodes):
680
+ node = all_nodes[slug]
681
+ t = _text(docs / node["file"]) or ""
682
+ _pairs, body = split_frontmatter(t)
683
+ rows, _errs = knowledge.kb_parse_claims(t)
684
+ for r in rows:
685
+ r["_topic"] = slug
686
+ r["id"] = r["id"] or "%s:%d" % (slug, r["_line"])
687
+ by_id.setdefault(r["id"], r)
688
+ rows_of[slug] = rows
689
+ meta = node["meta"]
690
+ if slug in tomb:
691
+ topics[slug] = {"name": slug, "merged_into": _v(meta, "redirect_to")}
692
+ continue
693
+ topics[slug] = {
694
+ "name": first_heading(body) or slug,
695
+ "description": _v(meta, "description"),
696
+ "aka": knowledge._as_list(meta.get("synonyms")),
697
+ "gaps": knowledge._as_list(meta.get("gaps")),
698
+ "related": knowledge._as_list(meta.get("related")),
699
+ "parents": knowledge._as_list(meta.get("parents")),
700
+ "file": node["file"],
701
+ "facts": [r["id"] for r in rows],
702
+ "count": len(rows),
703
+ }
704
+ for slug, t in topics.items():
705
+ if "merged_into" in t:
706
+ continue
707
+ t["area"] = topic_area(slug, live, all_nodes)
708
+ t["children"] = sorted(s for s, o in topics.items()
709
+ if "merged_into" not in o and slug in o["parents"])
710
+ passages, grounds = Passages(docs), Grounds(docs)
711
+ sources_of_topic = {}
712
+ for slug in sorted(rows_of):
713
+ for r in rows_of[slug]:
714
+ kind, rest = _kind(r)
715
+ f = {"text": r["claim"], "valid": r["valid"], "qty": r["qty"], "about": r["about"],
716
+ "origin": (r["prov"] or "").strip().lower(), "topic": slug,
717
+ "state": {"SUPERSEDED": "superseded", "CONTESTED": "contested",
718
+ "DIVERGES": "diverges"}.get(kind, "ok")}
719
+ if kind == "SUPERSEDED":
720
+ f["successors"] = _ids(rest)
721
+ f["chain_ends"] = chain_ends(r["id"], by_id)
722
+ if kind == "CONTESTED":
723
+ f["with"] = _ids(rest)
724
+ if kind == "DIVERGES":
725
+ f["diverges_from"] = _ids(rest)
726
+ srcs = []
727
+ for src in r["source"].split(";"):
728
+ src = src.strip()
729
+ if not src:
730
+ continue
731
+ rel, _, loc = src.rpartition("#") if "#" in src else (src, "", "")
732
+ rel = rel.strip()
733
+ entry = {"path": rel}
734
+ if not _inside(docs, rel):
735
+ entry["reason"] = "outside"
736
+ elif rel.startswith("corpus/given/"):
737
+ entry["source"] = rel[len("corpus/given/"):]
738
+ sources_of_topic.setdefault(entry["source"], set()).add(slug)
739
+ entry.update(passages.read(rel, loc.strip()) if loc else {"reason": "no_locator"})
740
+ elif loc:
741
+ entry.update(passages.read(rel, loc.strip()))
742
+ if loc:
743
+ entry["loc"] = loc.strip()
744
+ srcs.append(entry)
745
+ f["sources"] = srcs
746
+ if f["origin"] == "derived":
747
+ leaves = []
748
+ for rel in knowledge.kb_claim_sources(r):
749
+ rel = rel.strip()
750
+ for g in grounds.leaves(rel if _inside(docs, rel) else None):
751
+ if g not in leaves:
752
+ leaves.append(g)
753
+ f["grounds"] = leaves
754
+ f["ground_class"] = ground_class(leaves)
755
+ f["statement"] = f["origin"] == "elicited" or f.get("ground_class") == "statement"
756
+ facts.setdefault(r["id"], f)
757
+ sources = build_sources(docs, rows_of)
758
+ order = sorted(s for s in topics if "merged_into" not in topics[s])
759
+ return {"topics": topics, "facts": facts, "sources": sources, "order": order,
760
+ "map": build_map(topics, order, facts, sources)}
761
+
762
+
763
+ def build_sources(docs, rows_of):
764
+ given = docs / "corpus" / "given"
765
+ out = {}
766
+ if not given.is_dir():
767
+ return out
768
+ cited = {}
769
+ for slug, rows in rows_of.items():
770
+ for r in rows:
771
+ for rel in sorted(set(knowledge.kb_claim_sources(r))):
772
+ if rel.startswith("corpus/given/"):
773
+ name = rel[len("corpus/given/"):]
774
+ c = cited.setdefault(name, [0, set()])
775
+ c[0] += 1
776
+ c[1].add(slug)
777
+ for mp in sorted(given.glob("*.meta.md")):
778
+ name = mp.name[:-len(".meta.md")]
779
+ t = _text(mp) or ""
780
+ meta = sdlc_core.load_frontmatter(t.splitlines()) or {}
781
+ if knowledge.kb_is_tombstone(meta):
782
+ continue # withdrawn: no bytes to show; corpus/INDEX.md keeps the row
783
+ through = _v(meta, "extracted_through")
784
+ parsed = knowledge.kb_parse_extracted_through(through) if through else None
785
+ if not through:
786
+ read = {"kind": "unrecorded"}
787
+ elif parsed is None:
788
+ read = {"kind": "unreadable", "raw": through}
789
+ elif parsed[0] == "complete":
790
+ read = {"kind": "complete"}
791
+ else:
792
+ total = knowledge.kb_extraction_extent(given / name, parsed[0])
793
+ read = {"kind": "page" if parsed[0] == "p" else "line", "n": parsed[1]}
794
+ if total:
795
+ read["of"] = total
796
+ c = cited.get(name, [0, set()])
797
+ entry = {"kind": Path(name).suffix.lstrip(".").lower(), "date": _v(meta, "date"),
798
+ "read": read, "facts": c[0], "topics": sorted(c[1]),
799
+ "sidecar": "corpus/given/" + mp.name}
800
+ sup = knowledge.kb_unquote(meta.get("supersedes"))
801
+ if sup:
802
+ entry["newer_of"] = sup
803
+ out[name] = entry
804
+ for name, e in list(out.items()):
805
+ older = e.get("newer_of")
806
+ if older in out:
807
+ out[older]["older_of"] = name
808
+ return out
809
+
810
+
811
+ def build_map(topics, order, facts, sources):
812
+ """The three views' geometry, computed here: deterministic, laid out, framed.
813
+
814
+ Topics: a radial tree by area (first parents), unplaced topics on an outer
815
+ ring. Everything: each topic's facts on a small spiral around it, each source
816
+ document at the centre of the topics that use it."""
817
+ pos = {}
818
+ areas = [s for s in order if topics[s].get("area") == s]
819
+ kids = {s: [] for s in order}
820
+ for s in order:
821
+ area = topics[s].get("area")
822
+ if area and area != s:
823
+ parent = topics[s]["parents"][0]
824
+ if parent in kids:
825
+ kids[parent].append(s)
826
+ weight = {}
827
+
828
+ def w(s):
829
+ if s not in weight:
830
+ weight[s] = max(1, sum(w(k) for k in kids[s]))
831
+ return weight[s]
832
+
833
+ total = sum(w(a) for a in areas) or 1
834
+ ring = 260.0
835
+
836
+ def place(s, depth, a0, a1):
837
+ ang = (a0 + a1) / 2
838
+ r = depth * ring
839
+ pos[s] = (round(r * math.cos(ang), 1), round(r * math.sin(ang), 1))
840
+ cur = a0
841
+ for k in kids[s]:
842
+ span = (a1 - a0) * w(k) / w(s)
843
+ place(k, depth + 1, cur, cur + span)
844
+ cur += span
845
+
846
+ cur = 0.0
847
+ for a in areas:
848
+ span = 2 * math.pi * w(a) / total
849
+ place(a, 1 if len(areas) > 1 else 0, cur, cur + span)
850
+ cur += span
851
+ rest = [s for s in order if s not in pos]
852
+ if rest:
853
+ depth = max([0] + [math.hypot(*p) for p in pos.values()]) + ring
854
+ for i, s in enumerate(rest):
855
+ ang = 2 * math.pi * i / len(rest)
856
+ pos[s] = (round(depth * math.cos(ang), 1), round(depth * math.sin(ang), 1))
857
+ nodes = [{"id": s, "x": pos[s][0], "y": pos[s][1], "area": topics[s].get("area"),
858
+ "count": topics[s]["count"]} for s in order]
859
+ edges = []
860
+ for s in order:
861
+ for p in topics[s]["parents"]:
862
+ if p in pos:
863
+ edges.append({"a": s, "b": p, "kind": "part_of"})
864
+ for r in topics[s]["related"]:
865
+ if r in pos:
866
+ edges.append({"a": s, "b": r, "kind": "related"})
867
+ shared = {}
868
+ for name in sorted(sources):
869
+ ts = [t for t in sources[name]["topics"] if t in pos]
870
+ for i, a in enumerate(ts):
871
+ for b in ts[i + 1:]:
872
+ shared[(a, b)] = shared.get((a, b), 0) + 1
873
+ for (a, b), n in sorted(shared.items()):
874
+ edges.append({"a": a, "b": b, "kind": "shared", "n": n, "computed": True})
875
+ # everything: facts spiral around their topic; sources at their topics' centre
876
+ every = []
877
+ golden = math.pi * (3 - math.sqrt(5))
878
+ for s in order:
879
+ cx, cy = pos[s]
880
+ for i, fid in enumerate(topics[s]["facts"]):
881
+ r = 18 + 7 * math.sqrt(i + 1)
882
+ every.append({"id": fid, "kind": "fact", "x": round(cx + r * math.cos(i * golden), 1),
883
+ "y": round(cy + r * math.sin(i * golden), 1)})
884
+ for i, name in enumerate(sorted(sources)):
885
+ ts = [pos[t] for t in sources[name]["topics"] if t in pos]
886
+ if ts:
887
+ x, y = sum(p[0] for p in ts) / len(ts), sum(p[1] for p in ts) / len(ts)
888
+ else:
889
+ x, y = 0.0, 0.0
890
+ r = 40 + 4 * (i % 7)
891
+ every.append({"id": name, "kind": "source", "x": round(x + r * math.cos(i * golden), 1),
892
+ "y": round(y + r * math.sin(i * golden), 1)})
893
+ return {"nodes": nodes, "edges": edges, "every": every}
894
+
895
+
896
+ # ------------------------------------------------------------ the documents
897
+
898
+ def doc_page(docs, rel, facts):
899
+ t = _text(docs / rel)
900
+ if t is None:
901
+ return None
902
+ pairs, body = split_frontmatter(t)
903
+ base = posixpath.dirname(rel)
904
+ page = {"title": first_heading(body) or posixpath.basename(rel),
905
+ "meta": pairs, "html": markdown(body, base, facts),
906
+ "_n": normalize(" ".join([first_heading(body) or "", rel,
907
+ " ".join(v for _k, v in pairs), body]))}
908
+ if re.match(r"^solutions/ANALYSIS_[^/]+\.md$", rel):
909
+ page["chain"] = {"steps": analysis_chain(body), "_stem": posixpath.basename(rel)[9:-3]}
910
+ return page
911
+
912
+
913
+ # The chain an analysis is read through (R24): why (Vision), what (use cases, flows and
914
+ # interfaces, risks), how (solution study, design and tests), then the merge brief and
915
+ # E2E script, then the Diary. Headings are the validator's own wherever it names them --
916
+ # ANALYSIS_SECTIONS, SECURITY_SECTION and every lens's risk section in DOMAINS -- and the
917
+ # template's otherwise; a heading matches by prefix, case-insensitively.
918
+ CHAIN_STEPS = ("vision", "use_cases", "flows", "risks", "solution", "design",
919
+ "merge_tests", "diary")
920
+
921
+
922
+ def _chain_headings():
923
+ named = {pair[0]: pair for pair in sdlc_core.ANALYSIS_SECTIONS}
924
+ risks = list(sdlc_core.SECURITY_SECTION)
925
+ for lens in sdlc_core.DOMAINS.values():
926
+ risks += [h for h in lens["risk_section"] if h not in risks]
927
+ return (("vision", named["## Objective"] + named["## Feature Vision"] + ("## Vision Alignment",)),
928
+ ("use_cases", ("## Use Cases",)),
929
+ ("flows", ("## Functional Spec", "## Interface Contract")),
930
+ ("risks", tuple(risks)),
931
+ ("solution", ("## Capability Ledger",) + named["## Impact"]),
932
+ ("design", named["## Action Plan"] + named["## Test Strategy"]),
933
+ ("diary", named["## Diary"]))
934
+
935
+
936
+ def chain_step(heading):
937
+ """The chain step a level-2 heading belongs to, or None (it stays where it is)."""
938
+ h = heading.strip().lower()
939
+ for step, aliases in _chain_headings():
940
+ if any(h.startswith(a.lower()) for a in aliases):
941
+ return step
942
+ return None
943
+
944
+
945
+ def analysis_chain(body):
946
+ """[{step, sections: [{title, id}]}] in chain order; sections as written, in
947
+ document order. The id is the one the formatter gives the heading."""
948
+ found = {s: [] for s in CHAIN_STEPS}
949
+ fenced = False
950
+ for ln in body.split("\n"):
951
+ if ln.strip().startswith("```"):
952
+ fenced = not fenced
953
+ continue
954
+ if fenced or not ln.startswith("## "):
955
+ continue
956
+ step = chain_step(ln)
957
+ m = _HEAD.match(ln)
958
+ if step and m:
959
+ found[step].append({"title": m.group(2), "id": _slugify(m.group(2))})
960
+ return [{"step": s, "sections": found[s]} for s in CHAIN_STEPS]
961
+
962
+
963
+ def companion_paths(stem):
964
+ """The documents named after a unit's stem: (key, docs-relative path). One list,
965
+ read by the chain page and by the work and feature lists."""
966
+ return (("merge", "solutions/MERGE_REVIEW_%s.md" % stem),
967
+ ("e2e", "solutions/E2E_TEST_%s.md" % stem),
968
+ ("request", "audit/requests/REQUEST_%s.md" % stem))
969
+
970
+
971
+ def verify_links(docs, stem):
972
+ """The merge brief and E2E script of a unit, where they exist: who merges reads the
973
+ first while the work is open, who tests reads the second after it closed."""
974
+ return {key: path for key, path in companion_paths(stem)
975
+ if key in ("merge", "e2e") and (docs / path).is_file()}
976
+
977
+
978
+ def link_companions(docs, pages):
979
+ """Each analysis's merge brief, E2E script and request record, where they exist,
980
+ and the project's North Star (R25)."""
981
+ north_star = None
982
+ vp = "vision/project_vision.md"
983
+ if vp in pages:
984
+ title, _body, is_ns = vision_lead(split_frontmatter(_text(docs / vp) or "")[1])
985
+ if is_ns:
986
+ north_star = {"path": vp, "id": _slugify(title)}
987
+ for rel, page in pages.items():
988
+ chain = page.get("chain")
989
+ if not chain:
990
+ continue
991
+ stem = chain.pop("_stem")
992
+ chain["north_star"] = north_star
993
+ chain["companions"] = {key: path if path in pages else None
994
+ for key, path in companion_paths(stem)}
995
+
996
+
997
+ def orientation_sources(docs):
998
+ """{role: docs-relative path} of what the agent reads at session start, from
999
+ `sdlc_core.orient_docs` -- the one list. Roles are matched by position: a fifth
1000
+ source added there needs a role here, and the battery goes red until it has one."""
1001
+ roles = ("readme", "manifest", "router", "register")
1002
+ out = {}
1003
+ for role, (_label, rel) in zip(roles, sdlc_core.orient_docs()):
1004
+ rel = rel.split("/", 1)[1]
1005
+ out[role] = rel if (docs / rel).is_file() else None
1006
+ return out
1007
+
1008
+
1009
+ def audit_pages(docs):
1010
+ """Documents the agent reads that have a page but no place in the tree (R23)."""
1011
+ out = []
1012
+ oriented = [r for r in orientation_sources(docs).values() if r]
1013
+ for rel in oriented + ["topics/INDEX.md", "audit/project_notes.md", "audit/reviews/REVIEW_LOG.md"]:
1014
+ if (docs / rel).is_file():
1015
+ out.append(rel)
1016
+ aud = docs / "audit"
1017
+ if aud.is_dir():
1018
+ out += ["audit/" + p.name for p in sorted(aud.glob("HANDOFF_*.md"))]
1019
+ req = aud / "requests"
1020
+ if req.is_dir():
1021
+ out += ["audit/requests/" + p.name for p in sorted(req.glob("*.md"))]
1022
+ return out
1023
+
1024
+
1025
+ def build(project, docs, name):
1026
+ lens = project_lens(project, name)
1027
+ kb = build_kb(docs)
1028
+ fact_ids = set(kb["facts"]) if kb else None
1029
+ catalog = knowledge.memory_records(docs)
1030
+ paths = [r[0] for r in catalog]
1031
+ pages = {}
1032
+ for rel in sorted(set(paths + audit_pages(docs))):
1033
+ page = doc_page(docs, rel, fact_ids)
1034
+ if page is not None:
1035
+ pages[rel] = page
1036
+ link_companions(docs, pages)
1037
+ search = [{"k": "doc", "path": rel, "title": p["title"], "n": p.pop("_n")}
1038
+ for rel, p in sorted(pages.items())]
1039
+
1040
+ tree = {}
1041
+ for rel in paths:
1042
+ if rel in pages:
1043
+ tree.setdefault(posixpath.dirname(rel), []).append(
1044
+ {"path": rel, "title": pages[rel]["title"]})
1045
+ tree = [{"folder": f, "docs": sorted(d, key=lambda e: e["path"])} for f, d in sorted(tree.items())]
1046
+
1047
+ work = build_work(project, docs, fact_ids)
1048
+ units = build_units(project, lens) if units_page(lens) else None
1049
+ rules = build_rules(docs, pages)
1050
+ home = build_home(docs, pages, work, kb, fact_ids)
1051
+ head = sdlc_core.git_head(project) if sdlc_core.git_available(project) else ""
1052
+ changed = sdlc_core.git_changed_since(project, "HEAD", name) if head else None
1053
+ core = {
1054
+ "meta": {"generated": datetime.now().strftime("%Y-%m-%d %H:%M"),
1055
+ "git": bool(head), "commit": head, "changed": len(changed or []),
1056
+ "docs_dir": name, "lens": lens, "units_page": units_page(lens),
1057
+ "has_kb": bool(kb), "has_sources": bool(kb and kb["sources"])},
1058
+ "home": home, "work": work, "units": units, "rules": rules,
1059
+ "guides": build_guides(docs, pages), "tree": tree,
1060
+ "chronology": home["lately_all"], "search": search,
1061
+ }
1062
+ home.pop("lately_all")
1063
+ if kb:
1064
+ kb["search"] = ([{"k": "topic", "id": s, "title": kb["topics"][s]["name"],
1065
+ "n": normalize(" ".join([s, kb["topics"][s]["name"],
1066
+ " ".join(kb["topics"][s]["aka"]),
1067
+ kb["topics"][s]["description"]]))}
1068
+ for s in kb["order"]]
1069
+ + [{"k": "fact", "id": fid, "title": f["text"], "n": normalize(f["text"]),
1070
+ "statement": f["statement"]}
1071
+ for fid, f in kb["facts"].items()])
1072
+ return core, pages, kb
1073
+
1074
+
1075
+ def build_work(project, docs, facts):
1076
+ cards = []
1077
+ for p, meta in sdlc_core.list_workstreams(project):
1078
+ card = {"name": _v(meta, "workstream"), "group": status_group(meta.get("status")),
1079
+ "path": p.relative_to(docs).as_posix()}
1080
+ for key in ("status", "level", "since", "updated", "branch", "next"):
1081
+ if _v(meta, key):
1082
+ card[key] = _v(meta, key)
1083
+ card.update(verify_links(docs, p.stem[len("HANDOFF_"):]))
1084
+ cards.append(card)
1085
+ cards.sort(key=lambda c: c["name"].lower())
1086
+ cards.sort(key=lambda c: c.get("updated", ""), reverse=True)
1087
+ cards.sort(key=lambda c: (c["group"], not c.get("updated")))
1088
+ notes = None
1089
+ np = docs / "audit" / sdlc_core.PROJECT_NOTES
1090
+ if np.is_file():
1091
+ t = _text(np)
1092
+ if t is not None:
1093
+ notes = {"path": "audit/" + sdlc_core.PROJECT_NOTES, "html": markdown(t, "audit", facts)}
1094
+ register = "audit/handoff.md" if (docs / "audit" / "handoff.md").is_file() else None
1095
+ return {"cards": cards, "notes": notes, "register": register}
1096
+
1097
+
1098
+ def build_units(project, lens):
1099
+ default = sdlc_core.project_default_domain(project)
1100
+ units = []
1101
+ for p, meta, text in sdlc_core.list_analyses(project):
1102
+ _pairs, body = split_frontmatter(text)
1103
+ u = {"name": first_heading(body) or p.stem, "group": status_group(meta.get("status")),
1104
+ "lens": sdlc_core.resolve_domain(meta, default)[0],
1105
+ "path": "solutions/" + p.name}
1106
+ for key, field in (("id", "id"), ("status", "status"), ("level", "level"),
1107
+ ("start", "start_date"), ("end", "end_date")):
1108
+ if _v(meta, field):
1109
+ u[key] = _v(meta, field)
1110
+ if "id" not in u and _v(meta, "feature"):
1111
+ u["id"] = _v(meta, "feature")
1112
+ u.update(verify_links(sdlc_core.ai_path(project), p.stem[len("ANALYSIS_"):]))
1113
+ units.append(u)
1114
+ # newest first by declared start date (owner, 2026-10-19); undated last, by id
1115
+ units.sort(key=lambda u: (u.get("id", ""), u["path"]))
1116
+ units.sort(key=lambda u: u.get("start", ""), reverse=True)
1117
+ units.sort(key=lambda u: not u.get("start"))
1118
+ return units
1119
+
1120
+
1121
+ def build_rules(docs, pages):
1122
+ def entries(folder, pattern):
1123
+ d = docs / folder
1124
+ return sorted(folder + "/" + p.name for p in d.glob(pattern)
1125
+ if p.name != "INDEX.md") if d.is_dir() else []
1126
+
1127
+ def item(rel):
1128
+ meta = dict((k.lower(), v) for k, v in pages[rel]["meta"])
1129
+ return {"path": rel, "title": pages[rel]["title"], "when": meta.get("description", "")}
1130
+
1131
+ vision = [item(r) for r in entries("vision", "*.md") if r in pages]
1132
+ for v in vision:
1133
+ t = _text(docs / v["path"]) or ""
1134
+ pairs, body = split_frontmatter(t)
1135
+ v["status"] = vision_status(pairs, body) or ""
1136
+ decisions = [item(r) for r in entries("architecture", "*.md") if r in pages]
1137
+ return {"vision": vision, "decisions": decisions,
1138
+ "manifest": "INDEX.md" if "INDEX.md" in pages else None}
1139
+
1140
+
1141
+ def build_guides(docs, pages):
1142
+ """The guides page (R26): the router, then operative guides (when to read each, status
1143
+ as declared), then code-comprehension guides (`source_kind: code`)."""
1144
+ ref = docs / "reference"
1145
+ operative, comprehension = [], []
1146
+ for p in sorted(ref.glob("GUIDE_*.md")) if ref.is_dir() else []:
1147
+ rel = "reference/" + p.name
1148
+ if rel not in pages:
1149
+ continue
1150
+ meta = dict((k.lower(), v) for k, v in pages[rel]["meta"])
1151
+ g = {"path": rel, "title": pages[rel]["title"], "when": meta.get("description", ""),
1152
+ "status": meta.get("status", "")}
1153
+ (comprehension if meta.get("source_kind", "").strip().lower() == "code"
1154
+ else operative).append(g)
1155
+ return {"router": "reference/INDEX.md" if "reference/INDEX.md" in pages else None,
1156
+ "operative": operative, "comprehension": comprehension}
1157
+
1158
+
1159
+ def build_home(docs, pages, work, kb, facts):
1160
+ readme = pages.get("README.md")
1161
+ title, intro = None, ""
1162
+ t = _text(docs / "README.md") if readme else None
1163
+ if t is not None:
1164
+ _pairs, body = split_frontmatter(t)
1165
+ title = first_heading(body)
1166
+ intro = markdown(opening_paragraph(body), "", facts)
1167
+ vision = None
1168
+ vp = "vision/project_vision.md"
1169
+ if (docs / vp).is_file():
1170
+ vt = _text(docs / vp)
1171
+ if vt is not None:
1172
+ pairs, body = split_frontmatter(vt)
1173
+ st, sb, is_ns = vision_lead(body)
1174
+ vision = {"path": vp, "status": vision_status(pairs, body), "north_star": is_ns,
1175
+ "section_title": st, "section_html": markdown(sb or "", "vision", facts)}
1176
+ events = chronology(docs, pages)
1177
+ known = []
1178
+ if kb:
1179
+ for s in kb["order"]:
1180
+ if kb["topics"][s].get("area") == s:
1181
+ known.append({"slug": s, "name": kb["topics"][s]["name"],
1182
+ "topics": [o for o in kb["order"]
1183
+ if o != s and kb["topics"][o].get("area") == s]})
1184
+ links = {role: (rel if rel in pages else None)
1185
+ for role, rel in orientation_sources(docs).items()}
1186
+ links["work"] = "work"
1187
+ if work["notes"]:
1188
+ links["notes"] = work["notes"]["path"]
1189
+ if kb:
1190
+ links["topics"] = "map"
1191
+ return {"title": title or "", "intro_html": intro, "vision": vision, "links": links,
1192
+ "open": [{k: c[k] for k in ("name", "status", "next", "path") if k in c}
1193
+ for c in work["cards"]],
1194
+ "lately": events[:10], "lately_all": events, "known": known}
1195
+
1196
+
1197
+ SPIKE_OUTCOME = ("## Answer / Outcome",)
1198
+
1199
+
1200
+ def chronology(docs, pages):
1201
+ """Dated events the documents declare, most recent first: {date, kind, label,
1202
+ path}. Which lines are events is F-073's rule (R22), read with the validator's
1203
+ own readers -- `section_lines` + `entry_openers` for Diary entries, spike
1204
+ outcomes and project notes, `request_entries`, `parse_review_log`, `adr_date`,
1205
+ `knowledge.frontmatter_date` -- so the page and `validate` cannot disagree. No
1206
+ analysis start or end date, no state, nothing from git. `path` is the page the
1207
+ event opens, or None when the site has no page for it."""
1208
+ events = []
1209
+
1210
+ def add(date, kind, label, rel, source=None):
1211
+ e = {"date": date, "kind": kind, "label": label,
1212
+ "path": rel if rel in pages else None}
1213
+ if source:
1214
+ e["source"] = source # opens the source's own page (#/source/<name>)
1215
+ events.append(e)
1216
+
1217
+ def openers(rel, kind, aliases=None):
1218
+ text = _text(docs / rel) if (docs / rel).is_file() else None
1219
+ if text is None:
1220
+ return
1221
+ if aliases is not None:
1222
+ section = sdlc_core.section_lines(text, aliases)
1223
+ if section is None:
1224
+ return
1225
+ text = section[1]
1226
+ for date, label, _ in sdlc_core.entry_openers(text):
1227
+ add(date, kind, label, rel)
1228
+
1229
+ def title_of(rel, text):
1230
+ return pages[rel]["title"] if rel in pages else (
1231
+ first_heading(split_frontmatter(text)[1]) or posixpath.basename(rel))
1232
+
1233
+ for p in sorted(docs.glob("solutions/ANALYSIS_*.md")):
1234
+ text = _text(p)
1235
+ # a shadow mirror is not an analysis to `validate` (list_analyses): not here either
1236
+ if text is not None and not sdlc_core.is_shadow(p, (text.splitlines() or [""])[0]):
1237
+ # a Diary label ("closed", "Approved (R5)") names no unit: prefix the id, so
1238
+ # the event reads on its own in the chronology (field case 2026-10-19)
1239
+ uid = dict((k.lower(), v) for k, v in split_frontmatter(text)[0]).get("id", "").strip()
1240
+ start = len(events)
1241
+ openers("solutions/" + p.name, "diary", sdlc_core.DIARY_SECTION)
1242
+ if uid:
1243
+ for e in events[start:]:
1244
+ e["label"] = "%s — %s" % (uid, e["label"])
1245
+ # spike outcomes: SPIKE_* in the code/kb/course lenses, RESEARCH_* in marketing
1246
+ for rel in sorted(["solutions/" + p.name for p in docs.glob("solutions/SPIKE_*.md")]
1247
+ + ["spikes/" + p.name for p in docs.glob("spikes/RESEARCH_*.md")]):
1248
+ openers(rel, "spike", SPIKE_OUTCOME)
1249
+ openers("audit/" + sdlc_core.PROJECT_NOTES, "project_note")
1250
+ for p in sorted(docs.glob("audit/requests/REQUEST_*.md")):
1251
+ rel = "audit/requests/" + p.name
1252
+ text = _text(p)
1253
+ for rid, date, label, _ in sdlc_core.request_entries(text or "")[0]:
1254
+ add(date, "request", "%s — %s" % (rid, label), rel)
1255
+ rel = "audit/reviews/REVIEW_LOG.md"
1256
+ text = _text(docs / rel) if (docs / rel).is_file() else None
1257
+ if text is not None:
1258
+ for row in sdlc_core.parse_review_log(text)[0]:
1259
+ # F-085: a `post-merge` row is the owner's defect report, not a review
1260
+ kind = "defect" if row["tier"].lower().startswith("post-merge") else "review"
1261
+ add(row["date"], kind, "%s — %s: %s" % (
1262
+ row["doc_key"], row["tier"], row["verdict"]), rel)
1263
+ for p in sorted(docs.glob("architecture/ADR_*.md")):
1264
+ rel = "architecture/" + p.name
1265
+ text = _text(p)
1266
+ date = sdlc_core.adr_date(p.name, text or "")
1267
+ if date:
1268
+ add(date, "decision", title_of(rel, text or ""), rel)
1269
+ for folder, kind, suffix in (("corpus/notes", "note", ".md"),
1270
+ ("corpus/given", "source", ".meta.md")):
1271
+ for p in sorted(docs.glob(folder + "/*" + suffix)):
1272
+ rel = folder + "/" + p.name
1273
+ text = _text(p)
1274
+ if text is None:
1275
+ continue
1276
+ fm = sdlc_core.load_frontmatter(text.splitlines())
1277
+ date = knowledge.frontmatter_date(fm)
1278
+ if not date:
1279
+ continue
1280
+ if kind == "source" and knowledge.kb_is_tombstone(fm):
1281
+ continue
1282
+ if kind == "source":
1283
+ name = p.name[:-len(suffix)]
1284
+ # F-084: a DECLARED sidecar's date is the day it was SENT
1285
+ sent = _v(fm, "provenance").upper() == "DECLARED"
1286
+ add(date, "sent" if sent else kind, name, rel, source=name)
1287
+ else:
1288
+ add(date, kind, title_of(rel, text), rel)
1289
+ # Most recent first. Within one day a document's later entry is the more recent
1290
+ # one, so the reading order is reversed too. Entries carry no time of day, so
1291
+ # between DIFFERENT documents on one day the order is fixed but not a time order:
1292
+ # the kinds come in the reverse of the reading order above.
1293
+ ranked = sorted(enumerate(events), key=lambda ne: (ne[1]["date"], ne[0]), reverse=True)
1294
+ return [e for _, e in ranked]
1295
+
1296
+
1297
+ # ----------------------------------------------------------------- writing
1298
+
1299
+ def _js(var, obj):
1300
+ s = json.dumps(obj, ensure_ascii=True, separators=(",", ":"))
1301
+ return "window.%s = %s;\n" % (var, s.replace("<", "\\u003c"))
1302
+
1303
+
1304
+ def check_out(out, docs):
1305
+ out = out.resolve()
1306
+ d = docs.resolve()
1307
+ if out == d or d in out.parents:
1308
+ raise SiteError("--out %s is inside the docs root %s: the site is written outside it."
1309
+ % (out, d))
1310
+ if out.exists() and not out.is_dir():
1311
+ raise SiteError("--out %s exists and is not a folder." % out)
1312
+ if out.is_dir() and any(out.iterdir()) and not (out / MARKER).is_file():
1313
+ raise SiteError("--out %s is not empty and was not written by this generator: "
1314
+ "refusing to write over it." % out)
1315
+ return out
1316
+
1317
+
1318
+ def check_zip(target, docs, out):
1319
+ """Where `--zip` may write: a .zip file outside the docs root and outside the site."""
1320
+ target = target.resolve()
1321
+ if target.suffix.lower() != ".zip":
1322
+ raise SiteError("--zip %s must name a .zip file." % target)
1323
+ for folder, what in ((docs.resolve(), "the docs root"), (out.resolve(), "the site folder")):
1324
+ if target == folder or folder in target.parents:
1325
+ raise SiteError("--zip %s is inside %s %s." % (target, what, folder))
1326
+ if target.exists() and not target.is_file():
1327
+ raise SiteError("--zip %s exists and is not a file." % target)
1328
+ return target
1329
+
1330
+
1331
+ def write_zip(out, target):
1332
+ """The site as one file to share. Entry names always use '/': an archive whose names
1333
+ carry '\\' (Windows PowerShell 5.1 Compress-Archive) unpacks on Linux and macOS as
1334
+ files named `data\\core.js`, and the page then finds no data (field case 2026-10-19)."""
1335
+ with zipfile.ZipFile(str(target), "w", zipfile.ZIP_DEFLATED) as z:
1336
+ for p in sorted(out.rglob("*")):
1337
+ if p.is_file() and p.name != MARKER:
1338
+ z.write(str(p), p.relative_to(out).as_posix())
1339
+
1340
+
1341
+ def write_site(out, core, pages, kb):
1342
+ out.mkdir(parents=True, exist_ok=True)
1343
+ for rel in PAGE_FILES + ("data",):
1344
+ p = out / rel
1345
+ if p.is_dir():
1346
+ shutil.rmtree(p)
1347
+ elif p.exists():
1348
+ p.unlink()
1349
+ (out / MARKER).write_text("Written by docs_site.py; regenerated on every run.\n",
1350
+ encoding="utf-8", newline="\n")
1351
+ for name in PAGE_FILES:
1352
+ shutil.copyfile(PAGE_DIR / name, out / name)
1353
+ data = out / "data"
1354
+ data.mkdir()
1355
+ (data / "core.js").write_text(_js("DOCS_SITE_CORE", core), encoding="utf-8", newline="\n")
1356
+ (data / "docs.js").write_text(_js("DOCS_SITE_DOCS", pages), encoding="utf-8", newline="\n")
1357
+ if kb:
1358
+ (data / "kb.js").write_text(_js("DOCS_SITE_KB", kb), encoding="utf-8", newline="\n")
1359
+
1360
+
1361
+ def git_ignored(project, out):
1362
+ if not sdlc_core.git_available(project):
1363
+ return None
1364
+ try:
1365
+ out.relative_to(project.resolve())
1366
+ except ValueError:
1367
+ return None # outside the repository: nothing to commit
1368
+ try:
1369
+ r = subprocess.run(["git", "check-ignore", "-q", str(out)], cwd=str(project),
1370
+ capture_output=True, text=True, timeout=10)
1371
+ return {0: True, 1: False}.get(r.returncode)
1372
+ except Exception:
1373
+ return None
1374
+
1375
+
1376
+ def ensure_ignored(project, out):
1377
+ """Add the site folder to the project's .gitignore when git does not ignore it, so the
1378
+ site's copy of the documents is not committed. An entry already in the file is never
1379
+ rewritten (git may ignore it elsewhere, or the user negated it on purpose). Returns the
1380
+ line added, or None; False when the folder stays not ignored."""
1381
+ if git_ignored(project, out) is not False:
1382
+ return None
1383
+ rel = out.resolve().relative_to(project.resolve()).as_posix()
1384
+ entry = rel + "/"
1385
+ gi = project / ".gitignore"
1386
+ try:
1387
+ raw = gi.read_bytes() if gi.is_file() else b""
1388
+ text = raw.decode("utf-8")
1389
+ if {rel, entry, "/" + rel, "/" + entry} & {l.strip() for l in text.splitlines()}:
1390
+ return False
1391
+ nl = "\r\n" if "\r\n" in text else "\n"
1392
+ sep = nl if text and not text.endswith(("\n", "\r")) else ""
1393
+ with open(str(gi), "ab") as f:
1394
+ f.write((sep + entry + nl).encode("utf-8"))
1395
+ except (OSError, UnicodeDecodeError):
1396
+ return False
1397
+ return entry
1398
+
1399
+
1400
+ def _shown(path, docs):
1401
+ try:
1402
+ return Path(path).relative_to(docs).as_posix()
1403
+ except ValueError:
1404
+ return str(path)
1405
+
1406
+
1407
+ def main(argv=None):
1408
+ ap = argparse.ArgumentParser(
1409
+ prog="docs_site.py",
1410
+ description="Generate a static, read-only site of what the agent reads in this project.")
1411
+ ap.add_argument("--root", help="project root (default: discovered from the current folder)")
1412
+ ap.add_argument("--docs-dir", dest="docs_dir", help="docs root name (ai_docs or mkt_docs)")
1413
+ ap.add_argument("--out", help="output folder (default: <project>/%s)" % DEFAULT_OUT)
1414
+ ap.add_argument("--open", action="store_true", help="open the site in the browser")
1415
+ ap.add_argument("--zip", metavar="FILE",
1416
+ help="also write the site as one .zip to share; it opens on any system")
1417
+ args = ap.parse_args(argv)
1418
+ del _UNREADABLE[:]
1419
+ try:
1420
+ project, docs, name = resolve_root(args)
1421
+ out = check_out(Path(args.out) if args.out else project / DEFAULT_OUT, docs)
1422
+ target = check_zip(Path(args.zip), docs, out) if args.zip else None
1423
+ except SiteError as exc:
1424
+ print("[ERROR] %s" % exc)
1425
+ return 2
1426
+ if not PAGE_DIR.is_dir():
1427
+ print("[ERROR] the page files are missing: %s (reinstall the skill)" % PAGE_DIR)
1428
+ return 2
1429
+ try:
1430
+ with _GuardedReads():
1431
+ core, pages, kb = build(project, docs, name)
1432
+ except OSError as exc:
1433
+ # a reader that bypasses read_text (raw bytes) met an unreadable file
1434
+ _note_unreadable(getattr(exc, "filename", None) or "?", exc)
1435
+ for path, err in _UNREADABLE:
1436
+ print("[ERROR] unreadable: %s (%s)" % (_shown(path, docs), err))
1437
+ print("[ERROR] the site was not written: fix the file's permissions and run again.")
1438
+ return 1
1439
+ write_site(out, core, pages, kb)
1440
+ print("[ok] docs site written: %s (%d documents%s, from %s)" % (
1441
+ out / "index.html", len(pages),
1442
+ ", %d topics, %d facts" % (len(kb["order"]), len(kb["facts"])) if kb else "", docs))
1443
+ for path, exc in _UNREADABLE:
1444
+ print("[ERROR] unreadable: %s (%s)" % (_shown(path, docs), exc))
1445
+ added = ensure_ignored(project, out)
1446
+ if added:
1447
+ print("[ok] added %s to %s so the site's copy of your documents is not committed."
1448
+ % (added, project / ".gitignore"))
1449
+ elif added is False:
1450
+ print("[note] %s is not git-ignored: add it to .gitignore so the site's copy of "
1451
+ "your documents is not committed." % out)
1452
+ if target:
1453
+ write_zip(out, target)
1454
+ print("[ok] docs site zipped: %s (unzip it and open index.html)" % target)
1455
+ if args.open:
1456
+ import webbrowser
1457
+ webbrowser.open((out / "index.html").as_uri())
1458
+ return 1 if _UNREADABLE else 0
1459
+
1460
+
1461
+ if __name__ == "__main__":
1462
+ sys.exit(main())