sdtk-spec-kit 0.3.16 → 0.3.17

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,865 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ SDTK-SPEC Atlas Builder -- generic local-project edition.
4
+
5
+ Scans markdown files under configured scan roots, builds a document index
6
+ and graph, and generates a static local viewer.
7
+
8
+ Usage:
9
+ python build_atlas.py --project-root <path> --output-dir <path>
10
+ [--scan-root <path> ...] [--exclude <frag> ...]
11
+ [--verbose]
12
+
13
+ Outputs (written to <output-dir>/):
14
+ ATLAS_STATE.json - incremental scan/build state
15
+ SDTK_DOC_INDEX.json - full document index
16
+ SDTK_DOC_GRAPH.json - nodes + typed edges
17
+ SDTK_DOC_ATLAS_SUMMARY.md - human-readable summary
18
+ viewer.html - static local viewer (data embedded)
19
+ vendor/mermaid.min.js - vendored viewer asset
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import hashlib
26
+ import json
27
+ import re
28
+ import shutil
29
+ import sys
30
+ from datetime import datetime, timezone
31
+ from pathlib import Path
32
+ from typing import Any
33
+
34
+ ATLAS_STATE_VERSION = 6
35
+ MERMAID_VENDOR_PATH = Path(__file__).parent / "vendor" / "mermaid.min.js"
36
+ MERMAID_ASSET_NAME = "mermaid.min.js"
37
+ _VIEWER_TEMPLATE_PATH = Path(__file__).parent / "doc_atlas_viewer_template.html"
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # Default consumer project exclude fragments
41
+ # ---------------------------------------------------------------------------
42
+ DEFAULT_EXCLUDE_FRAGS: list[str] = [
43
+ ".git",
44
+ ".sdtk/atlas",
45
+ "node_modules",
46
+ ".venv",
47
+ "venv",
48
+ "dist",
49
+ "build",
50
+ "coverage",
51
+ ".next",
52
+ ".turbo",
53
+ ".cache",
54
+ "__pycache__",
55
+ ]
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Reference patterns
59
+ # ---------------------------------------------------------------------------
60
+ RE_BK = re.compile(r"\bBK-(\d{3,})\b")
61
+ RE_KNOWLEDGE_ID = re.compile(r"\b(KD|KT|KP|KA|KR|KRB|KF)-(\d{4})\b")
62
+ RE_REPO_PATH = re.compile(
63
+ r"(?:^|[\s`(\[])([a-zA-Z0-9_\-]+(?:/[a-zA-Z0-9_\-. ]+)+\."
64
+ r"(?:md|py|ps1|json|yaml|yml|html|txt))"
65
+ )
66
+ RE_WIKI_LINK = re.compile(r"\[\[([^\]]+)\]\]")
67
+ RE_MARKDOWN_LINK = re.compile(r"(?<!!)\[[^\]]+\]\(([^)]+)\)")
68
+ RE_SKILL_REF = re.compile(r"\b(sdtk-[a-z0-9][a-z0-9-]*)\b")
69
+ RE_RELEASE_REF = re.compile(r"\b(?:sdtk-spec-kit@)?(0\.\d+\.\d+)\b")
70
+
71
+
72
+ # ---------------------------------------------------------------------------
73
+ # Generic doc-family classifier (project-scope, no maintainer assumptions)
74
+ # ---------------------------------------------------------------------------
75
+ def classify_family(rel: str) -> str:
76
+ p = rel.replace("\\", "/").lower()
77
+ name = Path(rel).name.lower()
78
+ if p == "readme.md":
79
+ return "root-readme"
80
+ if "backlog" in name:
81
+ return "backlog"
82
+ if "governance" in p:
83
+ return "governance"
84
+ if "docs/specs" in p or "specs/" in p:
85
+ return "spec"
86
+ if "docs/architecture" in p or "architecture/" in p:
87
+ return "architecture"
88
+ if "docs/api" in p or "api/" in p:
89
+ return "api"
90
+ if "docs/qa" in p or "qa/" in p:
91
+ return "qa"
92
+ if "docs/design" in p or "design/" in p:
93
+ return "design"
94
+ if "docs/dev" in p or "dev/" in p:
95
+ return "dev"
96
+ if "docs/product" in p or "product/" in p:
97
+ return "product"
98
+ if "skills" in p:
99
+ return "skill"
100
+ if "templates" in p:
101
+ return "template"
102
+ return "other-markdown"
103
+
104
+
105
+ def classify_role(rel: str) -> str:
106
+ p = rel.replace("\\", "/").lower()
107
+ if "governance" in p:
108
+ return "governance"
109
+ if "spec" in p or "architecture" in p:
110
+ return "spec-artifact"
111
+ if "skill" in p:
112
+ return "skill"
113
+ return "other"
114
+
115
+
116
+ # ---------------------------------------------------------------------------
117
+ # Scanner helpers
118
+ # ---------------------------------------------------------------------------
119
+ def _now_utc() -> str:
120
+ return datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
121
+
122
+
123
+ def _write_text_lf(path: Path, content: str) -> None:
124
+ path.write_text(content, encoding="utf-8", newline="\n")
125
+
126
+
127
+ def _is_excluded(
128
+ path: Path,
129
+ root: Path,
130
+ exclude_frags: list[str],
131
+ ) -> bool:
132
+ try:
133
+ rel = path.relative_to(root).as_posix().lower()
134
+ except ValueError:
135
+ rel = path.as_posix().lower()
136
+ for frag in exclude_frags:
137
+ norm_frag = frag.replace("\\", "/").lower()
138
+ if norm_frag in rel:
139
+ return True
140
+ return False
141
+
142
+
143
+ def _extract_title(text: str) -> str:
144
+ for line in text.splitlines():
145
+ stripped = line.strip()
146
+ if stripped.startswith("# "):
147
+ return stripped[2:].strip()
148
+ return ""
149
+
150
+
151
+ def _extract_headings(text: str) -> list[str]:
152
+ headings: list[str] = []
153
+ for line in text.splitlines():
154
+ stripped = line.strip()
155
+ if not stripped.startswith("#"):
156
+ continue
157
+ level = len(stripped) - len(stripped.lstrip("#"))
158
+ if 1 <= level <= 6 and len(stripped) > level and stripped[level] == " ":
159
+ headings.append(stripped[level + 1:].strip())
160
+ return headings
161
+
162
+
163
+ def _parse_frontmatter(text: str) -> tuple[dict[str, Any], str]:
164
+ lines = text.splitlines()
165
+ if not lines or lines[0].strip() != "---":
166
+ return {}, text
167
+
168
+ fields: dict[str, Any] = {}
169
+ current_list_key: str | None = None
170
+ for idx in range(1, len(lines)):
171
+ raw = lines[idx]
172
+ stripped = raw.strip()
173
+ if stripped in {"---", "..."}:
174
+ body = "\n".join(lines[idx + 1:])
175
+ if text.endswith("\n"):
176
+ body += "\n"
177
+ return fields, body
178
+ if not stripped:
179
+ current_list_key = None
180
+ continue
181
+ if stripped.startswith("- ") and current_list_key and isinstance(fields.get(current_list_key), list):
182
+ fields[current_list_key].append(stripped[2:].strip().strip('"\''))
183
+ continue
184
+ if ":" not in raw:
185
+ current_list_key = None
186
+ continue
187
+ key, value = raw.split(":", 1)
188
+ key = key.strip()
189
+ value = value.strip()
190
+ if not key:
191
+ current_list_key = None
192
+ continue
193
+ if not value:
194
+ fields[key] = []
195
+ current_list_key = key
196
+ continue
197
+ if value.startswith("[") and value.endswith("]"):
198
+ inner = value[1:-1].strip()
199
+ if inner:
200
+ fields[key] = [part.strip().strip('"\'') for part in inner.split(",") if part.strip()]
201
+ else:
202
+ fields[key] = []
203
+ current_list_key = None
204
+ continue
205
+ fields[key] = value.strip('"\'')
206
+ current_list_key = None
207
+
208
+ return {}, text
209
+
210
+
211
+ def _normalize_internal_ref(raw: str) -> str:
212
+ value = raw.strip()
213
+ if not value:
214
+ return ""
215
+ value = value.split("|", 1)[0].strip()
216
+ value = value.split("#", 1)[0].strip()
217
+ value = value.replace("\\", "/")
218
+ while value.startswith("./"):
219
+ value = value[2:]
220
+ if value.startswith("/"):
221
+ value = value[1:]
222
+ return value.strip()
223
+
224
+
225
+ def _extract_references(text: str) -> tuple[list[str], list[str], list[str]]:
226
+ issues = sorted(set(f"BK-{m}" for m in RE_BK.findall(text)))
227
+ knowledge_ids = sorted(
228
+ set(f"{m[0]}-{m[1]}" for m in RE_KNOWLEDGE_ID.findall(text))
229
+ )
230
+ raw_paths = RE_REPO_PATH.findall(text)
231
+ paths: list[str] = []
232
+ seen: set[str] = set()
233
+ for rp in raw_paths:
234
+ normalised = _normalize_internal_ref(rp)
235
+ if normalised and normalised not in seen:
236
+ seen.add(normalised)
237
+ paths.append(normalised)
238
+ return issues, knowledge_ids, paths
239
+
240
+
241
+ def _extract_wiki_links(text: str) -> list[str]:
242
+ links: list[str] = []
243
+ seen: set[str] = set()
244
+ for raw in RE_WIKI_LINK.findall(text):
245
+ normalised = _normalize_internal_ref(raw)
246
+ if normalised and normalised not in seen:
247
+ seen.add(normalised)
248
+ links.append(normalised)
249
+ return links
250
+
251
+
252
+ def _extract_markdown_links(text: str) -> list[str]:
253
+ links: list[str] = []
254
+ seen: set[str] = set()
255
+ for raw in RE_MARKDOWN_LINK.findall(text):
256
+ target = raw.strip().strip('<>')
257
+ lower = target.lower()
258
+ if not target or lower.startswith(("http://", "https://", "mailto:", "#")) or "://" in target:
259
+ continue
260
+ # Markdown links may include optional titles: [x](path.md "title").
261
+ if ' "' in target:
262
+ target = target.split(' "', 1)[0]
263
+ if " '" in target:
264
+ target = target.split(" '", 1)[0]
265
+ normalised = _normalize_internal_ref(target)
266
+ if normalised and normalised not in seen:
267
+ seen.add(normalised)
268
+ links.append(normalised)
269
+ return links
270
+
271
+
272
+ def _extract_skill_refs(text: str, path_refs: list[str], wiki_links: list[str]) -> list[str]:
273
+ refs = set(match.lower() for match in RE_SKILL_REF.findall(text))
274
+ for ref in path_refs + wiki_links:
275
+ parts = [part for part in ref.split("/") if part]
276
+ for marker in ("skills", "skills-claude"):
277
+ if marker in parts:
278
+ idx = parts.index(marker)
279
+ if idx + 1 < len(parts):
280
+ refs.add(parts[idx + 1].lower())
281
+ return sorted(refs)
282
+
283
+
284
+ def _extract_template_refs(path_refs: list[str], wiki_links: list[str]) -> list[str]:
285
+ refs: set[str] = set()
286
+ for ref in path_refs + wiki_links:
287
+ norm = _normalize_internal_ref(ref)
288
+ if "/templates/" in f"/{norm}":
289
+ refs.add(norm)
290
+ return sorted(refs)
291
+
292
+
293
+ def _extract_release_refs(text: str) -> list[str]:
294
+ return sorted(set(RE_RELEASE_REF.findall(text)))
295
+
296
+
297
+ def _compute_file_hash(md_file: Path) -> str:
298
+ content = md_file.read_bytes()
299
+ return hashlib.sha256(content).hexdigest()
300
+
301
+
302
+ def _parse_doc_record(md_file: Path, root: Path) -> dict[str, Any]:
303
+ rel = md_file.relative_to(root).as_posix()
304
+ text = md_file.read_text(encoding="utf-8", errors="replace")
305
+ frontmatter_fields, body_text = _parse_frontmatter(text)
306
+ title = str(
307
+ frontmatter_fields.get("title")
308
+ or _extract_title(body_text)
309
+ or md_file.stem.replace("_", " ").replace("-", " ")
310
+ )
311
+ headings = _extract_headings(body_text)
312
+ issues, knowledge_ids, path_refs = _extract_references(text)
313
+ wiki_links = _extract_wiki_links(text)
314
+ markdown_links = _extract_markdown_links(text)
315
+ path_refs = sorted(set(path_refs + markdown_links))
316
+ family = classify_family(rel)
317
+ role = classify_role(rel)
318
+ skill_refs = _extract_skill_refs(text, path_refs, wiki_links)
319
+ template_refs = _extract_template_refs(path_refs, wiki_links)
320
+ release_refs = _extract_release_refs(text)
321
+ return {
322
+ "id": rel,
323
+ "path": rel,
324
+ "title": title,
325
+ "family": family,
326
+ "role": role,
327
+ "trust_zone": "medium",
328
+ "body_markdown": body_text,
329
+ "issues": issues,
330
+ "knowledge_ids": knowledge_ids,
331
+ "headings": headings,
332
+ "frontmatter_fields": frontmatter_fields,
333
+ "skill_refs": skill_refs,
334
+ "template_refs": template_refs,
335
+ "release_refs": release_refs,
336
+ "lane_refs": [],
337
+ "wiki_links": wiki_links,
338
+ "path_refs": path_refs,
339
+ "outgoing_paths": path_refs,
340
+ }
341
+
342
+
343
+ def list_indexable_markdown_files(
344
+ root: Path,
345
+ scan_roots: list[Path],
346
+ exclude_frags: list[str],
347
+ ) -> list[Path]:
348
+ files: list[Path] = []
349
+ seen_paths: set[str] = set()
350
+
351
+ for scan_root in scan_roots:
352
+ if not scan_root.exists():
353
+ print(f"[atlas] Warning: scan root does not exist, skipping: {scan_root}", file=sys.stderr)
354
+ continue
355
+ if scan_root.is_file() and scan_root.suffix.lower() == ".md":
356
+ candidates = [scan_root]
357
+ elif scan_root.is_dir():
358
+ candidates = [p for p in sorted(scan_root.rglob("*.md")) if p.is_file()]
359
+ else:
360
+ candidates = []
361
+
362
+ for md_file in candidates:
363
+ if _is_excluded(md_file, root=root, exclude_frags=exclude_frags):
364
+ continue
365
+ try:
366
+ rel = md_file.relative_to(root).as_posix()
367
+ except ValueError:
368
+ rel = md_file.as_posix()
369
+ if rel in seen_paths:
370
+ continue
371
+ seen_paths.add(rel)
372
+ files.append(md_file)
373
+
374
+ files.sort(key=lambda p: p.as_posix())
375
+ return files
376
+
377
+
378
+ # ---------------------------------------------------------------------------
379
+ # Incremental build
380
+ # ---------------------------------------------------------------------------
381
+ def _empty_atlas_state() -> dict[str, Any]:
382
+ return {"version": ATLAS_STATE_VERSION, "documents": {}}
383
+
384
+
385
+ def _atlas_state_path(atlas_dir: Path) -> Path:
386
+ return atlas_dir / "ATLAS_STATE.json"
387
+
388
+
389
+ def load_atlas_state(atlas_dir: Path) -> dict[str, Any]:
390
+ state_path = _atlas_state_path(atlas_dir)
391
+ if not state_path.exists():
392
+ return _empty_atlas_state()
393
+ try:
394
+ data = json.loads(state_path.read_text(encoding="utf-8"))
395
+ except (OSError, json.JSONDecodeError):
396
+ return _empty_atlas_state()
397
+ if not isinstance(data, dict):
398
+ return _empty_atlas_state()
399
+ if data.get("version") != ATLAS_STATE_VERSION:
400
+ return _empty_atlas_state()
401
+ documents = data.get("documents")
402
+ if not isinstance(documents, dict):
403
+ return _empty_atlas_state()
404
+ return {"version": ATLAS_STATE_VERSION, "generated": data.get("generated"), "documents": documents}
405
+
406
+
407
+ def save_atlas_state(state: dict[str, Any], atlas_dir: Path) -> Path:
408
+ atlas_dir.mkdir(parents=True, exist_ok=True)
409
+ state_path = _atlas_state_path(atlas_dir)
410
+ _write_text_lf(state_path, json.dumps(state, ensure_ascii=True, indent=2, sort_keys=False))
411
+ return state_path
412
+
413
+
414
+ def build_docs_incremental(
415
+ root: Path,
416
+ atlas_dir: Path,
417
+ generated: str,
418
+ scan_roots: list[Path],
419
+ exclude_frags: list[str],
420
+ ) -> tuple[list[dict[str, Any]], dict[str, Any], dict[str, int]]:
421
+ prior_state = load_atlas_state(atlas_dir)
422
+ prior_documents = prior_state.get("documents", {})
423
+ current_files = list_indexable_markdown_files(root, scan_roots, exclude_frags)
424
+
425
+ current_rel_paths = {}
426
+ for md_file in current_files:
427
+ try:
428
+ rel = md_file.relative_to(root).as_posix()
429
+ except ValueError:
430
+ rel = md_file.as_posix()
431
+ current_rel_paths[rel] = md_file
432
+
433
+ next_documents: dict[str, Any] = {}
434
+ reused_count = 0
435
+ reparsed_count = 0
436
+
437
+ for rel, md_file in current_rel_paths.items():
438
+ stats = md_file.stat()
439
+ current_mtime = stats.st_mtime_ns
440
+ prior_record = prior_documents.get(rel)
441
+ prior_doc = prior_record.get("doc") if isinstance(prior_record, dict) else None
442
+
443
+ if (
444
+ isinstance(prior_record, dict)
445
+ and isinstance(prior_doc, dict)
446
+ and prior_record.get("mtime") == current_mtime
447
+ ):
448
+ next_documents[rel] = prior_record
449
+ reused_count += 1
450
+ continue
451
+
452
+ current_hash = _compute_file_hash(md_file)
453
+ if (
454
+ isinstance(prior_record, dict)
455
+ and isinstance(prior_doc, dict)
456
+ and prior_record.get("hash") == current_hash
457
+ ):
458
+ next_documents[rel] = {
459
+ "mtime": current_mtime,
460
+ "hash": current_hash,
461
+ "last_indexed": prior_record.get("last_indexed") or generated,
462
+ "doc": prior_doc,
463
+ }
464
+ reused_count += 1
465
+ continue
466
+
467
+ next_documents[rel] = {
468
+ "mtime": current_mtime,
469
+ "hash": current_hash,
470
+ "last_indexed": generated,
471
+ "doc": _parse_doc_record(md_file, root=root),
472
+ }
473
+ reparsed_count += 1
474
+
475
+ removed_count = len(set(prior_documents.keys()) - set(current_rel_paths.keys()))
476
+ docs = sorted(
477
+ [record["doc"] for record in next_documents.values()],
478
+ key=lambda d: d["id"],
479
+ )
480
+ next_state = {
481
+ "version": ATLAS_STATE_VERSION,
482
+ "generated": generated,
483
+ "documents": next_documents,
484
+ }
485
+ build_stats = {
486
+ "discovered_count": len(current_rel_paths),
487
+ "reused_count": reused_count,
488
+ "reparsed_count": reparsed_count,
489
+ "removed_count": removed_count,
490
+ }
491
+ return docs, next_state, build_stats
492
+
493
+
494
+ # ---------------------------------------------------------------------------
495
+ # Graph builder
496
+ # ---------------------------------------------------------------------------
497
+ def _build_doc_alias_map(docs: list[dict[str, Any]]) -> dict[str, set[str]]:
498
+ alias_map: dict[str, set[str]] = {}
499
+ for doc in docs:
500
+ doc_id = doc["id"]
501
+ path_obj = Path(doc_id)
502
+ aliases = {
503
+ doc_id,
504
+ doc_id.lower(),
505
+ path_obj.name,
506
+ path_obj.name.lower(),
507
+ path_obj.stem,
508
+ path_obj.stem.lower(),
509
+ }
510
+ if doc_id.lower().endswith(".md"):
511
+ no_ext = doc_id[:-3]
512
+ no_ext_path = Path(no_ext)
513
+ aliases.update({no_ext, no_ext.lower(), no_ext_path.name, no_ext_path.name.lower()})
514
+ for alias in aliases:
515
+ alias_map.setdefault(alias, set()).add(doc_id)
516
+ return alias_map
517
+
518
+
519
+ def _resolve_doc_reference(raw: str, alias_map: dict[str, set[str]]) -> str | None:
520
+ normalised = _normalize_internal_ref(raw)
521
+ if not normalised:
522
+ return None
523
+ candidates = [normalised, normalised.lower()]
524
+ if not normalised.lower().endswith(".md"):
525
+ candidates.extend([f"{normalised}.md", f"{normalised.lower()}.md"])
526
+ for candidate in candidates:
527
+ matches = alias_map.get(candidate)
528
+ if matches and len(matches) == 1:
529
+ return next(iter(matches))
530
+ return None
531
+
532
+
533
+ def build_graph(docs: list[dict[str, Any]]) -> dict[str, Any]:
534
+ alias_map = _build_doc_alias_map(docs)
535
+
536
+ nodes = [
537
+ {
538
+ "id": d["id"],
539
+ "title": d["title"],
540
+ "family": d["family"],
541
+ "role": d["role"],
542
+ "trust_zone": d.get("trust_zone", "medium"),
543
+ }
544
+ for d in docs
545
+ ]
546
+
547
+ edges: list[dict[str, Any]] = []
548
+
549
+ for doc in docs:
550
+ src = doc["id"]
551
+
552
+ for issue in doc.get("issues", []):
553
+ edges.append({"source": src, "target": issue, "type": "references_issue", "label": issue})
554
+
555
+ for kid in doc.get("knowledge_ids", []):
556
+ edges.append({"source": src, "target": kid, "type": "references_knowledge_object", "label": kid})
557
+
558
+ for rp in doc.get("path_refs", doc.get("outgoing_paths", [])):
559
+ target = _resolve_doc_reference(rp, alias_map)
560
+ if target:
561
+ edges.append({"source": src, "target": target, "type": "references_path", "label": rp})
562
+
563
+ for wiki_ref in doc.get("wiki_links", []):
564
+ target = _resolve_doc_reference(wiki_ref, alias_map)
565
+ if target:
566
+ edges.append({"source": src, "target": target, "type": "references_wiki_link", "label": wiki_ref})
567
+
568
+ for skill_ref in doc.get("skill_refs", []):
569
+ edges.append({"source": src, "target": f"__skill__{skill_ref}", "type": "references_skill", "label": skill_ref})
570
+
571
+ for template_ref in doc.get("template_refs", []):
572
+ edges.append({"source": src, "target": f"__template__{template_ref}", "type": "references_template", "label": template_ref})
573
+
574
+ family_groups: dict[str, list[str]] = {}
575
+ for doc in docs:
576
+ family_groups.setdefault(doc["family"], []).append(doc["id"])
577
+ for family, members in family_groups.items():
578
+ if len(members) < 2:
579
+ continue
580
+ for mid in members:
581
+ edges.append({"source": mid, "target": f"__family__{family}", "type": "same_family", "label": family})
582
+
583
+ return {"nodes": nodes, "edges": edges}
584
+
585
+
586
+ # ---------------------------------------------------------------------------
587
+ # Summary markdown
588
+ # ---------------------------------------------------------------------------
589
+ def build_summary(
590
+ docs: list[dict[str, Any]],
591
+ graph: dict[str, Any],
592
+ generated: str,
593
+ stats: dict[str, int] | None,
594
+ root: Path,
595
+ scan_roots: list[Path],
596
+ exclude_frags: list[str],
597
+ ) -> str:
598
+ family_counts: dict[str, int] = {}
599
+ for d in docs:
600
+ family_counts[d["family"]] = family_counts.get(d["family"], 0) + 1
601
+
602
+ edge_type_counts: dict[str, int] = {}
603
+ for e in graph["edges"]:
604
+ et = e["type"]
605
+ edge_type_counts[et] = edge_type_counts.get(et, 0) + 1
606
+
607
+ lines: list[str] = [
608
+ "# Document Atlas Summary",
609
+ "",
610
+ f"Generated: {generated}",
611
+ f"Project root: {root}",
612
+ "",
613
+ "## Document Counts",
614
+ "",
615
+ f"Total documents indexed: {len(docs)}",
616
+ "",
617
+ "| Family | Count |",
618
+ "|--------|-------|",
619
+ ]
620
+ for fam, cnt in sorted(family_counts.items(), key=lambda x: -x[1]):
621
+ lines.append(f"| {fam} | {cnt} |")
622
+
623
+ if stats is not None:
624
+ lines += [
625
+ "",
626
+ "## Incremental Build",
627
+ "",
628
+ f"Discovered markdown docs: {stats['discovered_count']}",
629
+ f"Reused cached docs: {stats['reused_count']}",
630
+ f"Reparsed docs: {stats['reparsed_count']}",
631
+ f"Removed stale docs: {stats['removed_count']}",
632
+ ]
633
+
634
+ lines += [
635
+ "",
636
+ "## Graph Summary",
637
+ "",
638
+ f"Total nodes: {len(graph['nodes'])}",
639
+ f"Total edges: {len(graph['edges'])}",
640
+ "",
641
+ "## Scan Roots",
642
+ "",
643
+ ]
644
+ for sr in scan_roots:
645
+ lines.append(f"- {sr}")
646
+
647
+ lines += [
648
+ "",
649
+ "## Exclusions Applied",
650
+ "",
651
+ ]
652
+ for frag in exclude_frags:
653
+ lines.append(f"- {frag}")
654
+
655
+ return "\n".join(lines) + "\n"
656
+
657
+
658
+ # ---------------------------------------------------------------------------
659
+ # Static viewer
660
+ # ---------------------------------------------------------------------------
661
+ _FAMILY_COLORS = {
662
+ "governance": "#58a6ff",
663
+ "backlog": "#d2a8ff",
664
+ "spec": "#f0883e",
665
+ "architecture": "#3fb950",
666
+ "api": "#f778ba",
667
+ "qa": "#79c0ff",
668
+ "design": "#ffa657",
669
+ "dev": "#56d364",
670
+ "product": "#e3b341",
671
+ "skill": "#58a6ff",
672
+ "template": "#f0883e",
673
+ "root-readme": "#e3b341",
674
+ "other-markdown": "#8b949e",
675
+ }
676
+
677
+
678
+ def build_viewer(index: dict, graph: dict, generated: str) -> str:
679
+ if not _VIEWER_TEMPLATE_PATH.exists():
680
+ raise FileNotFoundError(f"Viewer template not found: {_VIEWER_TEMPLATE_PATH}")
681
+ index_json = json.dumps(index, ensure_ascii=True, separators=(",", ":"))
682
+ graph_json = json.dumps(graph, ensure_ascii=True, separators=(",", ":"))
683
+ family_colors_json = json.dumps(_FAMILY_COLORS, ensure_ascii=True, separators=(",", ":"))
684
+ template = _VIEWER_TEMPLATE_PATH.read_text(encoding="utf-8")
685
+ return (
686
+ template
687
+ .replace("__ATLAS_GENERATED__", generated)
688
+ .replace("__ATLAS_INDEX_JSON__", index_json)
689
+ .replace("__ATLAS_GRAPH_JSON__", graph_json)
690
+ .replace("__ATLAS_FAMILY_COLORS_JSON__", family_colors_json)
691
+ )
692
+
693
+
694
+ def copy_viewer_assets(atlas_dir: Path) -> list[Path]:
695
+ if not MERMAID_VENDOR_PATH.exists():
696
+ raise FileNotFoundError(f"Missing Mermaid runtime asset: {MERMAID_VENDOR_PATH}")
697
+ atlas_dir.mkdir(parents=True, exist_ok=True)
698
+ # Copy mermaid to atlas root (same location the viewer template expects)
699
+ destination = atlas_dir / MERMAID_ASSET_NAME
700
+ shutil.copyfile(MERMAID_VENDOR_PATH, destination)
701
+ return [destination]
702
+
703
+
704
+ # ---------------------------------------------------------------------------
705
+ # Main build
706
+ # ---------------------------------------------------------------------------
707
+ def build_atlas(
708
+ root: Path,
709
+ atlas_dir: Path,
710
+ scan_roots: list[Path] | None = None,
711
+ exclude_frags: list[str] | None = None,
712
+ verbose: bool = False,
713
+ ) -> dict[str, Any]:
714
+ generated = _now_utc()
715
+ frags = exclude_frags if exclude_frags is not None else DEFAULT_EXCLUDE_FRAGS
716
+ roots = scan_roots if scan_roots else [root]
717
+
718
+ print(f"[atlas] Project root: {root}")
719
+ print(f"[atlas] Output dir: {atlas_dir}")
720
+ print(f"[atlas] Scan roots: {[str(r) for r in roots]}")
721
+
722
+ atlas_dir.mkdir(parents=True, exist_ok=True)
723
+
724
+ print("[atlas] Scanning markdown files...")
725
+ docs, state, stats = build_docs_incremental(
726
+ root=root,
727
+ atlas_dir=atlas_dir,
728
+ generated=generated,
729
+ scan_roots=roots,
730
+ exclude_frags=frags,
731
+ )
732
+ print(f"[atlas] Indexed {len(docs)} documents.")
733
+ if verbose:
734
+ print(
735
+ f"[atlas] Incremental build: reused {stats['reused_count']} cached, "
736
+ f"reparsed {stats['reparsed_count']}, removed {stats['removed_count']}."
737
+ )
738
+
739
+ print("[atlas] Building graph...")
740
+ graph = build_graph(docs)
741
+ print(f"[atlas] Graph: {len(graph['nodes'])} nodes, {len(graph['edges'])} edges.")
742
+
743
+ index_data = {
744
+ "generated": generated,
745
+ "count": len(docs),
746
+ "documents": docs,
747
+ }
748
+
749
+ save_atlas_state(state, atlas_dir=atlas_dir)
750
+
751
+ index_path = atlas_dir / "SDTK_DOC_INDEX.json"
752
+ _write_text_lf(index_path, json.dumps(index_data, ensure_ascii=True, indent=2, sort_keys=False))
753
+
754
+ graph_out = {
755
+ "generated": generated,
756
+ "node_count": len(graph["nodes"]),
757
+ "edge_count": len(graph["edges"]),
758
+ "nodes": graph["nodes"],
759
+ "edges": graph["edges"],
760
+ }
761
+ graph_path = atlas_dir / "SDTK_DOC_GRAPH.json"
762
+ _write_text_lf(graph_path, json.dumps(graph_out, ensure_ascii=True, indent=2, sort_keys=False))
763
+
764
+ summary_text = build_summary(docs, graph, generated, stats=stats, root=root, scan_roots=roots, exclude_frags=frags)
765
+ summary_path = atlas_dir / "SDTK_DOC_ATLAS_SUMMARY.md"
766
+ _write_text_lf(summary_path, summary_text)
767
+
768
+ viewer_html = build_viewer(index_data, graph_out, generated)
769
+ viewer_path = atlas_dir / "viewer.html"
770
+ _write_text_lf(viewer_path, viewer_html)
771
+
772
+ for asset_path in copy_viewer_assets(atlas_dir=atlas_dir):
773
+ if verbose:
774
+ print(f"[atlas] Wrote asset: {asset_path.name}")
775
+
776
+ print(f"[atlas] Done. Output: {atlas_dir}")
777
+ return {
778
+ "generated": generated,
779
+ "doc_count": len(docs),
780
+ "node_count": len(graph["nodes"]),
781
+ "edge_count": len(graph["edges"]),
782
+ "stats": stats,
783
+ "atlas_dir": str(atlas_dir),
784
+ }
785
+
786
+
787
+ # ---------------------------------------------------------------------------
788
+ # CLI entry point
789
+ # ---------------------------------------------------------------------------
790
+ def main() -> int:
791
+ parser = argparse.ArgumentParser(
792
+ description="SDTK-SPEC Atlas Builder -- build a local document graph and viewer.",
793
+ formatter_class=argparse.RawDescriptionHelpFormatter,
794
+ )
795
+ parser.add_argument(
796
+ "--project-root",
797
+ required=True,
798
+ help="Absolute path to the project root to scan.",
799
+ )
800
+ parser.add_argument(
801
+ "--output-dir",
802
+ required=True,
803
+ help="Directory to write atlas artifacts into.",
804
+ )
805
+ parser.add_argument(
806
+ "--scan-root",
807
+ dest="scan_roots",
808
+ action="append",
809
+ metavar="PATH",
810
+ default=None,
811
+ help="Explicit scan root (repeatable). Defaults to project root.",
812
+ )
813
+ parser.add_argument(
814
+ "--exclude",
815
+ dest="excludes",
816
+ action="append",
817
+ metavar="FRAG",
818
+ default=None,
819
+ help="Exclusion path fragment (repeatable). Defaults to standard set.",
820
+ )
821
+ parser.add_argument(
822
+ "--verbose",
823
+ action="store_true",
824
+ default=False,
825
+ help="Show incremental build detail.",
826
+ )
827
+
828
+ args = parser.parse_args()
829
+
830
+ root = Path(args.project_root).resolve()
831
+ if not root.is_dir():
832
+ print(f"[atlas] ERROR: --project-root is not a directory: {root}", file=sys.stderr)
833
+ return 1
834
+
835
+ atlas_dir = Path(args.output_dir).resolve()
836
+
837
+ scan_roots: list[Path] | None = None
838
+ if args.scan_roots:
839
+ scan_roots = [Path(sr).resolve() for sr in args.scan_roots]
840
+
841
+ excludes: list[str] | None = None
842
+ if args.excludes:
843
+ excludes = args.excludes
844
+
845
+ try:
846
+ result = build_atlas(
847
+ root=root,
848
+ atlas_dir=atlas_dir,
849
+ scan_roots=scan_roots,
850
+ exclude_frags=excludes,
851
+ verbose=args.verbose,
852
+ )
853
+ # Print JSON summary to stdout for Node CLI to parse
854
+ print(f"[atlas:result] {json.dumps(result)}")
855
+ return 0
856
+ except FileNotFoundError as e:
857
+ print(f"[atlas] ERROR: {e}", file=sys.stderr)
858
+ return 2
859
+ except Exception as e:
860
+ print(f"[atlas] ERROR: {e}", file=sys.stderr)
861
+ return 1
862
+
863
+
864
+ if __name__ == "__main__":
865
+ sys.exit(main())