graphitect 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (336) hide show
  1. graphify/__init__.py +30 -0
  2. graphify/__main__.py +757 -0
  3. graphify/_minhash.py +107 -0
  4. graphify/affected.py +318 -0
  5. graphify/always_on/agents-md.md +12 -0
  6. graphify/always_on/antigravity-rules.md +14 -0
  7. graphify/always_on/claude-md.md +9 -0
  8. graphify/always_on/gemini-md.md +9 -0
  9. graphify/always_on/kiro-steering.md +5 -0
  10. graphify/always_on/vscode-instructions.md +17 -0
  11. graphify/analyze.py +769 -0
  12. graphify/benchmark.py +152 -0
  13. graphify/build.py +2300 -0
  14. graphify/cache.py +1746 -0
  15. graphify/callflow_html.py +2051 -0
  16. graphify/cargo_introspect.py +109 -0
  17. graphify/cli.py +4745 -0
  18. graphify/cluster.py +409 -0
  19. graphify/command-kilo.md +15 -0
  20. graphify/cross_repo_calls.py +216 -0
  21. graphify/cross_repo_types.py +75 -0
  22. graphify/csharp_dispatch.py +154 -0
  23. graphify/dedup.py +1213 -0
  24. graphify/detect.py +2566 -0
  25. graphify/diagnostics.py +406 -0
  26. graphify/export.py +1349 -0
  27. graphify/exporters/__init__.py +1 -0
  28. graphify/exporters/base.py +14 -0
  29. graphify/exporters/graphdb.py +173 -0
  30. graphify/exporters/html.py +637 -0
  31. graphify/extract.py +7856 -0
  32. graphify/extractors/MIGRATION.md +107 -0
  33. graphify/extractors/__init__.py +66 -0
  34. graphify/extractors/apex.py +215 -0
  35. graphify/extractors/base.py +85 -0
  36. graphify/extractors/bash.py +579 -0
  37. graphify/extractors/blade.py +53 -0
  38. graphify/extractors/commonlisp.py +540 -0
  39. graphify/extractors/csharp.py +448 -0
  40. graphify/extractors/dart.py +564 -0
  41. graphify/extractors/dm.py +494 -0
  42. graphify/extractors/elixir.py +241 -0
  43. graphify/extractors/engine.py +6509 -0
  44. graphify/extractors/fortran.py +311 -0
  45. graphify/extractors/go.py +527 -0
  46. graphify/extractors/json_config.py +240 -0
  47. graphify/extractors/julia.py +289 -0
  48. graphify/extractors/markdown.py +408 -0
  49. graphify/extractors/models.py +131 -0
  50. graphify/extractors/objc.py +566 -0
  51. graphify/extractors/ocaml.py +289 -0
  52. graphify/extractors/pascal.py +688 -0
  53. graphify/extractors/pascal_forms.py +196 -0
  54. graphify/extractors/powershell.py +522 -0
  55. graphify/extractors/razor.py +192 -0
  56. graphify/extractors/resolution.py +3584 -0
  57. graphify/extractors/robot.py +296 -0
  58. graphify/extractors/rust.py +470 -0
  59. graphify/extractors/sln.py +92 -0
  60. graphify/extractors/sql.py +720 -0
  61. graphify/extractors/terraform.py +181 -0
  62. graphify/extractors/verilog.py +329 -0
  63. graphify/extractors/zig.py +181 -0
  64. graphify/file_slice.py +246 -0
  65. graphify/global_graph.py +194 -0
  66. graphify/google_workspace.py +237 -0
  67. graphify/hooks.py +933 -0
  68. graphify/ids.py +93 -0
  69. graphify/ingest.py +358 -0
  70. graphify/install.py +2366 -0
  71. graphify/llm.py +3544 -0
  72. graphify/manifest.py +4 -0
  73. graphify/manifest_ingest.py +311 -0
  74. graphify/mcp_ingest.py +386 -0
  75. graphify/multigraph_compat.py +212 -0
  76. graphify/pascal_resolution.py +129 -0
  77. graphify/paths.py +436 -0
  78. graphify/pg_introspect.py +165 -0
  79. graphify/prs.py +770 -0
  80. graphify/querylog.py +80 -0
  81. graphify/reflect.py +882 -0
  82. graphify/report.py +346 -0
  83. graphify/resolver_registry.py +85 -0
  84. graphify/ruby_resolution.py +242 -0
  85. graphify/scip_ingest.py +363 -0
  86. graphify/security.py +460 -0
  87. graphify/semantic_cleanup.py +336 -0
  88. graphify/serve.py +2608 -0
  89. graphify/skill-agents.md +710 -0
  90. graphify/skill-aider.md +1283 -0
  91. graphify/skill-amp.md +710 -0
  92. graphify/skill-claw.md +713 -0
  93. graphify/skill-codex.md +710 -0
  94. graphify/skill-copilot.md +713 -0
  95. graphify/skill-devin.md +1410 -0
  96. graphify/skill-droid.md +710 -0
  97. graphify/skill-kilo.md +722 -0
  98. graphify/skill-kiro.md +713 -0
  99. graphify/skill-opencode.md +705 -0
  100. graphify/skill-pi.md +713 -0
  101. graphify/skill-trae.md +711 -0
  102. graphify/skill-vscode.md +709 -0
  103. graphify/skill-windows.md +755 -0
  104. graphify/skill.md +713 -0
  105. graphify/skills/agents/references/add-watch.md +56 -0
  106. graphify/skills/agents/references/exports.md +87 -0
  107. graphify/skills/agents/references/extraction-spec.md +70 -0
  108. graphify/skills/agents/references/github-and-merge.md +46 -0
  109. graphify/skills/agents/references/hooks.md +33 -0
  110. graphify/skills/agents/references/query.md +311 -0
  111. graphify/skills/agents/references/transcribe.md +52 -0
  112. graphify/skills/agents/references/update.md +210 -0
  113. graphify/skills/amp/references/add-watch.md +56 -0
  114. graphify/skills/amp/references/exports.md +87 -0
  115. graphify/skills/amp/references/extraction-spec.md +70 -0
  116. graphify/skills/amp/references/github-and-merge.md +46 -0
  117. graphify/skills/amp/references/hooks.md +33 -0
  118. graphify/skills/amp/references/query.md +311 -0
  119. graphify/skills/amp/references/transcribe.md +52 -0
  120. graphify/skills/amp/references/update.md +210 -0
  121. graphify/skills/claude/references/add-watch.md +56 -0
  122. graphify/skills/claude/references/exports.md +87 -0
  123. graphify/skills/claude/references/extraction-spec.md +70 -0
  124. graphify/skills/claude/references/github-and-merge.md +46 -0
  125. graphify/skills/claude/references/hooks.md +33 -0
  126. graphify/skills/claude/references/query.md +311 -0
  127. graphify/skills/claude/references/transcribe.md +52 -0
  128. graphify/skills/claude/references/update.md +210 -0
  129. graphify/skills/claw/references/add-watch.md +56 -0
  130. graphify/skills/claw/references/exports.md +87 -0
  131. graphify/skills/claw/references/extraction-spec.md +31 -0
  132. graphify/skills/claw/references/github-and-merge.md +46 -0
  133. graphify/skills/claw/references/hooks.md +33 -0
  134. graphify/skills/claw/references/query.md +311 -0
  135. graphify/skills/claw/references/transcribe.md +52 -0
  136. graphify/skills/claw/references/update.md +210 -0
  137. graphify/skills/codex/references/add-watch.md +56 -0
  138. graphify/skills/codex/references/exports.md +87 -0
  139. graphify/skills/codex/references/extraction-spec.md +31 -0
  140. graphify/skills/codex/references/github-and-merge.md +46 -0
  141. graphify/skills/codex/references/hooks.md +33 -0
  142. graphify/skills/codex/references/query.md +311 -0
  143. graphify/skills/codex/references/transcribe.md +52 -0
  144. graphify/skills/codex/references/update.md +210 -0
  145. graphify/skills/copilot/references/add-watch.md +56 -0
  146. graphify/skills/copilot/references/exports.md +87 -0
  147. graphify/skills/copilot/references/extraction-spec.md +70 -0
  148. graphify/skills/copilot/references/github-and-merge.md +46 -0
  149. graphify/skills/copilot/references/hooks.md +33 -0
  150. graphify/skills/copilot/references/query.md +311 -0
  151. graphify/skills/copilot/references/transcribe.md +52 -0
  152. graphify/skills/copilot/references/update.md +210 -0
  153. graphify/skills/droid/references/add-watch.md +56 -0
  154. graphify/skills/droid/references/exports.md +87 -0
  155. graphify/skills/droid/references/extraction-spec.md +70 -0
  156. graphify/skills/droid/references/github-and-merge.md +46 -0
  157. graphify/skills/droid/references/hooks.md +33 -0
  158. graphify/skills/droid/references/query.md +311 -0
  159. graphify/skills/droid/references/transcribe.md +52 -0
  160. graphify/skills/droid/references/update.md +210 -0
  161. graphify/skills/kilo/references/add-watch.md +56 -0
  162. graphify/skills/kilo/references/exports.md +87 -0
  163. graphify/skills/kilo/references/extraction-spec.md +70 -0
  164. graphify/skills/kilo/references/github-and-merge.md +46 -0
  165. graphify/skills/kilo/references/hooks.md +33 -0
  166. graphify/skills/kilo/references/query.md +311 -0
  167. graphify/skills/kilo/references/transcribe.md +52 -0
  168. graphify/skills/kilo/references/update.md +210 -0
  169. graphify/skills/kiro/references/add-watch.md +56 -0
  170. graphify/skills/kiro/references/exports.md +87 -0
  171. graphify/skills/kiro/references/extraction-spec.md +31 -0
  172. graphify/skills/kiro/references/github-and-merge.md +46 -0
  173. graphify/skills/kiro/references/hooks.md +33 -0
  174. graphify/skills/kiro/references/query.md +311 -0
  175. graphify/skills/kiro/references/transcribe.md +52 -0
  176. graphify/skills/kiro/references/update.md +210 -0
  177. graphify/skills/opencode/references/add-watch.md +56 -0
  178. graphify/skills/opencode/references/exports.md +87 -0
  179. graphify/skills/opencode/references/extraction-spec.md +70 -0
  180. graphify/skills/opencode/references/github-and-merge.md +46 -0
  181. graphify/skills/opencode/references/hooks.md +33 -0
  182. graphify/skills/opencode/references/query.md +311 -0
  183. graphify/skills/opencode/references/transcribe.md +52 -0
  184. graphify/skills/opencode/references/update.md +210 -0
  185. graphify/skills/pi/references/add-watch.md +56 -0
  186. graphify/skills/pi/references/exports.md +87 -0
  187. graphify/skills/pi/references/extraction-spec.md +31 -0
  188. graphify/skills/pi/references/github-and-merge.md +46 -0
  189. graphify/skills/pi/references/hooks.md +33 -0
  190. graphify/skills/pi/references/query.md +311 -0
  191. graphify/skills/pi/references/transcribe.md +52 -0
  192. graphify/skills/pi/references/update.md +210 -0
  193. graphify/skills/trae/references/add-watch.md +56 -0
  194. graphify/skills/trae/references/exports.md +87 -0
  195. graphify/skills/trae/references/extraction-spec.md +70 -0
  196. graphify/skills/trae/references/github-and-merge.md +46 -0
  197. graphify/skills/trae/references/hooks.md +35 -0
  198. graphify/skills/trae/references/query.md +311 -0
  199. graphify/skills/trae/references/transcribe.md +52 -0
  200. graphify/skills/trae/references/update.md +210 -0
  201. graphify/skills/vscode/references/add-watch.md +56 -0
  202. graphify/skills/vscode/references/exports.md +87 -0
  203. graphify/skills/vscode/references/extraction-spec.md +70 -0
  204. graphify/skills/vscode/references/github-and-merge.md +46 -0
  205. graphify/skills/vscode/references/hooks.md +33 -0
  206. graphify/skills/vscode/references/query.md +311 -0
  207. graphify/skills/vscode/references/transcribe.md +52 -0
  208. graphify/skills/vscode/references/update.md +210 -0
  209. graphify/skills/windows/references/add-watch.md +56 -0
  210. graphify/skills/windows/references/exports.md +87 -0
  211. graphify/skills/windows/references/extraction-spec.md +70 -0
  212. graphify/skills/windows/references/github-and-merge.md +46 -0
  213. graphify/skills/windows/references/hooks.md +33 -0
  214. graphify/skills/windows/references/query.md +311 -0
  215. graphify/skills/windows/references/transcribe.md +52 -0
  216. graphify/skills/windows/references/update.md +210 -0
  217. graphify/symbol_resolution.py +556 -0
  218. graphify/transcribe.py +186 -0
  219. graphify/tree_html.py +603 -0
  220. graphify/validate.py +95 -0
  221. graphify/watch.py +2280 -0
  222. graphify/wiki.py +405 -0
  223. graphitect/__init__.py +28 -0
  224. graphitect/__main__.py +4 -0
  225. graphitect/_vendor/__init__.py +2 -0
  226. graphitect/_vendor/archify/LICENSE +22 -0
  227. graphitect/_vendor/archify/SKILL.md +137 -0
  228. graphitect/_vendor/archify/THIRD_PARTY_NOTICES.md +69 -0
  229. graphitect/_vendor/archify/assets/JetBrainsMono-OFL.txt +93 -0
  230. graphitect/_vendor/archify/assets/template.html +14935 -0
  231. graphitect/_vendor/archify/bin/archify.mjs +2091 -0
  232. graphitect/_vendor/archify/bin/open-artifact.mjs +86 -0
  233. graphitect/_vendor/archify/bin/preview.mjs +653 -0
  234. graphitect/_vendor/archify/bin/visual-check.mjs +829 -0
  235. graphitect/_vendor/archify/brand-marks/README.md +31 -0
  236. graphitect/_vendor/archify/brand-marks/catalog.json +131 -0
  237. graphitect/_vendor/archify/delta/architecture-delta.mjs +1221 -0
  238. graphitect/_vendor/archify/examples/agent-run.lifecycle.json +60 -0
  239. graphitect/_vendor/archify/examples/agent-tool-call.workflow.json +94 -0
  240. graphitect/_vendor/archify/examples/async-job-roundtrip.sequence.json +61 -0
  241. graphitect/_vendor/archify/examples/brand-aware-delivery.architecture.json +47 -0
  242. graphitect/_vendor/archify/examples/cache-miss-request.sequence.json +82 -0
  243. graphitect/_vendor/archify/examples/checkout-platform.base.architecture.json +31 -0
  244. graphitect/_vendor/archify/examples/checkout-platform.head.architecture.json +31 -0
  245. graphitect/_vendor/archify/examples/dataflow-product-analytics.html +15045 -0
  246. graphitect/_vendor/archify/examples/deployment-release.lifecycle.json +49 -0
  247. graphitect/_vendor/archify/examples/event-stream.dataflow.json +57 -0
  248. graphitect/_vendor/archify/examples/incident-response.workflow.json +64 -0
  249. graphitect/_vendor/archify/examples/lifecycle-agent-run.html +14980 -0
  250. graphitect/_vendor/archify/examples/product-analytics.dataflow.json +76 -0
  251. graphitect/_vendor/archify/examples/production-deployment.architecture.json +71 -0
  252. graphitect/_vendor/archify/examples/release-delivery.workflow.json +62 -0
  253. graphitect/_vendor/archify/examples/sequence-cache-miss-request.html +15060 -0
  254. graphitect/_vendor/archify/examples/web-app-rendered.html +15009 -0
  255. graphitect/_vendor/archify/examples/web-app.architecture.json +46 -0
  256. graphitect/_vendor/archify/examples/workflow-agent-tool-call-rendered.html +15051 -0
  257. graphitect/_vendor/archify/migrations/workflow-v2.mjs +279 -0
  258. graphitect/_vendor/archify/package-lock.json +149 -0
  259. graphitect/_vendor/archify/package.json +39 -0
  260. graphitect/_vendor/archify/recipes/scenarios.mjs +391 -0
  261. graphitect/_vendor/archify/references/authoring-contract.md +243 -0
  262. graphitect/_vendor/archify/references/brand-marks.md +65 -0
  263. graphitect/_vendor/archify/references/delivery-contract.md +120 -0
  264. graphitect/_vendor/archify/references/viewer-runtime.md +45 -0
  265. graphitect/_vendor/archify/renderers/architecture/grid.mjs +62 -0
  266. graphitect/_vendor/archify/renderers/architecture/render-architecture.mjs +1078 -0
  267. graphitect/_vendor/archify/renderers/dataflow/README.md +104 -0
  268. graphitect/_vendor/archify/renderers/dataflow/render-dataflow.mjs +483 -0
  269. graphitect/_vendor/archify/renderers/lifecycle/README.md +115 -0
  270. graphitect/_vendor/archify/renderers/lifecycle/render-lifecycle.mjs +561 -0
  271. graphitect/_vendor/archify/renderers/sequence/README.md +114 -0
  272. graphitect/_vendor/archify/renderers/sequence/render-sequence.mjs +464 -0
  273. graphitect/_vendor/archify/renderers/shared/brand-marks.mjs +563 -0
  274. graphitect/_vendor/archify/renderers/shared/cli.mjs +218 -0
  275. graphitect/_vendor/archify/renderers/shared/desktop-readability.mjs +26 -0
  276. graphitect/_vendor/archify/renderers/shared/diagnostics.mjs +127 -0
  277. graphitect/_vendor/archify/renderers/shared/engineering-profiles.mjs +157 -0
  278. graphitect/_vendor/archify/renderers/shared/generated-brand-marks.mjs +2003 -0
  279. graphitect/_vendor/archify/renderers/shared/generated-validators.mjs +13 -0
  280. graphitect/_vendor/archify/renderers/shared/geometry.mjs +1423 -0
  281. graphitect/_vendor/archify/renderers/shared/i18n.mjs +595 -0
  282. graphitect/_vendor/archify/renderers/shared/layout-report.mjs +40 -0
  283. graphitect/_vendor/archify/renderers/shared/legend.mjs +217 -0
  284. graphitect/_vendor/archify/renderers/shared/output-path.mjs +340 -0
  285. graphitect/_vendor/archify/renderers/shared/repository-evidence.mjs +238 -0
  286. graphitect/_vendor/archify/renderers/shared/repository-location.mjs +58 -0
  287. graphitect/_vendor/archify/renderers/shared/text-fit.mjs +49 -0
  288. graphitect/_vendor/archify/renderers/shared/utils.mjs +232 -0
  289. graphitect/_vendor/archify/renderers/shared/validator.mjs +86 -0
  290. graphitect/_vendor/archify/renderers/workflow/README.md +223 -0
  291. graphitect/_vendor/archify/renderers/workflow/render-workflow.mjs +35 -0
  292. graphitect/_vendor/archify/renderers/workflow/workflow-compiler.mjs +4400 -0
  293. graphitect/_vendor/archify/renderers/workflow/workflow-migration-geometry.mjs +144 -0
  294. graphitect/_vendor/archify/schemas/README.md +211 -0
  295. graphitect/_vendor/archify/schemas/architecture.schema.json +178 -0
  296. graphitect/_vendor/archify/schemas/common.schema.json +115 -0
  297. graphitect/_vendor/archify/schemas/dataflow.schema.json +243 -0
  298. graphitect/_vendor/archify/schemas/lifecycle.schema.json +266 -0
  299. graphitect/_vendor/archify/schemas/sequence.schema.json +223 -0
  300. graphitect/_vendor/archify/schemas/workflow.schema.json +428 -0
  301. graphitect/_vendor/archify/scripts/check-render-output.mjs +836 -0
  302. graphitect/_vendor/archify/scripts/check-update.mjs +1667 -0
  303. graphitect/_vendor/archify/scripts/generate-brand-marks.mjs +141 -0
  304. graphitect/_vendor/archify/scripts/generate-validators.mjs +66 -0
  305. graphitect/_vendor/archify/scripts/render-examples.mjs +26 -0
  306. graphitect/_vendor/archify/scripts/update-contract.mjs +182 -0
  307. graphitect/_vendor/archify/skill-release.json +10 -0
  308. graphitect/cli.py +981 -0
  309. graphitect/deliver/__init__.py +5 -0
  310. graphitect/deliver/archify_adapter.py +1877 -0
  311. graphitect/deliver/archify_ir.py +160 -0
  312. graphitect/deliver/archify_repair.py +135 -0
  313. graphitect/deliver/doc_compiler.py +916 -0
  314. graphitect/ground/__init__.py +5 -0
  315. graphitect/ground/describe_source.py +27 -0
  316. graphitect/ground/fullread_source.py +56 -0
  317. graphitect/ground/graphify_source.py +107 -0
  318. graphitect/models.py +118 -0
  319. graphitect/skill/SKILL.md +80 -0
  320. graphitect/skill/agents/openai.yaml +4 -0
  321. graphitect/synthesize/__init__.py +5 -0
  322. graphitect/synthesize/engine.py +281 -0
  323. graphitect/synthesize/llm_backend.py +331 -0
  324. graphitect/synthesize/questions.py +139 -0
  325. graphitect/synthesize/rubric.py +104 -0
  326. graphitect-0.2.0.dist-info/METADATA +284 -0
  327. graphitect-0.2.0.dist-info/RECORD +336 -0
  328. graphitect-0.2.0.dist-info/WHEEL +5 -0
  329. graphitect-0.2.0.dist-info/entry_points.txt +2 -0
  330. graphitect-0.2.0.dist-info/licenses/LICENSE +21 -0
  331. graphitect-0.2.0.dist-info/licenses/LICENSE-ARCHIFY-MIT +22 -0
  332. graphitect-0.2.0.dist-info/licenses/LICENSE-GRAPHIFY-APACHE-2.0 +202 -0
  333. graphitect-0.2.0.dist-info/licenses/LICENSE-GRAPHIFY-MIT +21 -0
  334. graphitect-0.2.0.dist-info/licenses/NOTICE-ARCHIFY-THIRD-PARTY.md +69 -0
  335. graphitect-0.2.0.dist-info/licenses/NOTICE-GRAPHIFY +8 -0
  336. graphitect-0.2.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,2051 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ callflow_html.py — Generate call-flow architecture HTML from graphify knowledge graph outputs.
4
+
5
+ Reads graph.json plus optional GRAPH_REPORT.md, .graphify_labels.json, and sections JSON,
6
+ then produces a self-contained HTML file with:
7
+ - Dark-themed CSS (fixed template)
8
+ - Navigation bar from section list
9
+ - Architecture overview flowchart LR (aggregated section-level edges)
10
+ - Per-section flowchart LR (auto-generated representative intra-section edges)
11
+ - Call detail table scaffolding (headers + representative node rows)
12
+ - Auto-generated section intros and key-file cards
13
+
14
+ Usage:
15
+ python3 -m graphify export callflow-html
16
+ python3 -m graphify export callflow-html /path/to/project/graphify-out/graph.json
17
+ python3 -m graphify export callflow-html --graph /path/to/graph.json --output docs/architecture.html
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import argparse
24
+ import os
25
+ import re
26
+ import sys
27
+ import hashlib
28
+ from pathlib import Path
29
+ from collections import Counter, defaultdict
30
+ from datetime import datetime, timezone
31
+ from html import escape
32
+
33
+ from graphify.paths import GRAPHIFY_OUT, GRAPHIFY_OUT_NAME
34
+
35
+
36
+ # ──────────────────────────────────────────────
37
+ # 1. CSS template (fixed, project-agnostic)
38
+ # ──────────────────────────────────────────────
39
+
40
+ CSS = """:root {
41
+ --bg: #0f172a; --surface: #1e293b; --border: #334155;
42
+ --text: #e2e8f0; --muted: #94a3b8; --accent: #38bdf8;
43
+ --warn: #fbbf24; --err: #f87171; --ok: #34d399;
44
+ }
45
+ * { box-sizing: border-box; margin: 0; padding: 0; }
46
+ body { font-family: 'Segoe UI', system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--text); line-height: 1.7; }
47
+ .container { max-width: 1200px; margin: 0 auto; padding: 40px 24px; }
48
+ h1 { font-size: 2.4rem; margin-bottom: 8px; background: linear-gradient(135deg, var(--accent), #a78bfa); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
49
+ h2 { font-size: 1.7rem; margin: 48px 0 16px; padding-bottom: 8px; border-bottom: 2px solid var(--accent); }
50
+ h3 { font-size: 1.25rem; margin: 32px 0 12px; color: var(--accent); }
51
+ h4 { font-size: 1.05rem; margin: 20px 0 8px; color: var(--warn); }
52
+ p { margin: 8px 0; color: var(--muted); }
53
+ .subtitle { color: var(--muted); font-size: 1.1rem; margin-bottom: 32px; }
54
+ .mermaid { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 24px; margin: 20px 0; overflow-x: auto; position: relative; }
55
+ .mermaid.is-enhanced { padding: 0; overflow: hidden; min-height: 260px; }
56
+ .mermaid-viewport { padding: 54px 24px 24px; overflow: hidden; cursor: grab; touch-action: none; min-height: 260px; }
57
+ .mermaid-viewport.is-dragging { cursor: grabbing; }
58
+ .mermaid-viewport svg { max-width: none !important; height: auto; transform-origin: 0 0; transition: transform 120ms ease; }
59
+ .mermaid-toolbar { position: absolute; top: 10px; right: 10px; z-index: 3; display: flex; align-items: center; gap: 6px; padding: 6px; background: rgba(15,23,42,0.92); border: 1px solid var(--border); border-radius: 8px; box-shadow: 0 8px 24px rgba(0,0,0,0.28); }
60
+ .mermaid-toolbar button, .mermaid-toolbar .zoom-level { height: 28px; min-width: 32px; border: 1px solid var(--border); border-radius: 6px; background: #1e293b; color: var(--text); font: 600 0.78rem system-ui, sans-serif; display: inline-flex; align-items: center; justify-content: center; }
61
+ .mermaid-toolbar button { cursor: pointer; }
62
+ .mermaid-toolbar button:hover { border-color: var(--accent); color: var(--accent); }
63
+ .mermaid-toolbar .zoom-level { min-width: 52px; color: var(--muted); background: transparent; }
64
+ .call-table { width: 100%; border-collapse: collapse; margin: 16px 0; font-size: 0.92rem; }
65
+ .call-table th { background: #1a2744; color: var(--accent); text-align: left; padding: 10px 14px; border: 1px solid var(--border); }
66
+ .call-table td { padding: 8px 14px; border: 1px solid var(--border); vertical-align: top; }
67
+ .call-table tr:nth-child(even) { background: rgba(255,255,255,0.02); }
68
+ .tag { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 0.8rem; font-weight: 600; }
69
+ .tag-async { background: #7c3aed33; color: #a78bfa; }
70
+ .tag-class { background: #05966933; color: var(--ok); }
71
+ .tag-func { background: #2563eb33; color: var(--accent); }
72
+ .tag-cmd { background: #d9770633; color: var(--warn); }
73
+ .tag-endpoint { background: #dc262633; color: var(--err); }
74
+ .tag-hook { background: #db277733; color: #f472b6; }
75
+ .card { background: var(--surface); border: 1px solid var(--border); border-radius: 10px; padding: 20px; margin: 16px 0; }
76
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(340px, 1fr)); gap: 16px; margin: 16px 0; }
77
+ .arrow-chain { font-family: 'Fira Code', monospace; font-size: 0.85rem; color: var(--accent); padding: 10px; background: rgba(56,189,248,0.06); border-radius: 6px; }
78
+ code { font-family: 'Fira Code', 'Cascadia Code', monospace; background: rgba(255,255,255,0.06); padding: 1px 6px; border-radius: 3px; font-size: 0.88em; }
79
+ ul, ol { margin: 8px 0 8px 24px; color: var(--muted); }
80
+ li { margin: 4px 0; }
81
+ a { color: var(--accent); }
82
+ hr { border: none; border-top: 1px solid var(--border); margin: 40px 0; }
83
+ .nav { position: sticky; top: 0; background: var(--bg); z-index: 10; padding: 12px 0; border-bottom: 1px solid var(--border); display: flex; gap: 20px; flex-wrap: wrap; font-size: 0.9rem; }
84
+ .nav a { text-decoration: none; }
85
+ .nav a:hover { text-decoration: underline; }
86
+ @media (max-width: 768px) { .container { padding: 16px; } h1 { font-size: 1.8rem; } }
87
+ """
88
+
89
+
90
+ # ──────────────────────────────────────────────
91
+ # 2. Data loading and normalization helpers
92
+ # ──────────────────────────────────────────────
93
+
94
+ def read_json(path: str | Path, default=None):
95
+ """Read JSON with a useful error message."""
96
+ if not path:
97
+ return default
98
+ path = Path(path)
99
+ if not path.exists():
100
+ return default
101
+ try:
102
+ return json.loads(path.read_text(encoding="utf-8"))
103
+ except json.JSONDecodeError as exc:
104
+ raise SystemExit(f"ERROR: invalid JSON in {path}: {exc}") from exc
105
+
106
+
107
+ def first_present(mapping: dict, *keys, default=None):
108
+ """Return the first non-empty value for any candidate key."""
109
+ for key in keys:
110
+ if key in mapping and mapping[key] not in (None, ""):
111
+ return mapping[key]
112
+ return default
113
+
114
+
115
+ def first_list(*values) -> list:
116
+ """Return the first list from a set of possible schema locations."""
117
+ for value in values:
118
+ if isinstance(value, list):
119
+ return value
120
+ return []
121
+
122
+
123
+ def to_float(value, default: float = 0.0) -> float:
124
+ """Convert graph numeric fields that may be serialized as strings."""
125
+ try:
126
+ return float(value)
127
+ except (TypeError, ValueError):
128
+ return default
129
+
130
+
131
+ def endpoint_id(value) -> str:
132
+ """Normalize edge endpoints that may be strings or node-like objects."""
133
+ if isinstance(value, dict):
134
+ value = first_present(value, "id", "node_id", "key", "name", "qualified_name")
135
+ return str(value or "")
136
+
137
+
138
+ def normalize_node(raw: dict, index: int) -> dict:
139
+ """Normalize a graphify node across common graph.json schema variants."""
140
+ node = dict(raw)
141
+ node_id = first_present(
142
+ node,
143
+ "id",
144
+ "node_id",
145
+ "key",
146
+ "uid",
147
+ "name",
148
+ "qualified_name",
149
+ "fqname",
150
+ "symbol",
151
+ default=f"node_{index + 1}",
152
+ )
153
+ source_file = first_present(
154
+ node,
155
+ "source_file",
156
+ "file",
157
+ "file_path",
158
+ "filepath",
159
+ "path",
160
+ "module_path",
161
+ "defined_in",
162
+ default="",
163
+ )
164
+ label = first_present(
165
+ node,
166
+ "label",
167
+ "display_name",
168
+ "title",
169
+ "name",
170
+ "qualified_name",
171
+ "fqname",
172
+ "symbol",
173
+ default=node_id,
174
+ )
175
+ community = first_present(
176
+ node,
177
+ "community",
178
+ "community_id",
179
+ "cluster",
180
+ "cluster_id",
181
+ "group",
182
+ "group_id",
183
+ "modularity_class",
184
+ default="unknown",
185
+ )
186
+ node_type = first_present(node, "node_type", "kind", "type", "category", default="")
187
+ file_type = first_present(node, "file_type", "content_type", "artifact_type", default="")
188
+ if not file_type:
189
+ suffix = Path(str(source_file)).suffix.lower()
190
+ file_type = "document" if suffix in {".md", ".mdx", ".rst", ".txt"} else "code"
191
+
192
+ node["id"] = str(node_id)
193
+ node["label"] = str(label)
194
+ node["community"] = community
195
+ node["source_file"] = str(source_file or "")
196
+ node["node_type"] = str(node_type or "")
197
+ node["file_type"] = str(file_type or "code")
198
+ return node
199
+
200
+
201
+ def normalize_edge(raw: dict, index: int) -> dict | None:
202
+ """Normalize graphify edges while preserving original fields."""
203
+ edge = dict(raw)
204
+ source = endpoint_id(first_present(edge, "source", "src", "from", "from_id", "start", "u"))
205
+ target = endpoint_id(first_present(edge, "target", "dst", "to", "to_id", "end", "v"))
206
+ if not source or not target:
207
+ return None
208
+
209
+ relation = first_present(edge, "relation", "type", "kind", "label", "predicate", default="relates")
210
+ confidence = first_present(edge, "confidence", "evidence", "provenance", default="EXTRACTED")
211
+ score = first_present(edge, "confidence_score", "score", "weight", "probability", default=1.0)
212
+
213
+ edge["id"] = str(first_present(edge, "id", "edge_id", default=f"edge_{index + 1}"))
214
+ edge["source"] = source
215
+ edge["target"] = target
216
+ edge["relation"] = str(relation or "relates").lower()
217
+ edge["confidence"] = str(confidence or "EXTRACTED").upper()
218
+ edge["confidence_score"] = to_float(score, 1.0)
219
+ return edge
220
+
221
+
222
+ def _node_link_payload(data: dict) -> tuple[list, list] | None:
223
+ """Read current graphify graph.json via NetworkX's node-link parser."""
224
+ if not isinstance(data.get("nodes"), list):
225
+ return None
226
+ if not isinstance(data.get("links"), list) and not isinstance(data.get("edges"), list):
227
+ return None
228
+
229
+ try:
230
+ # Shared loader normalizes the raw writer's "edges" key to "links"
231
+ # before parsing; without it an edges-keyed payload raised
232
+ # KeyError: 'links' and this function silently returned None even
233
+ # though the shape check above accepts "edges" (#2212).
234
+ from graphify.paths import load_node_link_graph
235
+
236
+ # Force directed/multigraph so the stored caller->callee direction and
237
+ # parallel edges survive the round-trip; mirrors affected.py,
238
+ # serve.py and cli.py (#1174) and the directed-view fix for
239
+ # path/shortest_path (#2487, #2309). graph.json is written with
240
+ # "directed": false for backward compatibility, so without this
241
+ # networkx returns an undirected Graph and edge orientation becomes
242
+ # arbitrary -- which silently swaps the Caller and Callee columns of
243
+ # the call table and drops parallel edges. The _src/_tgt override
244
+ # below still wins on legacy marker files.
245
+ graph = load_node_link_graph({**data, "directed": True, "multigraph": True})
246
+ except Exception:
247
+ return None
248
+
249
+ nodes = []
250
+ for node_id, attrs in graph.nodes(data=True):
251
+ node = dict(attrs)
252
+ node["id"] = node_id
253
+ nodes.append(node)
254
+
255
+ edges = []
256
+ for index, (source, target, attrs) in enumerate(graph.edges(data=True), 1):
257
+ edge = dict(attrs)
258
+ edge["source"] = edge.get("_src", edge.get("source", source))
259
+ edge["target"] = edge.get("_tgt", edge.get("target", target))
260
+ edge.setdefault("id", f"edge_{index}")
261
+ edges.append(edge)
262
+ return nodes, edges
263
+
264
+
265
+ def load_graph(path: str | Path) -> tuple:
266
+ """Load graph.json. Returns normalized (nodes, edges, hyperedges, metadata)."""
267
+ if path:
268
+ from graphify.security import check_graph_file_size_cap
269
+ try:
270
+ check_graph_file_size_cap(Path(path))
271
+ except ValueError as exc:
272
+ raise SystemExit(f"ERROR: {exc}") from exc
273
+ data = read_json(path)
274
+ if not isinstance(data, dict):
275
+ raise SystemExit(f"ERROR: graph file must contain a JSON object: {path}")
276
+
277
+ graph_block = data.get("graph") if isinstance(data.get("graph"), dict) else {}
278
+ meta_block = data.get("metadata") if isinstance(data.get("metadata"), dict) else {}
279
+
280
+ node_link = _node_link_payload(data)
281
+ if node_link:
282
+ raw_nodes, raw_edges = node_link
283
+ else:
284
+ raw_nodes = first_list(data.get("nodes"), data.get("vertices"), graph_block.get("nodes"), graph_block.get("vertices"))
285
+ raw_edges = first_list(data.get("links"), data.get("edges"), graph_block.get("links"), graph_block.get("edges"))
286
+ hyperedges = first_list(data.get("hyperedges"), graph_block.get("hyperedges"), data.get("groups"), graph_block.get("groups"))
287
+
288
+ nodes = [normalize_node(n, i) for i, n in enumerate(raw_nodes) if isinstance(n, dict)]
289
+ edges = []
290
+ for i, raw_edge in enumerate(raw_edges):
291
+ if not isinstance(raw_edge, dict):
292
+ continue
293
+ edge = normalize_edge(raw_edge, i)
294
+ if edge:
295
+ edges.append(edge)
296
+
297
+ meta = dict(graph_block)
298
+ meta.update(meta_block)
299
+ for key in ("built_at_commit", "commit", "project_name", "repo", "repository", "language_breakdown"):
300
+ if data.get(key) and not meta.get(key):
301
+ meta[key] = data.get(key)
302
+ if meta.get("commit") and not meta.get("built_at_commit"):
303
+ meta["built_at_commit"] = meta["commit"]
304
+
305
+ return nodes, edges, hyperedges, meta
306
+
307
+
308
+ def load_labels(path: str | Path | None) -> dict:
309
+ """Load community labels from .graphify_labels.json, tolerating wrapper keys."""
310
+ data = read_json(path, default={})
311
+ if not isinstance(data, dict):
312
+ return {}
313
+ if isinstance(data.get("labels"), dict):
314
+ data = data["labels"]
315
+ if isinstance(data.get("communities"), dict):
316
+ data = data["communities"]
317
+ labels = {}
318
+ for key, value in data.items():
319
+ if isinstance(value, dict):
320
+ value = first_present(value, "label", "name", "title", default=key)
321
+ labels[str(key)] = str(value)
322
+ return labels
323
+
324
+
325
+ def load_sections(path: str | Path | None) -> list:
326
+ """Load section definitions from JSON file."""
327
+ data = read_json(path, default=[])
328
+ if isinstance(data, dict) and isinstance(data.get("sections"), list):
329
+ data = data["sections"]
330
+ if not isinstance(data, list):
331
+ raise SystemExit(f"ERROR: sections file must contain a JSON array: {path}")
332
+ return data
333
+
334
+
335
+ def load_report(path: str | Path | None) -> str:
336
+ """Load GRAPH_REPORT.md if it exists."""
337
+ if path and os.path.exists(path):
338
+ return Path(path).read_text(encoding="utf-8")
339
+ return ""
340
+
341
+
342
+ # ──────────────────────────────────────────────
343
+ # 3. Mermaid-safe label helpers
344
+ # ──────────────────────────────────────────────
345
+
346
+ def safe_mermaid_text(text: str) -> str:
347
+ """Sanitize text for use inside a Mermaid node label.
348
+
349
+ Replaces characters that Mermaid interprets as syntax:
350
+ - -> (edge arrow) -> text
351
+ - # (comment) -> removed
352
+ - {} (shape syntax) -> removed
353
+ - backticks -> removed
354
+ - " -> '
355
+ - HTML metacharacters -> entities
356
+ """
357
+ text = str(text or "")
358
+ text = text.replace('"', "'")
359
+ text = text.replace('`', '')
360
+ text = text.replace('#', '')
361
+ text = text.replace('|', ' ')
362
+ text = text.replace('{', '').replace('}', '')
363
+ text = text.replace("->>", " to ").replace("-->", " to ").replace("->", " to ")
364
+ text = " ".join(text.split())
365
+ return escape(text, quote=False)
366
+
367
+
368
+ def html_comment_text(text: str) -> str:
369
+ """Keep generated HTML comments well-formed."""
370
+ return str(text or "").replace("--", "- -").replace("\n", " ")
371
+
372
+
373
+ def stable_ascii_id(raw: str, prefix: str = "node", limit: int = 48) -> str:
374
+ """Build a Mermaid-safe ASCII identifier with a hash suffix to avoid collisions."""
375
+ raw = str(raw or "")
376
+ digest = hashlib.sha1(raw.encode("utf-8"), usedforsecurity=False).hexdigest()[:8]
377
+ slug = re.sub(r"[^A-Za-z0-9_]+", "_", raw)
378
+ slug = re.sub(r"_+", "_", slug).strip("_")
379
+ if not slug:
380
+ slug = prefix
381
+ if slug[0].isdigit():
382
+ slug = f"{prefix}_{slug}"
383
+ return f"{slug[:limit].rstrip('_')}_{digest}"
384
+
385
+
386
+ def node_mermaid_id(node: dict) -> str:
387
+ """Generate a safe Mermaid node ID from a graph node.
388
+
389
+ Mermaid IDs must match [a-zA-Z][a-zA-Z0-9_]* — no dots, hyphens, slashes.
390
+ """
391
+ return stable_ascii_id(node.get("id", "unknown"), "node")
392
+
393
+
394
+ def mermaid_section_id(section_id: str) -> str:
395
+ """Convert a section ID (like 'cli-entry') to a safe Mermaid ID (like 'CLI_ENTRY')."""
396
+ return stable_ascii_id(section_id, "section").upper()
397
+
398
+
399
+ def safe_file_path(path: str) -> str:
400
+ """Return a short, safe display path."""
401
+ # Truncate long paths for display
402
+ parts = path.split("/")
403
+ if len(parts) > 3:
404
+ return "/".join(parts[-3:])
405
+ return path
406
+
407
+
408
+ def safe_filename(text: str, fallback: str = "project") -> str:
409
+ """Create a conservative filename stem from a project name."""
410
+ stem = re.sub(r"[^A-Za-z0-9._-]+", "-", str(text or "")).strip("-._")
411
+ return stem or fallback
412
+
413
+
414
+ def infer_project_name(graph_path: str, meta: dict) -> str:
415
+ """Infer a display project name when graph metadata does not include one."""
416
+ if meta.get("project_name"):
417
+ return meta["project_name"]
418
+ path = Path(graph_path).resolve()
419
+ if path.parent.name == GRAPHIFY_OUT_NAME and len(path.parents) > 1:
420
+ return path.parents[1].name
421
+ return path.parent.name or "Project"
422
+
423
+
424
+ def resolve_graphify_paths(args) -> dict:
425
+ """Resolve project root, graphify output dir, and optional files."""
426
+ base = Path(args.project).expanduser() if args.project else Path.cwd()
427
+ if args.graphify_out:
428
+ graphify_out = Path(args.graphify_out).expanduser()
429
+ elif args.graph:
430
+ graphify_out = Path(args.graph).expanduser().parent
431
+ elif (base / "graph.json").exists():
432
+ graphify_out = base
433
+ else:
434
+ graphify_out = base / GRAPHIFY_OUT
435
+
436
+ project_root = graphify_out.parent if graphify_out.name == GRAPHIFY_OUT_NAME else base
437
+ graph = Path(args.graph).expanduser() if args.graph else graphify_out / "graph.json"
438
+ report = Path(args.report).expanduser() if args.report else graphify_out / "GRAPH_REPORT.md"
439
+ labels = Path(args.labels).expanduser() if args.labels else graphify_out / ".graphify_labels.json"
440
+ sections = Path(args.sections).expanduser() if args.sections else None
441
+ return {
442
+ "base": project_root,
443
+ "graphify_out": graphify_out,
444
+ "graph": graph,
445
+ "report": report,
446
+ "labels": labels,
447
+ "sections": sections,
448
+ }
449
+
450
+
451
+ def is_zh(lang: str) -> bool:
452
+ """Return true when localized strings should be Chinese."""
453
+ return (lang or "").lower().startswith("zh")
454
+
455
+
456
+ def pick_text(lang: str, zh: str, en: str) -> str:
457
+ """Small localization helper for generated copy."""
458
+ return zh if is_zh(lang) else en
459
+
460
+
461
+ def detect_lang(lang: str, nodes: list, labels: dict) -> str:
462
+ """Resolve auto language from labels and node names."""
463
+ if lang and lang.lower() != "auto":
464
+ return lang
465
+ sample = " ".join(
466
+ list(labels.values())[:50]
467
+ + [str(n.get("label", "")) for n in nodes[:200]]
468
+ + [str(n.get("source_file", "")) for n in nodes[:100]]
469
+ )
470
+ return "zh-CN" if re.search(r"[\u4e00-\u9fff]", sample) else "en"
471
+
472
+
473
+ def truncate_text(text: str, limit: int) -> str:
474
+ """Truncate without splitting Mermaid syntax."""
475
+ text = " ".join(str(text or "").split())
476
+ if len(text) <= limit:
477
+ return text
478
+ return text[: max(0, limit - 3)].rstrip() + "..."
479
+
480
+
481
+ def humanize_label(label: str, source_file: str = "") -> str:
482
+ """Convert graph labels into short labels people can scan in a diagram."""
483
+ label = str(label or "").strip()
484
+ if not label:
485
+ return Path(source_file).name if source_file else "Unknown"
486
+ if label.startswith(".") and label.endswith("()"):
487
+ return label[1:]
488
+ if label.endswith((".py", ".ts", ".tsx", ".js", ".jsx", ".go", ".rs", ".java", ".rb")):
489
+ return Path(label).name
490
+ if "_" in label and " " not in label and len(label) > 28:
491
+ parts = [p for p in label.split("_") if p]
492
+ if parts:
493
+ label = " ".join(parts[-3:])
494
+ return truncate_text(label, 42)
495
+
496
+
497
+ def node_kind(node: dict) -> str:
498
+ """Classify a graph node for Mermaid styling and table tags."""
499
+ label = str(node.get("label") or node.get("id") or "").lower()
500
+ source_file = str(node.get("source_file") or "").lower()
501
+ file_type = str(node.get("file_type") or "").lower()
502
+ node_type = str(node.get("node_type") or "").lower()
503
+ if node_type in {"class", "klass", "struct", "interface", "enum", "trait", "model"}:
504
+ return "klass"
505
+ if node_type in {"module", "file", "package", "namespace"}:
506
+ return "module"
507
+ if node_type in {"endpoint", "route", "api", "handler", "controller"}:
508
+ return "api"
509
+ if node_type in {"test", "spec"}:
510
+ return "test"
511
+ if node_type in {"component", "hook", "view", "page"}:
512
+ return "ui"
513
+ if file_type in {"rationale", "document"}:
514
+ return "concept"
515
+ if "test" in source_file or label.startswith("test_") or "spec" in source_file:
516
+ return "test"
517
+ if any(word in label for word in ("endpoint", "router", "api", "route")):
518
+ return "api"
519
+ if any(word in label for word in ("cli", "command", "click", "typer")):
520
+ return "entry"
521
+ if any(word in label for word in ("async", "await", "stream", "sse")):
522
+ return "async"
523
+ raw_label = str(node.get("label") or "")
524
+ hook_like = raw_label.startswith("use") and len(raw_label) > 3 and (raw_label[3].isupper() or raw_label[3] in "_-")
525
+ if any(word in label for word in ("component", "props", "hook", "store")) or hook_like or source_file.endswith((".tsx", ".jsx", ".vue", ".svelte")):
526
+ return "ui"
527
+ raw = raw_label
528
+ if raw[:1].isupper() and not raw.endswith("()"):
529
+ return "klass"
530
+ if raw.endswith((".py", ".ts", ".tsx", ".js", ".jsx", ".go", ".rs", ".java", ".kt", ".rb", ".php", ".cs", ".swift", ".vue", ".svelte")):
531
+ return "module"
532
+ return "function"
533
+
534
+
535
+ def relation_label(relation: str, lang: str) -> str:
536
+ """Map graph edge relation names to short diagram labels."""
537
+ relation = str(relation or "").strip()
538
+ zh = {
539
+ "calls": "调用",
540
+ "uses": "使用",
541
+ "imports": "导入",
542
+ "imports_from": "导入",
543
+ "method": "方法",
544
+ "contains": "包含",
545
+ "rationale_for": "说明",
546
+ "conceptually_related_to": "相关",
547
+ "participate_in": "参与",
548
+ "form": "组成",
549
+ }
550
+ en = {
551
+ "calls": "calls",
552
+ "uses": "uses",
553
+ "imports": "imports",
554
+ "imports_from": "imports",
555
+ "method": "method",
556
+ "contains": "contains",
557
+ "rationale_for": "explains",
558
+ "conceptually_related_to": "relates",
559
+ "participate_in": "joins",
560
+ "form": "forms",
561
+ }
562
+ mapped = (zh if is_zh(lang) else en).get(relation, relation.replace("_", " "))
563
+ return safe_mermaid_text(mapped)
564
+
565
+
566
+ def preferred_edges(edges: list, allow_structure: bool = False) -> list:
567
+ """Filter to edges that make a readable call-flow diagram."""
568
+ primary = {"calls", "uses", "method", "imports", "imports_from"}
569
+ secondary = {"contains", "rationale_for", "conceptually_related_to"}
570
+ selected = []
571
+ for edge in edges:
572
+ if not should_include_edge(edge):
573
+ continue
574
+ relation = edge.get("relation", "")
575
+ if relation in primary or (allow_structure and relation in secondary):
576
+ selected.append(edge)
577
+ if selected:
578
+ return selected
579
+ return [edge for edge in edges if should_include_edge(edge)]
580
+
581
+
582
+ def edge_score(edge: dict) -> float:
583
+ """Rank edges by confidence and usefulness for diagrams."""
584
+ relation = edge.get("relation", "")
585
+ score = to_float(edge.get("confidence_score", 1.0), 1.0)
586
+ if str(edge.get("confidence", "")).upper() == "EXTRACTED":
587
+ score += 2.0
588
+ if relation in {"calls", "uses", "method"}:
589
+ score += 1.0
590
+ elif relation in {"imports", "imports_from"}:
591
+ score += 0.6
592
+ elif relation == "contains":
593
+ score -= 0.2
594
+ elif relation == "rationale_for":
595
+ score -= 0.6
596
+ return score
597
+
598
+
599
+ def mermaid_init(scale: float, direction: str = "LR") -> str:
600
+ """Return a Mermaid init directive that scales diagrams using Mermaid config."""
601
+ scale = max(0.65, min(float(scale or 1.0), 1.8))
602
+ config = {
603
+ "theme": "dark",
604
+ "themeVariables": {
605
+ "fontSize": f"{round(15 * scale, 1)}px",
606
+ "fontFamily": "Segoe UI, system-ui, sans-serif",
607
+ "primaryColor": "#1e293b",
608
+ "primaryTextColor": "#e2e8f0",
609
+ "primaryBorderColor": "#38bdf8",
610
+ "secondaryColor": "#0f172a",
611
+ "tertiaryColor": "#334155",
612
+ "lineColor": "#64748b",
613
+ "textColor": "#e2e8f0",
614
+ },
615
+ "flowchart": {
616
+ "htmlLabels": True,
617
+ "curve": "basis",
618
+ "nodeSpacing": round(48 * scale),
619
+ "rankSpacing": round(64 * scale),
620
+ "padding": round(14 * scale),
621
+ "diagramPadding": round(10 * scale),
622
+ "useMaxWidth": True,
623
+ },
624
+ }
625
+ return f"%%{{init: {json.dumps(config, ensure_ascii=False)}}}%%\nflowchart {direction}"
626
+
627
+
628
+ def mermaid_class_defs() -> list:
629
+ """Shared Mermaid-native styles for readable diagrams."""
630
+ return [
631
+ " classDef entry fill:#422006,stroke:#fbbf24,color:#fde68a,stroke-width:1px;",
632
+ " classDef api fill:#450a0a,stroke:#f87171,color:#fee2e2,stroke-width:1px;",
633
+ " classDef async fill:#2e1065,stroke:#a78bfa,color:#ede9fe,stroke-width:1px;",
634
+ " classDef klass fill:#064e3b,stroke:#34d399,color:#d1fae5,stroke-width:1px;",
635
+ " classDef ui fill:#831843,stroke:#f472b6,color:#fce7f3,stroke-width:1px;",
636
+ " classDef module fill:#172554,stroke:#60a5fa,color:#dbeafe,stroke-width:1px;",
637
+ " classDef test fill:#3f3f46,stroke:#a1a1aa,color:#f4f4f5,stroke-width:1px;",
638
+ " classDef concept fill:#292524,stroke:#a8a29e,color:#fafaf9,stroke-dasharray:4 3;",
639
+ " classDef function fill:#0f172a,stroke:#38bdf8,color:#e0f2fe,stroke-width:1px;",
640
+ ]
641
+
642
+
643
+ # ──────────────────────────────────────────────
644
+ # 4. Community and section indexing
645
+ # ──────────────────────────────────────────────
646
+
647
+ def build_community_index(nodes: list) -> dict:
648
+ """Map community_id (str) -> list of nodes."""
649
+ idx = defaultdict(list)
650
+ for n in nodes:
651
+ cid = str(n.get("community", "unknown"))
652
+ idx[cid].append(n)
653
+ return idx
654
+
655
+
656
+ def html_anchor_id(raw: str, fallback: str, used: set) -> str:
657
+ """Generate a stable, unique HTML anchor ID."""
658
+ raw = str(raw or fallback or "")
659
+ base = re.sub(r"[^a-z0-9]+", "-", raw.lower()).strip("-")
660
+ if not base:
661
+ base = re.sub(r"[^a-z0-9]+", "-", str(fallback or "section").lower()).strip("-")
662
+ if not base:
663
+ base = "section"
664
+ base = base[:48].strip("-") or "section"
665
+ candidate = base
666
+ if candidate in used:
667
+ candidate = f"{base}-{hashlib.sha1(raw.encode('utf-8'), usedforsecurity=False).hexdigest()[:6]}"
668
+ suffix = 2
669
+ while candidate in used:
670
+ candidate = f"{base}-{suffix}"
671
+ suffix += 1
672
+ used.add(candidate)
673
+ return candidate
674
+
675
+
676
+ def normalize_communities(value) -> list:
677
+ """Normalize section community lists from JSON or simple strings."""
678
+ if isinstance(value, list):
679
+ return value
680
+ if value in (None, ""):
681
+ return []
682
+ if isinstance(value, str):
683
+ return [part.strip() for part in value.split(",") if part.strip()]
684
+ return [value]
685
+
686
+
687
+ def normalize_sections(sections: list, lang: str) -> list:
688
+ """Ensure sections have safe unique IDs and an overview section first."""
689
+ overview_name = pick_text(lang, "架构总览", "Architecture Overview")
690
+ normalized = [{"id": "overview", "name": overview_name, "communities": []}]
691
+ used = {"overview", "hyperedges", "stats"}
692
+
693
+ for index, raw in enumerate(sections or [], 1):
694
+ if not isinstance(raw, dict):
695
+ continue
696
+ raw_id = str(raw.get("id") or raw.get("key") or raw.get("name") or f"section-{index}")
697
+ raw_name = str(raw.get("name") or raw.get("label") or raw_id)
698
+ if raw_id.lower() == "overview":
699
+ normalized[0]["name"] = raw_name or overview_name
700
+ continue
701
+
702
+ sid = html_anchor_id(raw_id, f"section-{index}", used)
703
+ normalized.append({
704
+ "id": sid,
705
+ "name": raw_name,
706
+ "communities": normalize_communities(raw.get("communities", raw.get("community"))),
707
+ })
708
+ return normalized
709
+
710
+
711
+ def label_for_community(cid: str, labels: dict, nodes: list, lang: str) -> str:
712
+ """Choose a readable section name for a community."""
713
+ if str(cid) in labels and labels[str(cid)]:
714
+ return labels[str(cid)]
715
+ keywords = section_keywords(nodes, 3)
716
+ if keywords:
717
+ return " ".join(word.title() for word in keywords[:3])
718
+ return pick_text(lang, f"社区 {cid}", f"Community {cid}")
719
+
720
+
721
+ SECTION_ARCHETYPES = [
722
+ (
723
+ "extract-pipeline",
724
+ "提取管线",
725
+ "Extraction Pipeline",
726
+ {
727
+ "extract", "extractor", "tree", "sitter", "parser", "language",
728
+ "python", "javascript", "typescript", "rust", "java", "go",
729
+ "ast", "calls", "imports", "multilang",
730
+ },
731
+ ),
732
+ (
733
+ "build-graph",
734
+ "图谱构建",
735
+ "Graph Build",
736
+ {
737
+ "build", "graph", "merge", "dedup", "node", "edge", "hyperedge",
738
+ "json", "schema", "normalize", "confidence",
739
+ },
740
+ ),
741
+ (
742
+ "analysis-clustering",
743
+ "分析聚类",
744
+ "Analysis & Clustering",
745
+ {
746
+ "cluster", "community", "leiden", "cohesion", "analyze", "god",
747
+ "surprise", "question", "query", "path", "explain", "benchmark",
748
+ },
749
+ ),
750
+ (
751
+ "outputs-docs",
752
+ "输出文档",
753
+ "Outputs & Docs",
754
+ {
755
+ "export", "html", "wiki", "obsidian", "canvas", "svg", "graphml",
756
+ "report", "callflow", "mermaid", "tree", "documentation",
757
+ },
758
+ ),
759
+ (
760
+ "cli-skills",
761
+ "CLI 与技能安装",
762
+ "CLI & Skill Installers",
763
+ {
764
+ "main", "install", "uninstall", "skill", "agent", "claude",
765
+ "codex", "opencode", "aider", "copilot", "kiro", "vscode",
766
+ "hook", "command",
767
+ },
768
+ ),
769
+ (
770
+ "ingest-cache-update",
771
+ "摄取与增量更新",
772
+ "Ingestion & Updates",
773
+ {
774
+ "ingest", "fetch", "download", "url", "html", "markdown",
775
+ "cache", "manifest", "watch", "update", "incremental",
776
+ "transcribe", "video", "audio", "google",
777
+ },
778
+ ),
779
+ (
780
+ "serve-api",
781
+ "服务 API",
782
+ "Serving API",
783
+ {
784
+ "serve", "api", "request", "response", "endpoint", "router",
785
+ "handle", "upload", "search", "delete", "enrich",
786
+ },
787
+ ),
788
+ (
789
+ "security-global",
790
+ "安全与全局图",
791
+ "Security & Global Graph",
792
+ {
793
+ "security", "safe", "ssrf", "xss", "path", "traversal",
794
+ "global", "prefix", "prune", "repo", "clone",
795
+ },
796
+ ),
797
+ (
798
+ "tests-fixtures",
799
+ "测试与样例",
800
+ "Tests & Fixtures",
801
+ {
802
+ "test", "tests", "fixture", "fixtures", "sample", "assert",
803
+ "pytest", "mock",
804
+ },
805
+ ),
806
+ ]
807
+
808
+
809
+ def _community_text(nodes: list, label: str = "") -> str:
810
+ parts = [label]
811
+ for node in nodes[:80]:
812
+ parts.append(str(node.get("label", "")))
813
+ parts.append(str(node.get("source_file", "")))
814
+ parts.append(str(node.get("node_type", "")))
815
+ parts.append(str(node.get("file_type", "")))
816
+ return " ".join(parts).lower()
817
+
818
+
819
+ def _keyword_score(text: str, keywords: set[str]) -> int:
820
+ score = 0
821
+ for keyword in keywords:
822
+ score += len(re.findall(rf"(?<![a-z0-9]){re.escape(keyword)}(?![a-z0-9])", text))
823
+ return score
824
+
825
+
826
+ def _rank_grouped_sections(grouped: dict, max_sections: int) -> tuple[list, list]:
827
+ """Return selected grouped sections and overflow communities."""
828
+ ranked = sorted(
829
+ grouped.values(),
830
+ key=lambda sec: (sec["priority"], -sec["node_count"], sec["id"]),
831
+ )
832
+ cap = max(1, int(max_sections or 15))
833
+ selected = ranked[:cap]
834
+ overflow = ranked[cap:]
835
+ overflow_communities = []
836
+ for sec in overflow:
837
+ overflow_communities.extend(sec["communities"])
838
+ return selected, overflow_communities
839
+
840
+
841
+ def derive_sections_from_communities(nodes: list, labels: dict, lang: str, max_sections: int) -> list:
842
+ """Derive architecture-oriented sections when no sections JSON is supplied."""
843
+ comm_idx = build_community_index(nodes)
844
+ sections = [{"id": "overview", "name": pick_text(lang, "架构总览", "Architecture Overview"), "communities": []}]
845
+ grouped = {}
846
+ unassigned = []
847
+
848
+ for cid, community_nodes in sorted(comm_idx.items(), key=lambda item: (-len(item[1]), str(item[0]))):
849
+ label = label_for_community(cid, labels, community_nodes, lang)
850
+ text = _community_text(community_nodes, label)
851
+ best = None
852
+ best_score = 0
853
+ for priority, (sid, zh_name, en_name, keywords) in enumerate(SECTION_ARCHETYPES):
854
+ score = _keyword_score(text, keywords)
855
+ if score > best_score:
856
+ best = (priority, sid, zh_name, en_name)
857
+ best_score = score
858
+
859
+ if best and best_score >= 2:
860
+ priority, sid, zh_name, en_name = best
861
+ sec = grouped.setdefault(
862
+ sid,
863
+ {
864
+ "id": sid,
865
+ "name": pick_text(lang, zh_name, en_name),
866
+ "communities": [],
867
+ "node_count": 0,
868
+ "priority": priority,
869
+ },
870
+ )
871
+ sec["communities"].append(cid)
872
+ sec["node_count"] += len(community_nodes)
873
+ else:
874
+ unassigned.append((cid, community_nodes, label))
875
+
876
+ selected, overflow_communities = _rank_grouped_sections(grouped, max(1, int(max_sections or 15)) - 1)
877
+ sections.extend(
878
+ {"id": sec["id"], "name": sec["name"], "communities": sec["communities"]}
879
+ for sec in selected
880
+ )
881
+
882
+ remaining_slots = max(0, int(max_sections or 15) - (len(sections) - 1) - 1)
883
+ for cid, community_nodes, label in unassigned[:remaining_slots]:
884
+ sections.append({"id": str(label or f"community-{cid}"), "name": label, "communities": [cid]})
885
+
886
+ other_communities = overflow_communities + [cid for cid, _, _ in unassigned[remaining_slots:]]
887
+ if other_communities:
888
+ sections.append({
889
+ "id": "other",
890
+ "name": pick_text(lang, "其他", "Other"),
891
+ "communities": other_communities,
892
+ })
893
+ return sections
894
+
895
+
896
+ def build_section_node_map(sections: list, comm_idx: dict) -> dict:
897
+ """Map section_id -> list of nodes belonging to its communities."""
898
+ section_nodes = {}
899
+ for sec in sections:
900
+ sid = sec["id"]
901
+ if sid == "overview":
902
+ section_nodes[sid] = []
903
+ continue
904
+ nodes = []
905
+ for cid in sec.get("communities", []):
906
+ nodes.extend(comm_idx.get(str(cid), []))
907
+ section_nodes[sid] = nodes
908
+ return section_nodes
909
+
910
+
911
+ def node_in_section(node_id: str, section_node_ids: set) -> bool:
912
+ """Check if a node belongs to a section."""
913
+ return node_id in section_node_ids
914
+
915
+
916
+ # ──────────────────────────────────────────────
917
+ # 5. Edge analysis
918
+ # ──────────────────────────────────────────────
919
+
920
+ def classify_edges(edges: list, section_nodes_map: dict) -> dict:
921
+ """Classify edges as intra-section or inter-section.
922
+
923
+ Returns:
924
+ {
925
+ "intra": {section_id: [edges]},
926
+ "inter": [edges],
927
+ "orphan": [edges] # one endpoint not in any section
928
+ }
929
+ """
930
+ # Build node -> section lookup
931
+ node_section = {}
932
+ for sid, nodes in section_nodes_map.items():
933
+ for n in nodes:
934
+ node_section[n.get("id")] = sid
935
+
936
+ intra = defaultdict(list)
937
+ inter = []
938
+ orphan = []
939
+
940
+ for e in edges:
941
+ src = e.get("source", "")
942
+ tgt = e.get("target", "")
943
+ src_sec = node_section.get(src)
944
+ tgt_sec = node_section.get(tgt)
945
+
946
+ if src_sec is None or tgt_sec is None:
947
+ orphan.append(e)
948
+ elif src_sec == tgt_sec:
949
+ intra[src_sec].append(e)
950
+ else:
951
+ inter.append(e)
952
+
953
+ return {"intra": dict(intra), "inter": inter, "orphan": orphan, "node_section": node_section}
954
+
955
+
956
+ def should_include_edge(edge: dict) -> bool:
957
+ """Decide whether to auto-include an edge in Mermaid output."""
958
+ conf = str(edge.get("confidence", "EXTRACTED")).upper()
959
+ score = to_float(edge.get("confidence_score", 1.0), 1.0)
960
+
961
+ if conf == "EXTRACTED":
962
+ return True
963
+ if conf == "INFERRED" and score >= 0.85:
964
+ return True
965
+ # Low-confidence INFERRED or AMBIGUOUS: comment out for LLM review
966
+ return False
967
+
968
+
969
+ # ──────────────────────────────────────────────
970
+ # 6. Mermaid diagram generators
971
+ # ──────────────────────────────────────────────
972
+
973
+ def node_degree_scores(edges: list) -> Counter:
974
+ """Score nodes by useful edge participation."""
975
+ scores = Counter()
976
+ for edge in edges:
977
+ score = edge_score(edge)
978
+ scores[edge.get("source", "")] += score
979
+ scores[edge.get("target", "")] += score
980
+ return scores
981
+
982
+
983
+ def node_importance(node: dict) -> float:
984
+ """Use graphify centrality fields when available."""
985
+ for key in ("pagerank", "page_rank", "pageRank", "rank", "centrality", "score"):
986
+ if key in node:
987
+ return to_float(node.get(key), 0.0)
988
+ return 0.0
989
+
990
+
991
+ def select_diagram_nodes(nodes: list, edges: list, max_nodes: int) -> list:
992
+ """Select a compact, connected subset of nodes for readable diagrams."""
993
+ node_by_id = {n.get("id"): n for n in nodes}
994
+ usable_edges = preferred_edges(edges, allow_structure=False)
995
+ if not usable_edges:
996
+ usable_edges = preferred_edges(edges, allow_structure=True)
997
+ scores = node_degree_scores(usable_edges)
998
+ outgoing = Counter(edge.get("source", "") for edge in usable_edges)
999
+ incoming = Counter(edge.get("target", "") for edge in usable_edges)
1000
+ selected = []
1001
+ seen = set()
1002
+
1003
+ def add_node(nid: str) -> bool:
1004
+ node = node_by_id.get(nid)
1005
+ if not node or nid in seen:
1006
+ return False
1007
+ kind = node_kind(node)
1008
+ if kind == "concept" and len(selected) >= max(4, max_nodes // 3):
1009
+ return False
1010
+ selected.append(node)
1011
+ seen.add(nid)
1012
+ return len(selected) >= max_nodes
1013
+
1014
+ # Start with likely entry points: nodes that call out more than they are called.
1015
+ entry_candidates = sorted(
1016
+ node_by_id,
1017
+ key=lambda nid: (-(outgoing[nid] - incoming[nid]), -outgoing[nid], str(nid)),
1018
+ )
1019
+ for nid in entry_candidates[: max(3, max_nodes // 3)]:
1020
+ if outgoing[nid] > 0 and add_node(nid):
1021
+ return selected
1022
+
1023
+ # Then pull in the most useful neighbors from the strongest edges.
1024
+ for edge in sorted(usable_edges, key=edge_score, reverse=True):
1025
+ for nid in (edge.get("source"), edge.get("target")):
1026
+ if add_node(nid):
1027
+ return selected
1028
+
1029
+ def fallback_key(node: dict) -> tuple:
1030
+ nid = node.get("id", "")
1031
+ kind_penalty = 1 if node_kind(node) == "concept" else 0
1032
+ return (
1033
+ kind_penalty,
1034
+ -scores.get(nid, 0),
1035
+ -node_importance(node),
1036
+ safe_file_path(node.get("source_file", "")),
1037
+ humanize_label(node.get("label", nid)),
1038
+ )
1039
+
1040
+ for node in sorted(nodes, key=fallback_key):
1041
+ nid = node.get("id")
1042
+ if nid not in seen:
1043
+ selected.append(node)
1044
+ seen.add(nid)
1045
+ if len(selected) >= max_nodes:
1046
+ break
1047
+ return selected
1048
+
1049
+
1050
+ def node_label(node: dict) -> str:
1051
+ """Build a readable Mermaid node label."""
1052
+ label = humanize_label(node.get("label") or node.get("id"), node.get("source_file", ""))
1053
+ source_file = safe_file_path(node.get("source_file", ""))
1054
+ if source_file and not label.endswith(Path(source_file).name):
1055
+ return f"{safe_mermaid_text(label)}<br/><small>{safe_mermaid_text(source_file)}</small>"
1056
+ return safe_mermaid_text(label)
1057
+
1058
+
1059
+ def group_nodes_by_file(nodes: list) -> dict:
1060
+ """Group selected nodes by source file for Mermaid subgraphs."""
1061
+ groups = defaultdict(list)
1062
+ for node in nodes:
1063
+ source_file = safe_file_path(node.get("source_file", "")) or "External / generated"
1064
+ groups[source_file].append(node)
1065
+ return dict(sorted(groups.items(), key=lambda item: (-len(item[1]), item[0])))
1066
+
1067
+
1068
+ def section_edge_summary(classified_edges: dict) -> dict:
1069
+ """Aggregate inter-section edge counts and relation names."""
1070
+ node_section = classified_edges.get("node_section", {})
1071
+ summary = defaultdict(lambda: {"count": 0, "relations": Counter()})
1072
+ for edge in classified_edges.get("inter", []):
1073
+ if not should_include_edge(edge):
1074
+ continue
1075
+ src_sec = node_section.get(edge.get("source"))
1076
+ tgt_sec = node_section.get(edge.get("target"))
1077
+ if not src_sec or not tgt_sec or src_sec == tgt_sec:
1078
+ continue
1079
+ key = (src_sec, tgt_sec)
1080
+ summary[key]["count"] += 1
1081
+ summary[key]["relations"][edge.get("relation", "relates")] += 1
1082
+ return summary
1083
+
1084
+
1085
+ def generate_overview_graph(sections: list, section_nodes_map: dict,
1086
+ classified_edges: dict, labels: dict, lang: str,
1087
+ diagram_scale: float) -> str:
1088
+ """Generate a readable section-level architecture overview."""
1089
+ lines = [mermaid_init(diagram_scale, "LR")]
1090
+ section_defs = [sec for sec in sections if sec["id"] != "overview"]
1091
+
1092
+ for sec in section_defs:
1093
+ sid = mermaid_section_id(sec["id"])
1094
+ node_count = len(section_nodes_map.get(sec["id"], []))
1095
+ label = (
1096
+ f"{safe_mermaid_text(sec.get('name', sec['id']))}"
1097
+ f"<br/><small>{node_count} {safe_mermaid_text('nodes')}</small>"
1098
+ )
1099
+ lines.append(f' {sid}("{label}")')
1100
+ lines.append(f" class {sid} module;")
1101
+
1102
+ aggregated = section_edge_summary(classified_edges)
1103
+ for (src, tgt), data in sorted(aggregated.items(), key=lambda item: item[1]["count"], reverse=True)[:12]:
1104
+ src_id = mermaid_section_id(src)
1105
+ tgt_id = mermaid_section_id(tgt)
1106
+ relation, _ = data["relations"].most_common(1)[0]
1107
+ label = relation_label(relation, lang)
1108
+ if data["count"] > 1:
1109
+ label = f"{label} x{data['count']}"
1110
+ lines.append(f" {src_id} -->|{label}| {tgt_id}")
1111
+
1112
+ if not aggregated and len(section_defs) > 1:
1113
+ for prev, cur in zip(section_defs, section_defs[1:]):
1114
+ lines.append(f" {mermaid_section_id(prev['id'])} -.-> {mermaid_section_id(cur['id'])}")
1115
+
1116
+ lines.extend(mermaid_class_defs())
1117
+ return "\n".join(lines)
1118
+
1119
+
1120
+ def generate_section_flowchart(section_id: str, section_name: str,
1121
+ nodes: list, edges: list, lang: str,
1122
+ diagram_scale: float, max_nodes: int,
1123
+ max_edges: int) -> str:
1124
+ """Generate a compact, human-readable call-flow chart for a section."""
1125
+ lines = [mermaid_init(diagram_scale, "LR")]
1126
+ lines.append(f" %% Section: {safe_mermaid_text(section_name)} ({len(nodes)} nodes, {len(edges)} edges)")
1127
+
1128
+ if not nodes:
1129
+ empty_label = pick_text(lang, f"{section_name} - 无节点", f"{section_name} - no nodes")
1130
+ lines.append(f' empty("{safe_mermaid_text(empty_label)}")')
1131
+ lines.extend(mermaid_class_defs())
1132
+ return "\n".join(lines)
1133
+
1134
+ selected_nodes = select_diagram_nodes(nodes, edges, max_nodes)
1135
+ selected_ids = {node.get("id") for node in selected_nodes}
1136
+ visible_edges = [
1137
+ edge for edge in preferred_edges(edges, allow_structure=False)
1138
+ if edge.get("source") in selected_ids and edge.get("target") in selected_ids
1139
+ ]
1140
+ if not visible_edges:
1141
+ visible_edges = [
1142
+ edge for edge in preferred_edges(edges, allow_structure=True)
1143
+ if edge.get("source") in selected_ids and edge.get("target") in selected_ids
1144
+ ]
1145
+
1146
+ groups = group_nodes_by_file(selected_nodes)
1147
+ class_lines = []
1148
+ for source_file, group in groups.items():
1149
+ group_id = node_mermaid_id({"id": f"{section_id}_{source_file}"})
1150
+ if len(groups) > 1 and len(group) > 1:
1151
+ lines.append(f' subgraph {group_id}["{safe_mermaid_text(source_file)}"]')
1152
+ indent = " "
1153
+ else:
1154
+ indent = " "
1155
+ for node in group:
1156
+ mid = node_mermaid_id(node)
1157
+ lines.append(f'{indent}{mid}("{node_label(node)}")')
1158
+ class_lines.append(f" class {mid} {node_kind(node)};")
1159
+ if len(groups) > 1 and len(group) > 1:
1160
+ lines.append(" end")
1161
+
1162
+ included = 0
1163
+ for edge in sorted(visible_edges, key=edge_score, reverse=True):
1164
+ if included >= max_edges:
1165
+ break
1166
+ src_id = node_mermaid_id({"id": edge.get("source", "")})
1167
+ tgt_id = node_mermaid_id({"id": edge.get("target", "")})
1168
+ rel = relation_label(edge.get("relation", ""), lang)
1169
+ lines.append(f" {src_id} -->|{rel}| {tgt_id}")
1170
+ included += 1
1171
+
1172
+ omitted_nodes = max(0, len(nodes) - len(selected_nodes))
1173
+ omitted_edges = max(0, len(visible_edges) - included)
1174
+ if omitted_nodes or omitted_edges:
1175
+ lines.append(f" %% Omitted for readability: {omitted_nodes} nodes, {omitted_edges} edges")
1176
+ lines.extend(class_lines)
1177
+ lines.extend(mermaid_class_defs())
1178
+ return "\n".join(lines)
1179
+
1180
+
1181
+ # ──────────────────────────────────────────────
1182
+ # 7. HTML generators
1183
+ # ──────────────────────────────────────────────
1184
+
1185
+ def generate_nav(sections: list) -> str:
1186
+ """Generate the sticky navigation bar."""
1187
+ links = []
1188
+ for sec in sections:
1189
+ links.append(f' <a href="#{escape(sec["id"], quote=True)}">{escape(sec["name"])}</a>')
1190
+ return '<div class="nav">\n' + "\n".join(links) + "\n</div>"
1191
+
1192
+
1193
+ def node_display_name(node: dict | None, fallback: str = "") -> str:
1194
+ """Readable node label for tables and summaries."""
1195
+ if not node:
1196
+ return str(fallback or "")
1197
+ label = str(node.get("label") or node.get("id") or fallback or "")
1198
+ return humanize_label(label, node.get("source_file", ""))
1199
+
1200
+
1201
+ def format_node_refs(node_ids: set, node_by_id: dict, lang: str, empty_text: str, limit: int = 3) -> str:
1202
+ """Render node references as readable labels instead of internal IDs."""
1203
+ if not node_ids:
1204
+ return escape(empty_text)
1205
+ parts = []
1206
+ for nid in sorted(node_ids, key=lambda item: node_display_name(node_by_id.get(item), item).lower())[:limit]:
1207
+ node = node_by_id.get(nid)
1208
+ label = node_display_name(node, nid)
1209
+ source = safe_file_path((node or {}).get("source_file", ""))
1210
+ if source:
1211
+ parts.append(f"<code>{escape(label)}</code><br><small style=\"color:var(--muted)\">{escape(source)}</small>")
1212
+ else:
1213
+ parts.append(f"<code>{escape(label)}</code>")
1214
+ if len(node_ids) > limit:
1215
+ parts.append(escape(pick_text(lang, f"+{len(node_ids) - limit} 个更多", f"+{len(node_ids) - limit} more")))
1216
+ return "<br>".join(parts)
1217
+
1218
+
1219
+ def generate_call_table_rows(
1220
+ nodes: list,
1221
+ section_edges: list,
1222
+ lang: str,
1223
+ all_edges: list | None = None,
1224
+ all_nodes: list | None = None,
1225
+ ) -> str:
1226
+ """Generate call table row scaffolding for a section's nodes.
1227
+
1228
+ The Caller/Callee columns make a claim about the whole graph ("External
1229
+ entry / no inbound edge"), so they must be computed from the whole graph.
1230
+ Built from ``section_edges`` alone they only see edges whose *both*
1231
+ endpoints sit in this section, so a node called from anywhere else is
1232
+ mislabelled an entry point. Section coverage makes that the common case
1233
+ rather than a corner case: only ``max_sections`` communities are rendered,
1234
+ so most callers are not in any rendered section at all.
1235
+
1236
+ ``all_edges``/``all_nodes`` are the full graph; ``all_nodes`` also lets
1237
+ out-of-section callers render as labels instead of raw node ids. Both
1238
+ default to None, preserving the previous behaviour for other callers.
1239
+ """
1240
+ if not nodes:
1241
+ return ""
1242
+
1243
+ # Build source/target lookup from edges
1244
+ node_by_id = {n.get("id"): n for n in (all_nodes or nodes)}
1245
+ callers = defaultdict(set)
1246
+ callees = defaultdict(set)
1247
+ for e in (all_edges if all_edges is not None else section_edges):
1248
+ src = e.get("source", "")
1249
+ tgt = e.get("target", "")
1250
+ if e.get("relation") in ("calls", "imports", "imports_from", "uses", "method", "indirect_call"):
1251
+ callers[tgt].add(src)
1252
+ callees[src].add(tgt)
1253
+
1254
+ rows = []
1255
+ for i, n in enumerate(nodes[:30], 1): # cap at 30 rows
1256
+ nid = n.get("id", "")
1257
+ label = n.get("label", nid)
1258
+ source_file = safe_file_path(n.get("source_file", ""))
1259
+ file_type = n.get("file_type", "code")
1260
+
1261
+ # Suggest a tag type based on file_type and label heuristics
1262
+ tag = _suggest_tag(label, file_type, lang, node_kind(n))
1263
+
1264
+ caller_text = format_node_refs(
1265
+ callers.get(nid, set()),
1266
+ node_by_id,
1267
+ lang,
1268
+ pick_text(lang, "外部入口 / 无直接入边", "External entry / no inbound edge"),
1269
+ )
1270
+ callee_text = format_node_refs(
1271
+ callees.get(nid, set()),
1272
+ node_by_id,
1273
+ lang,
1274
+ pick_text(lang, "无直接出边", "No direct outbound edge"),
1275
+ )
1276
+
1277
+ rows.append(f"""<tr>
1278
+ <td>{i}</td>
1279
+ <td><code>{escape(label)}</code><br><small style="color:var(--muted)">{escape(source_file)}</small></td>
1280
+ <td>{tag}</td>
1281
+ <td>{caller_text}</td>
1282
+ <td>{callee_text}</td>
1283
+ <td>{escape(_describe_node(label, source_file, file_type, lang))}</td>
1284
+ </tr>""")
1285
+
1286
+ return "\n".join(rows)
1287
+
1288
+
1289
+ def _suggest_tag(label: str, file_type: str, lang: str, kind: str = "") -> str:
1290
+ """Heuristic tag suggestion based on label name and file type."""
1291
+ lower = label.lower()
1292
+ names = {
1293
+ "concept": ("概念", "Concept", "tag-func"),
1294
+ "entry": ("入口", "Entry", "tag-cmd"),
1295
+ "api": ("API", "API", "tag-endpoint"),
1296
+ "async": ("异步", "Async", "tag-async"),
1297
+ "klass": ("类", "Class", "tag-class"),
1298
+ "ui": ("UI", "UI", "tag-hook"),
1299
+ "module": ("模块", "Module", "tag-class"),
1300
+ "test": ("测试", "Test", "tag-func"),
1301
+ "function": ("函数", "Function", "tag-func"),
1302
+ }
1303
+ if kind in names:
1304
+ zh, en, cls = names[kind]
1305
+ return f'<span class="tag {cls}">{pick_text(lang, zh, en)}</span>'
1306
+ if file_type == "rationale":
1307
+ return f'<span class="tag tag-func">{pick_text(lang, "概念", "Concept")}</span>'
1308
+ if any(kw in lower for kw in ("cli", "command", "scan", "serve", "chat", "config")):
1309
+ if "group" in lower or "command" in lower:
1310
+ return f'<span class="tag tag-cmd">{pick_text(lang, "CLI命令", "CLI")}</span>'
1311
+ if any(kw in lower for kw in ("router", "endpoint", "api", "/api/")):
1312
+ return f'<span class="tag tag-endpoint">{pick_text(lang, "API端点", "API")}</span>'
1313
+ if any(kw in lower for kw in ("async", "await", "stream")):
1314
+ return f'<span class="tag tag-async">{pick_text(lang, "异步", "Async")}</span>'
1315
+ if any(kw in lower for kw in ("class", "model", "schema", "dataclass", "pydantic")):
1316
+ return f'<span class="tag tag-class">{pick_text(lang, "类", "Class")}</span>'
1317
+ if any(kw in lower for kw in ("hook", "usestate", "useeffect", "store")):
1318
+ return '<span class="tag tag-hook">Hook</span>'
1319
+ if any(kw in lower for kw in ("component", "props", "tsx", "jsx", "render")):
1320
+ return f'<span class="tag tag-class">{pick_text(lang, "组件", "Component")}</span>'
1321
+ return f'<span class="tag tag-func">{pick_text(lang, "函数", "Function")}</span>'
1322
+
1323
+
1324
+ def _describe_node(label: str, source_file: str, file_type: str, lang: str) -> str:
1325
+ """Generate a compact human-readable description for a graph node."""
1326
+ lower = label.lower()
1327
+ source = source_file or pick_text(lang, "项目", "project")
1328
+ if file_type == "rationale":
1329
+ return pick_text(lang, f"设计说明:{label}", f"Design note for {label}.")
1330
+ if file_type == "document":
1331
+ return pick_text(lang, f"文档入口,描述 {label} 相关能力。", f"Documentation node describing {label}.")
1332
+ if label.endswith(".py") or label.endswith(".tsx") or label.endswith(".ts"):
1333
+ return pick_text(lang, f"{source} 中的模块文件,承载该层主要实现。", f"Module file in {source}.")
1334
+ if "config" in lower:
1335
+ return pick_text(lang, "读取、解析或持久化项目配置。", "Reads, resolves, or persists project configuration.")
1336
+ if "scan" in lower:
1337
+ return pick_text(lang, "触发项目扫描或处理扫描状态。", "Starts scanning or handles scan status.")
1338
+ if "ingest" in lower or "clone" in lower or "git" in lower:
1339
+ return pick_text(lang, "把本地目录或远程仓库转换为分析上下文。", "Turns a local path or remote repository into analysis context.")
1340
+ if "prompt" in lower:
1341
+ return pick_text(lang, "构造发送给 LLM 的结构化提示。", "Builds structured prompts for model calls.")
1342
+ if "analy" in lower:
1343
+ return pick_text(lang, "编排分析流程并产出结构化文档数据。", "Orchestrates analysis and returns structured documentation data.")
1344
+ if "graph" in lower or "dependency" in lower:
1345
+ return pick_text(lang, "构建依赖关系并提供排序或图形化数据。", "Builds dependency relationships and graph data.")
1346
+ if "export" in lower or "markdown" in lower or "html" in lower:
1347
+ return pick_text(lang, "将文档数据导出为目标格式。", "Exports documentation data to a target format.")
1348
+ if "chat" in lower or "rag" in lower or "retrieve" in lower:
1349
+ return pick_text(lang, "支撑检索增强问答或流式聊天。", "Supports retrieval-augmented Q&A or streaming chat.")
1350
+ if "wiki" in lower or "page" in lower or "sidebar" in lower:
1351
+ return pick_text(lang, "组织文档页面、侧边栏或内容读取。", "Organizes documentation pages, navigation, or content lookup.")
1352
+ if "cache" in lower or "hash" in lower:
1353
+ return pick_text(lang, "缓存分析结果或生成缓存键。", "Caches analysis results or computes cache keys.")
1354
+ if "test" in lower:
1355
+ return pick_text(lang, "验证导入、入口点或版本等基础行为。", "Verifies imports, entry points, or version behavior.")
1356
+ return pick_text(lang, f"{source} 中的 {label} 节点。", f"{label} node in {source}.")
1357
+
1358
+
1359
+ def generate_header(sections: list, meta: dict, lang: str) -> str:
1360
+ """Generate the HTML header, title, subtitle, and nav."""
1361
+ project_name = str(meta.get("project_name", "Project"))
1362
+ commit = str(meta.get("built_at_commit", "unknown"))[:7]
1363
+
1364
+ if lang.startswith("zh"):
1365
+ title = f"{project_name} — 完整调用流程与架构文档"
1366
+ subtitle = (
1367
+ f"由 graphify 知识图谱生成:{meta.get('node_count', '?')} 个节点、"
1368
+ f"{meta.get('edge_count', '?')} 条边、{meta.get('community_count', '?')} 个社区。"
1369
+ f"Commit: {commit}"
1370
+ )
1371
+ else:
1372
+ title = f"{project_name} — Complete Call Flow & Architecture Documentation"
1373
+ subtitle = (
1374
+ f"Generated from graphify knowledge graph: {meta.get('node_count', '?')} nodes, "
1375
+ f"{meta.get('edge_count', '?')} edges, {meta.get('community_count', '?')} communities. "
1376
+ f"Commit: {commit}"
1377
+ )
1378
+
1379
+ return f"""<h1>{escape(title)}</h1>
1380
+ <p class="subtitle">{escape(subtitle)}</p>
1381
+
1382
+ {generate_nav(sections)}
1383
+ """
1384
+
1385
+
1386
+ def derive_flow_chain(sections: list, classified_edges: dict) -> str:
1387
+ """Derive a readable section flow from inter-section edges."""
1388
+ section_names = {sec["id"]: sec.get("name", sec["id"]) for sec in sections}
1389
+ order = [sec["id"] for sec in sections if sec["id"] != "overview"]
1390
+ if not order:
1391
+ return "Graph nodes -> documentation"
1392
+
1393
+ outgoing = defaultdict(Counter)
1394
+ incoming = Counter()
1395
+ for (src, tgt), data in section_edge_summary(classified_edges).items():
1396
+ outgoing[src][tgt] += data["count"]
1397
+ incoming[tgt] += data["count"]
1398
+
1399
+ start = min(order, key=lambda sid: (incoming.get(sid, 0), order.index(sid)))
1400
+ chain = [start]
1401
+ seen = {start}
1402
+ current = start
1403
+ while len(chain) < min(7, len(order)):
1404
+ candidates = [(count, tgt) for tgt, count in outgoing.get(current, {}).items() if tgt not in seen]
1405
+ if candidates:
1406
+ _, nxt = max(candidates)
1407
+ else:
1408
+ remaining = [sid for sid in order if sid not in seen]
1409
+ if not remaining:
1410
+ break
1411
+ nxt = remaining[0]
1412
+ chain.append(nxt)
1413
+ seen.add(nxt)
1414
+ current = nxt
1415
+ return " -> ".join(section_names.get(sid, sid) for sid in chain)
1416
+
1417
+
1418
+ def generate_overview_cards(meta: dict, report_text: str, sections: list,
1419
+ section_nodes_map: dict, classified_edges: dict,
1420
+ lang: str) -> str:
1421
+ """Generate generic overview cards."""
1422
+ rows = []
1423
+ for sec in sections:
1424
+ if sec["id"] == "overview":
1425
+ continue
1426
+ communities = ", ".join(str(c) for c in sec.get("communities", []))
1427
+ node_count = len(section_nodes_map.get(sec["id"], []))
1428
+ rows.append(
1429
+ f"<tr><td>{escape(sec['name'])}</td><td>{node_count}</td><td><code>{escape(communities)}</code></td></tr>"
1430
+ )
1431
+
1432
+ flow = derive_flow_chain(sections, classified_edges)
1433
+ layer_title = pick_text(lang, "架构层次", "Architecture Layers")
1434
+ layer_cols = pick_text(lang, "<tr><th>层</th><th>节点</th><th>社区</th></tr>", "<tr><th>Layer</th><th>Nodes</th><th>Communities</th></tr>")
1435
+ flow_title = pick_text(lang, "核心数据流", "Core Flow")
1436
+ return f"""<div class="grid">
1437
+ <div class="card">
1438
+ <h4>{layer_title}</h4>
1439
+ <table style="width:100%;font-size:0.85rem;">
1440
+ {layer_cols}
1441
+ {''.join(rows)}
1442
+ </table>
1443
+ </div>
1444
+ <div class="card">
1445
+ <h4>{flow_title}</h4>
1446
+ <div class="arrow-chain">{escape(flow)}</div>
1447
+ </div>
1448
+ </div>"""
1449
+
1450
+
1451
+ def section_keywords(nodes: list, limit: int = 5) -> list:
1452
+ """Pick representative words from labels and file names."""
1453
+ counts = Counter()
1454
+ stopwords = {
1455
+ "the", "and", "for", "with", "from", "this", "that", "class", "function",
1456
+ "method", "file", "src", "lib", "core", "index", "main", "init", "py",
1457
+ "ts", "tsx", "js", "jsx", "go", "rs", "java", "html", "css",
1458
+ }
1459
+ for node in nodes:
1460
+ text = f"{node.get('label', '')} {node.get('source_file', '')}".replace("/", " ").replace("_", " ").replace("-", " ")
1461
+ for raw in text.split():
1462
+ word = "".join(ch for ch in raw.lower() if ch.isalnum())
1463
+ if len(word) < 3 or word in stopwords:
1464
+ continue
1465
+ counts[word] += 1
1466
+ return [word for word, _ in counts.most_common(limit)]
1467
+
1468
+
1469
+ def generate_section_intro(sec: dict, nodes: list, edge_count: int, lang: str) -> str:
1470
+ """Generate the section introductory paragraph."""
1471
+ file_counts = Counter(n.get("source_file") for n in nodes if n.get("source_file"))
1472
+ files = [safe_file_path(path) for path, _ in file_counts.most_common(3)]
1473
+ keywords = section_keywords(nodes, 4)
1474
+ if is_zh(lang):
1475
+ file_text = "、".join(files) if files else "未标注源文件"
1476
+ keyword_text = "、".join(keywords) if keywords else sec.get("name", sec["id"])
1477
+ text = (
1478
+ f"{sec.get('name', sec['id'])} 汇集了与 {keyword_text} 相关的实现,"
1479
+ f"主要分布在 {file_text}。本节覆盖 {len(nodes)} 个节点、{edge_count} 条内部边,"
1480
+ "图中只展示最有代表性的调用关系以保持可读性。"
1481
+ )
1482
+ else:
1483
+ file_text = ", ".join(files) if files else "unmapped files"
1484
+ keyword_text = ", ".join(keywords) if keywords else sec.get("name", sec["id"])
1485
+ text = (
1486
+ f"{sec.get('name', sec['id'])} groups implementation around {keyword_text}, "
1487
+ f"mostly in {file_text}. This section covers {len(nodes)} nodes and {edge_count} internal edges; "
1488
+ "the diagram shows only representative relationships to stay readable."
1489
+ )
1490
+ return f"<p>{escape(text)}</p>"
1491
+
1492
+
1493
+ def generate_section_cards(sec: dict, nodes: list, section_edges: list, lang: str) -> str:
1494
+ """Generate key file and design-note cards for a section."""
1495
+ file_counts = defaultdict(int)
1496
+ for n in nodes:
1497
+ source_file = n.get("source_file") or ""
1498
+ if source_file:
1499
+ file_counts[source_file] += 1
1500
+ top_files = sorted(file_counts.items(), key=lambda item: (-item[1], item[0]))[:8]
1501
+ if top_files:
1502
+ file_rows = "\n".join(
1503
+ f"<tr><td><code>{escape(safe_file_path(path))}</code></td><td>{count} {escape(pick_text(lang, '个节点', 'nodes'))}</td></tr>"
1504
+ for path, count in top_files
1505
+ )
1506
+ else:
1507
+ file_rows = f'<tr><td colspan="2">{escape(pick_text(lang, "无源文件映射", "No source file mapping"))}</td></tr>'
1508
+
1509
+ relation_counts = Counter(edge.get("relation", "relates") for edge in section_edges if should_include_edge(edge))
1510
+ relation_text = ", ".join(f"{relation_label(rel, lang)} x{count}" for rel, count in relation_counts.most_common(4))
1511
+ if not relation_text:
1512
+ relation_text = pick_text(lang, "未检测到高置信调用边", "No high-confidence call edges detected")
1513
+ note = pick_text(
1514
+ lang,
1515
+ f"本节由 graphify 社区聚类生成。关系概况:{relation_text}。图表优先展示高置信、跨节点调用或使用关系,完整节点清单位于表格中。",
1516
+ f"This section comes from graphify community clustering. Relationship summary: {relation_text}. The diagram prioritizes high-confidence calls or usage relationships; the table keeps the broader node inventory.",
1517
+ )
1518
+ key_files = pick_text(lang, "关键文件", "Key Files")
1519
+ role = pick_text(lang, "覆盖节点", "Coverage")
1520
+ design_notes = pick_text(lang, "设计备注", "Design Notes")
1521
+ return f"""<div class="grid">
1522
+ <div class="card">
1523
+ <h4>{key_files}</h4>
1524
+ <table style="width:100%;font-size:0.85rem;">
1525
+ <tr><th>File</th><th>{role}</th></tr>
1526
+ {file_rows}
1527
+ </table>
1528
+ </div>
1529
+ <div class="card">
1530
+ <h4>{design_notes}</h4>
1531
+ <p>{escape(note)}</p>
1532
+ </div>
1533
+ </div>"""
1534
+
1535
+
1536
+ # ──────────────────────────────────────────────
1537
+ # 8. Main entry point
1538
+ # ──────────────────────────────────────────────
1539
+
1540
+ class CallflowOptions:
1541
+ """Options for call-flow architecture HTML generation."""
1542
+
1543
+ def __init__(
1544
+ self,
1545
+ project: str | Path | None = None,
1546
+ *,
1547
+ graphify_out: str | Path | None = None,
1548
+ graph: str | Path | None = None,
1549
+ report: str | Path | None = None,
1550
+ labels: str | Path | None = None,
1551
+ sections: str | Path | None = None,
1552
+ output: str | Path | None = None,
1553
+ lang: str = "auto",
1554
+ max_sections: int = 15,
1555
+ diagram_scale: float = 1.0,
1556
+ max_diagram_nodes: int = 18,
1557
+ max_diagram_edges: int = 24,
1558
+ ):
1559
+ self.project = str(project) if project is not None else None
1560
+ self.graphify_out = str(graphify_out) if graphify_out is not None else None
1561
+ self.graph = str(graph) if graph is not None else None
1562
+ self.report = str(report) if report is not None else None
1563
+ self.labels = str(labels) if labels is not None else None
1564
+ self.sections = str(sections) if sections is not None else None
1565
+ self.output = str(output) if output is not None else None
1566
+ self.lang = lang
1567
+ self.max_sections = max_sections
1568
+ self.diagram_scale = diagram_scale
1569
+ self.max_diagram_nodes = max_diagram_nodes
1570
+ self.max_diagram_edges = max_diagram_edges
1571
+
1572
+
1573
+ def _report_highlights(report_text: str, lang: str) -> str:
1574
+ """Extract a compact highlights card from GRAPH_REPORT.md."""
1575
+ if not report_text.strip():
1576
+ return ""
1577
+
1578
+ lines = report_text.splitlines()
1579
+ keep: list[str] = []
1580
+ in_gods = False
1581
+ in_summary = False
1582
+ for line in lines:
1583
+ stripped = line.strip()
1584
+ if stripped.startswith("## "):
1585
+ in_summary = stripped == "## Summary"
1586
+ in_gods = stripped.startswith("## God Nodes")
1587
+ continue
1588
+ if in_summary and stripped.startswith("- "):
1589
+ keep.append(stripped[2:])
1590
+ elif in_gods and re.match(r"^\d+\.", stripped):
1591
+ keep.append(stripped)
1592
+ if len(keep) >= 6:
1593
+ break
1594
+
1595
+ if not keep:
1596
+ return ""
1597
+
1598
+ title = pick_text(lang, "图谱报告摘要", "Graph Report Highlights")
1599
+ items = "\n".join(f" <li>{escape(item)}</li>" for item in keep)
1600
+ return f"""<div class="card">
1601
+ <h4>{title}</h4>
1602
+ <ul>
1603
+ {items}
1604
+ </ul>
1605
+ </div>"""
1606
+
1607
+
1608
+ def write_callflow_html(
1609
+ project: str | Path | None = None,
1610
+ *,
1611
+ graphify_out: str | Path | None = None,
1612
+ graph: str | Path | None = None,
1613
+ report: str | Path | None = None,
1614
+ labels: str | Path | None = None,
1615
+ sections: str | Path | None = None,
1616
+ output: str | Path | None = None,
1617
+ lang: str = "auto",
1618
+ max_sections: int = 15,
1619
+ diagram_scale: float = 1.0,
1620
+ max_diagram_nodes: int = 18,
1621
+ max_diagram_edges: int = 24,
1622
+ verbose: bool = False,
1623
+ ) -> Path:
1624
+ """Generate call-flow architecture HTML from graphify output files."""
1625
+ args = CallflowOptions(
1626
+ project,
1627
+ graphify_out=graphify_out,
1628
+ graph=graph,
1629
+ report=report,
1630
+ labels=labels,
1631
+ sections=sections,
1632
+ output=output,
1633
+ lang=lang,
1634
+ max_sections=max_sections,
1635
+ diagram_scale=diagram_scale,
1636
+ max_diagram_nodes=max_diagram_nodes,
1637
+ max_diagram_edges=max_diagram_edges,
1638
+ )
1639
+
1640
+ paths = resolve_graphify_paths(args)
1641
+ if not paths["graph"].exists():
1642
+ raise FileNotFoundError(
1643
+ f"graphify output not found: {paths['graph']}. "
1644
+ "Run graphify first or pass --graph /path/to/graph.json."
1645
+ )
1646
+
1647
+ # Load data
1648
+ nodes, edges, hyperedges, meta = load_graph(paths["graph"])
1649
+ labels = load_labels(paths["labels"])
1650
+ lang = detect_lang(args.lang, nodes, labels)
1651
+ if paths["sections"]:
1652
+ sections = load_sections(paths["sections"])
1653
+ else:
1654
+ sections = derive_sections_from_communities(nodes, labels, lang, args.max_sections)
1655
+ sections = normalize_sections(sections, lang)
1656
+ report_text = load_report(paths["report"])
1657
+
1658
+ if not nodes:
1659
+ raise ValueError("graph.json contains 0 nodes")
1660
+ if len(sections) <= 1:
1661
+ raise ValueError("no sections defined")
1662
+
1663
+ if verbose and len(nodes) >= 5000:
1664
+ print("WARNING: Large graph -- Mermaid rendering may be slow. Consider --max-sections 5.", file=sys.stderr)
1665
+
1666
+ node_ids = {node.get("id") for node in nodes}
1667
+ missing_endpoint_edges = [edge for edge in edges if edge.get("source") not in node_ids or edge.get("target") not in node_ids]
1668
+ if verbose and missing_endpoint_edges:
1669
+ print(f"WARNING: {len(missing_endpoint_edges)} edges reference nodes not present in graph.json.", file=sys.stderr)
1670
+
1671
+ meta["project_name"] = infer_project_name(str(paths["graph"]), meta)
1672
+ meta["node_count"] = len(nodes)
1673
+ meta["edge_count"] = len(edges)
1674
+ meta["hyperedge_count"] = len(hyperedges)
1675
+
1676
+ if args.output:
1677
+ output_path = Path(args.output).expanduser()
1678
+ if not output_path.is_absolute():
1679
+ output_path = paths["base"] / output_path
1680
+ else:
1681
+ output_path = paths["graphify_out"] / f"{safe_filename(meta['project_name'])}-callflow.html"
1682
+
1683
+ if verbose:
1684
+ print(f"Loaded: {len(nodes)} nodes, {len(edges)} edges, {len(sections)} sections")
1685
+ print(f"Graph: {paths['graph']}")
1686
+
1687
+ # Build index
1688
+ comm_idx = build_community_index(nodes)
1689
+ meta["community_count"] = len(comm_idx)
1690
+ section_nodes_map = build_section_node_map(sections, comm_idx)
1691
+ classified = classify_edges(edges, section_nodes_map)
1692
+
1693
+ # Build HTML
1694
+ html = []
1695
+ doc_title = (
1696
+ f"{meta.get('project_name', 'Project')} — 完整调用流程与架构文档"
1697
+ if lang.startswith("zh")
1698
+ else f"{meta.get('project_name', 'Project')} — Complete Call Flow & Architecture Documentation"
1699
+ )
1700
+
1701
+ # Doctype and head
1702
+ html.append(f"""<!DOCTYPE html>
1703
+ <html lang="{escape(lang, quote=True)}">
1704
+ <head>
1705
+ <meta charset="UTF-8">
1706
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1707
+ <title>{escape(doc_title)}</title>
1708
+ <script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
1709
+ <style>
1710
+ {CSS}
1711
+ </style>
1712
+ </head>
1713
+ <body>
1714
+ <div class="container">
1715
+ """)
1716
+
1717
+ # Header + nav
1718
+ html.append(generate_header(sections, meta, lang))
1719
+
1720
+ # ── Architecture Overview (Section "overview") ──
1721
+ overview_name = sections[0].get("name", "Architecture Overview") if sections else "Architecture Overview"
1722
+ html.append(f"""<!-- ====== Architecture Overview ====== -->
1723
+ <h2 id="overview">1. {escape(str(overview_name))}</h2>
1724
+
1725
+ <div class="mermaid">
1726
+ """)
1727
+ html.append(generate_overview_graph(sections, section_nodes_map, classified, labels, lang, args.diagram_scale))
1728
+ html.append("""</div>
1729
+ """)
1730
+ html.append(generate_overview_cards(meta, report_text, sections, section_nodes_map, classified, lang))
1731
+ report_card = _report_highlights(report_text, lang)
1732
+ if report_card:
1733
+ html.append(f'<div class="grid">\n {report_card}\n</div>')
1734
+ html.append("<hr>")
1735
+
1736
+ # ── Per-section content ──
1737
+ section_num = 1 # overview was #1
1738
+ for sec in sections:
1739
+ if sec["id"] == "overview":
1740
+ continue
1741
+ section_num += 1
1742
+ sid = sec["id"]
1743
+ name = sec.get("name", sid)
1744
+ sec_nodes = section_nodes_map.get(sid, [])
1745
+ sec_edges = classified.get("intra", {}).get(sid, [])
1746
+
1747
+ edge_count = len(sec_edges)
1748
+ h3_title = pick_text(lang, "调用明细", "Call Details")
1749
+ number_header = "#"
1750
+ function_header = pick_text(lang, "节点", "Node")
1751
+ type_header = pick_text(lang, "类型", "Type")
1752
+ caller_header = pick_text(lang, "调用方", "Caller")
1753
+ callee_header = pick_text(lang, "被调用/依赖", "Callees")
1754
+ desc_header = pick_text(lang, "说明", "Description")
1755
+
1756
+ html.append(f"""<!-- ====== {section_num}. {html_comment_text(name)} ====== -->
1757
+ <h2 id="{escape(str(sid), quote=True)}">{section_num}. {escape(str(name))}</h2>
1758
+ {generate_section_intro(sec, sec_nodes, edge_count, lang)}
1759
+
1760
+ <div class="mermaid">
1761
+ {generate_section_flowchart(sid, name, sec_nodes, sec_edges, lang, args.diagram_scale, args.max_diagram_nodes, args.max_diagram_edges)}
1762
+ </div>
1763
+
1764
+ <h3>{h3_title}</h3>
1765
+ <table class="call-table">
1766
+ <tr>
1767
+ <th style="width:5%">{number_header}</th>
1768
+ <th style="width:28%">{function_header}</th>
1769
+ <th style="width:10%">{type_header}</th>
1770
+ <th style="width:17%">{caller_header}</th>
1771
+ <th style="width:20%">{callee_header}</th>
1772
+ <th style="width:20%">{desc_header}</th>
1773
+ </tr>
1774
+ {generate_call_table_rows(sec_nodes, sec_edges, lang, edges, nodes)}
1775
+ </table>
1776
+
1777
+ {generate_section_cards(sec, sec_nodes, sec_edges, lang)}
1778
+ <hr>
1779
+ """)
1780
+
1781
+ # ── Section: Hyperedges (if any) ──
1782
+ if hyperedges:
1783
+ html.append("""<h2 id="hyperedges">Group Relationships (Hyperedges)</h2>
1784
+ <div class="grid">
1785
+ """)
1786
+ for he in hyperedges[:9]:
1787
+ hid = he.get("id", "?")
1788
+ hlabel = he.get("label", hid)
1789
+ hnodes = he.get("nodes", [])
1790
+ hrel = he.get("relation", "")
1791
+ html.append(f""" <div class="card">
1792
+ <h4>{escape(str(hlabel))}</h4>
1793
+ <p><code>{escape(str(hrel))}</code> — {len(hnodes)} participants</p>
1794
+ <ul>""")
1795
+ for hn in hnodes[:5]:
1796
+ html.append(f" <li><code>{escape(str(hn))}</code></li>")
1797
+ if len(hnodes) > 5:
1798
+ html.append(f" <li>... and {len(hnodes) - 5} more</li>")
1799
+ html.append(" </ul>\n </div>")
1800
+ html.append("</div>\n<hr>")
1801
+
1802
+ # ── Section: Statistics ──
1803
+ total_sections = sum(1 for s in sections if s["id"] != "overview")
1804
+ html.append(f"""<h2 id="stats">Project Statistics</h2>
1805
+
1806
+ <div class="grid">
1807
+ <div class="card">
1808
+ <h4>Graph</h4>
1809
+ <table style="width:100%;font-size:0.85rem;">
1810
+ <tr><td>Nodes</td><td>{len(nodes)}</td></tr>
1811
+ <tr><td>Edges</td><td>{len(edges)}</td></tr>
1812
+ <tr><td>Hyperedges</td><td>{len(hyperedges)}</td></tr>
1813
+ <tr><td>Communities</td><td>{len(comm_idx)}</td></tr>
1814
+ <tr><td>Documented Sections</td><td>{total_sections}</td></tr>
1815
+ </table>
1816
+ </div>
1817
+ <div class="card">
1818
+ <h4>Edge Confidence</h4>
1819
+ <table style="width:100%;font-size:0.85rem;">
1820
+ <tr><td>EXTRACTED</td><td>{sum(1 for e in edges if e.get('confidence') == 'EXTRACTED')}</td></tr>
1821
+ <tr><td>INFERRED</td><td>{sum(1 for e in edges if e.get('confidence') == 'INFERRED')}</td></tr>
1822
+ <tr><td>AMBIGUOUS</td><td>{sum(1 for e in edges if e.get('confidence') == 'AMBIGUOUS')}</td></tr>
1823
+ </table>
1824
+ </div>
1825
+ </div>
1826
+ """)
1827
+
1828
+ # ── Footer ──
1829
+ html.append(f"""<div style="text-align:center; padding:40px 0; color: var(--muted); font-size:0.9rem;">
1830
+ <p>{escape(str(meta.get('project_name', 'Project')))} — Architecture Documentation</p>
1831
+ <p>Generated: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')} · graphify callflow-html</p>
1832
+ </div>
1833
+ """)
1834
+
1835
+ # Close
1836
+ html.append("""</div><!-- .container -->
1837
+
1838
+ <script>
1839
+ (function () {
1840
+ const mermaidConfig = {
1841
+ startOnLoad: false,
1842
+ theme: 'dark',
1843
+ securityLevel: 'loose',
1844
+ flowchart: { htmlLabels: true, useMaxWidth: true },
1845
+ themeVariables: {
1846
+ primaryColor: '#1e293b',
1847
+ primaryTextColor: '#e2e8f0',
1848
+ primaryBorderColor: '#38bdf8',
1849
+ secondaryColor: '#0f172a',
1850
+ tertiaryColor: '#334155',
1851
+ lineColor: '#64748b',
1852
+ textColor: '#e2e8f0',
1853
+ }
1854
+ };
1855
+
1856
+ mermaid.initialize(mermaidConfig);
1857
+
1858
+ function clamp(value, min, max) {
1859
+ return Math.min(max, Math.max(min, value));
1860
+ }
1861
+
1862
+ function enhanceMermaidDiagrams() {
1863
+ document.querySelectorAll('.mermaid').forEach((container) => {
1864
+ if (container.dataset.zoomReady === 'true') return;
1865
+ const svg = container.querySelector('svg');
1866
+ if (!svg) return;
1867
+
1868
+ container.dataset.zoomReady = 'true';
1869
+ container.classList.add('is-enhanced');
1870
+
1871
+ const viewport = document.createElement('div');
1872
+ viewport.className = 'mermaid-viewport';
1873
+ svg.parentNode.insertBefore(viewport, svg);
1874
+ viewport.appendChild(svg);
1875
+
1876
+ const toolbar = document.createElement('div');
1877
+ toolbar.className = 'mermaid-toolbar';
1878
+ toolbar.innerHTML = [
1879
+ '<button type="button" data-action="zoom-out" title="Zoom out">-</button>',
1880
+ '<span class="zoom-level" data-role="level">100%</span>',
1881
+ '<button type="button" data-action="zoom-in" title="Zoom in">+</button>',
1882
+ '<button type="button" data-action="fit" title="Fit width">Fit</button>',
1883
+ '<button type="button" data-action="reset" title="Reset view">Reset</button>'
1884
+ ].join('');
1885
+ container.insertBefore(toolbar, viewport);
1886
+
1887
+ const state = { scale: 1, x: 0, y: 0, dragging: false, startX: 0, startY: 0, originX: 0, originY: 0 };
1888
+ const level = toolbar.querySelector('[data-role="level"]');
1889
+
1890
+ function applyTransform() {
1891
+ svg.style.transform = `translate(${state.x}px, ${state.y}px) scale(${state.scale})`;
1892
+ level.textContent = `${Math.round(state.scale * 100)}%`;
1893
+ }
1894
+
1895
+ function zoomBy(delta) {
1896
+ state.scale = clamp(state.scale + delta, 0.25, 3);
1897
+ applyTransform();
1898
+ }
1899
+
1900
+ function reset() {
1901
+ state.scale = 1;
1902
+ state.x = 0;
1903
+ state.y = 0;
1904
+ applyTransform();
1905
+ }
1906
+
1907
+ function fitWidth() {
1908
+ const rawWidth = svg.viewBox && svg.viewBox.baseVal && svg.viewBox.baseVal.width
1909
+ ? svg.viewBox.baseVal.width
1910
+ : svg.getBoundingClientRect().width / state.scale;
1911
+ if (!rawWidth) {
1912
+ reset();
1913
+ return;
1914
+ }
1915
+ state.scale = clamp((viewport.clientWidth - 48) / rawWidth, 0.25, 1.4);
1916
+ state.x = 0;
1917
+ state.y = 0;
1918
+ applyTransform();
1919
+ }
1920
+
1921
+ toolbar.addEventListener('click', (event) => {
1922
+ const button = event.target.closest('button[data-action]');
1923
+ if (!button) return;
1924
+ const action = button.dataset.action;
1925
+ if (action === 'zoom-in') zoomBy(0.15);
1926
+ if (action === 'zoom-out') zoomBy(-0.15);
1927
+ if (action === 'fit') fitWidth();
1928
+ if (action === 'reset') reset();
1929
+ });
1930
+
1931
+ viewport.addEventListener('wheel', (event) => {
1932
+ if (!event.ctrlKey && !event.metaKey) return;
1933
+ event.preventDefault();
1934
+ zoomBy(event.deltaY < 0 ? 0.1 : -0.1);
1935
+ }, { passive: false });
1936
+
1937
+ viewport.addEventListener('pointerdown', (event) => {
1938
+ if (event.button !== 0) return;
1939
+ state.dragging = true;
1940
+ state.startX = event.clientX;
1941
+ state.startY = event.clientY;
1942
+ state.originX = state.x;
1943
+ state.originY = state.y;
1944
+ viewport.classList.add('is-dragging');
1945
+ viewport.setPointerCapture(event.pointerId);
1946
+ });
1947
+
1948
+ viewport.addEventListener('pointermove', (event) => {
1949
+ if (!state.dragging) return;
1950
+ state.x = state.originX + event.clientX - state.startX;
1951
+ state.y = state.originY + event.clientY - state.startY;
1952
+ applyTransform();
1953
+ });
1954
+
1955
+ function endDrag(event) {
1956
+ if (!state.dragging) return;
1957
+ state.dragging = false;
1958
+ viewport.classList.remove('is-dragging');
1959
+ if (viewport.hasPointerCapture(event.pointerId)) {
1960
+ viewport.releasePointerCapture(event.pointerId);
1961
+ }
1962
+ }
1963
+
1964
+ viewport.addEventListener('pointerup', endDrag);
1965
+ viewport.addEventListener('pointercancel', endDrag);
1966
+ applyTransform();
1967
+ });
1968
+ }
1969
+
1970
+ function renderMermaid() {
1971
+ const result = mermaid.run
1972
+ ? mermaid.run({ querySelector: '.mermaid' })
1973
+ : Promise.resolve();
1974
+ Promise.resolve(result)
1975
+ .then(enhanceMermaidDiagrams)
1976
+ .catch((error) => {
1977
+ console.error('Mermaid render failed:', error);
1978
+ enhanceMermaidDiagrams();
1979
+ });
1980
+ }
1981
+
1982
+ if (document.readyState === 'loading') {
1983
+ document.addEventListener('DOMContentLoaded', renderMermaid);
1984
+ } else {
1985
+ renderMermaid();
1986
+ }
1987
+ })();
1988
+ </script>
1989
+
1990
+ </body>
1991
+ </html>""")
1992
+
1993
+ # Write output
1994
+ output = "\n".join(html)
1995
+ output_path.parent.mkdir(parents=True, exist_ok=True)
1996
+ output_path.write_text(output, encoding="utf-8")
1997
+
1998
+ # Summary
1999
+ mermaid_count = output.count('<div class="mermaid">')
2000
+ table_count = output.count('<table class="call-table">')
2001
+ section_count = output.count('<h2 id=')
2002
+
2003
+ if verbose:
2004
+ print(f"Call-flow HTML written: {output_path}")
2005
+ print(f" Sections: {section_count} | Mermaid diagrams: {mermaid_count} | Call tables: {table_count}")
2006
+ print(" Diagrams use Mermaid init directives plus interactive zoom/pan controls.")
2007
+
2008
+ return output_path
2009
+
2010
+
2011
+ def main():
2012
+ parser = argparse.ArgumentParser(
2013
+ description="Generate call-flow architecture HTML from graphify knowledge graph outputs"
2014
+ )
2015
+ parser.add_argument("project", nargs="?", default=None, help="Project root or graphify output directory")
2016
+ parser.add_argument("--graphify-out", default=None, help="Path to graphify output directory")
2017
+ parser.add_argument("--graph", default=None, help="Path to graph.json")
2018
+ parser.add_argument("--report", default=None, help="Path to GRAPH_REPORT.md")
2019
+ parser.add_argument("--labels", default=None, help="Path to .graphify_labels.json")
2020
+ parser.add_argument("--sections", default=None, help="Path to sections JSON file; auto-derived when omitted")
2021
+ parser.add_argument("--output", default=None, help="Output HTML path")
2022
+ parser.add_argument("--lang", default="auto", help="HTML language: auto, zh-CN, en, etc. (default: auto)")
2023
+ parser.add_argument("--max-sections", type=int, default=15, help="Maximum auto-derived sections, excluding overview")
2024
+ parser.add_argument("--diagram-scale", type=float, default=1.0, help="Mermaid-native diagram scale via init directive (0.65-1.8)")
2025
+ parser.add_argument("--max-diagram-nodes", type=int, default=18, help="Maximum representative nodes per section diagram")
2026
+ parser.add_argument("--max-diagram-edges", type=int, default=24, help="Maximum representative edges per section diagram")
2027
+ args = parser.parse_args()
2028
+
2029
+ try:
2030
+ write_callflow_html(
2031
+ args.project,
2032
+ graphify_out=args.graphify_out,
2033
+ graph=args.graph,
2034
+ report=args.report,
2035
+ labels=args.labels,
2036
+ sections=args.sections,
2037
+ output=args.output,
2038
+ lang=args.lang,
2039
+ max_sections=args.max_sections,
2040
+ diagram_scale=args.diagram_scale,
2041
+ max_diagram_nodes=args.max_diagram_nodes,
2042
+ max_diagram_edges=args.max_diagram_edges,
2043
+ verbose=True,
2044
+ )
2045
+ except (FileNotFoundError, ValueError, SystemExit) as exc:
2046
+ print(f"ERROR: {exc}", file=sys.stderr)
2047
+ sys.exit(1)
2048
+
2049
+
2050
+ if __name__ == "__main__":
2051
+ main()