sdtk-spec-kit 0.4.11 → 0.4.14

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