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,1283 @@
1
+ ---
2
+ name: graphify
3
+ description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
4
+ ---
5
+
6
+ # /graphify
7
+
8
+ Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.
9
+
10
+ ## Usage
11
+
12
+ ```
13
+ /graphify # full pipeline on current directory (HTML viz; add --obsidian for a vault)
14
+ /graphify <path> # full pipeline on specific path
15
+ /graphify <path> --mode deep # thorough extraction, richer INFERRED edges
16
+ /graphify <path> --update # incremental - re-extract only new/changed files
17
+ /graphify <path> --cluster-only # rerun clustering on existing graph
18
+ /graphify <path> --no-viz # skip visualization, just report + JSON
19
+ /graphify <path> --html # (HTML is generated by default - this flag is a no-op)
20
+ /graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
21
+ /graphify <path> --graphml # export graph.graphml (Gephi, yEd)
22
+ /graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
23
+ /graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
24
+ /graphify <path> --mcp # start MCP stdio server for agent access
25
+ /graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
26
+ /graphify add <url> # fetch URL, save to ./raw, update graph
27
+ /graphify add <url> --author "Name" # tag who wrote it
28
+ /graphify add <url> --contributor "Name" # tag who added it to the corpus
29
+ /graphify query "<question>" # BFS traversal - broad context
30
+ /graphify query "<question>" --dfs # DFS - trace a specific path
31
+ /graphify query "<question>" --budget 1500 # cap answer at N tokens
32
+ /graphify path "AuthModule" "Database" # shortest path between two concepts
33
+ /graphify explain "SwinTransformer" # plain-language explanation of a node
34
+ ```
35
+
36
+ ## What graphify is for
37
+
38
+ graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
39
+
40
+ Three things it does that your AI assistant alone cannot:
41
+ 1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
42
+ 2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
43
+ 3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
44
+
45
+ Use it for:
46
+ - A codebase you're new to (understand architecture before touching anything)
47
+ - A reading list (papers + tweets + notes → one navigable graph)
48
+ - A research corpus (citation graph + concept graph in one)
49
+ - Your personal /raw folder (drop everything in, let it grow, query it)
50
+
51
+ ## What You Must Do When Invoked
52
+
53
+ If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
54
+
55
+ If no path was given, use `.` (current directory). Do not ask the user for a path.
56
+
57
+ Follow these steps in order. Do not skip steps.
58
+
59
+ ### Step 1 - Ensure graphify is installed
60
+
61
+ ```bash
62
+ # Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs)
63
+ PYTHON=""
64
+ GRAPHIFY_BIN=$(which graphify 2>/dev/null)
65
+ # 1. uv tool installs — most reliable on modern Mac/Linux
66
+ if [ -z "$PYTHON" ] && command -v uv >/dev/null 2>&1; then
67
+ _UV_PY=$(uv tool run --from graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
68
+ if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
69
+ fi
70
+ # 2. Read shebang from graphify binary (pipx and direct pip installs)
71
+ if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then
72
+ _SHEBANG=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
73
+ case "$_SHEBANG" in
74
+ *[!a-zA-Z0-9/_.@-]*) ;;
75
+ *) "$_SHEBANG" -c "import graphify" 2>/dev/null && PYTHON="$_SHEBANG" ;;
76
+ esac
77
+ fi
78
+ # 3. Fall back to python3
79
+ if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
80
+ if ! "$PYTHON" -c "import graphify" 2>/dev/null; then
81
+ if command -v uv >/dev/null 2>&1; then
82
+ uv tool install --upgrade graphifyy -q 2>&1 | tail -3
83
+ _UV_PY=$(uv tool run --from graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
84
+ if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
85
+ else
86
+ "$PYTHON" -m pip install graphifyy -q 2>/dev/null \
87
+ || "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
88
+ fi
89
+ fi
90
+ # Write interpreter path for all subsequent steps (persists across invocations)
91
+ mkdir -p graphify-out
92
+ "$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
93
+ ```
94
+
95
+ If the import succeeds, print nothing and move straight to Step 2.
96
+
97
+ **In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
98
+
99
+ ### Step 2 - Detect files
100
+
101
+ ```bash
102
+ $(cat graphify-out/.graphify_python) -c "
103
+ import json
104
+ from graphify.detect import detect
105
+ from pathlib import Path
106
+ result = detect(Path('INPUT_PATH'))
107
+ print(json.dumps(result))
108
+ " > .graphify_detect.json
109
+ ```
110
+
111
+ Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
112
+
113
+ ```
114
+ Corpus: X files · ~Y words
115
+ code: N files (.py .ts .go ...)
116
+ docs: N files (.md .txt ...)
117
+ papers: N files (.pdf ...)
118
+ images: N files
119
+ video: N files (.mp4 .mp3 ...)
120
+ ```
121
+
122
+ Omit any category with 0 files from the summary.
123
+
124
+ Then act on it:
125
+ - If `total_files` is 0: stop with "No supported files found in [path]."
126
+ - If `skipped_sensitive` is non-empty: report the count and list the skipped file names, so a wrongly-flagged source or doc is visible and can be renamed or moved (#2106).
127
+ - If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.
128
+ - Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
129
+
130
+ ### Step 2.5 - Transcribe video / audio files (only if video files detected)
131
+
132
+ Skip this step entirely if `detect` returned zero `video` files.
133
+
134
+ Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
135
+
136
+ **Strategy:** Read the god nodes from the detect output or analysis file. You are already a language model - write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
137
+
138
+ **However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
139
+
140
+ **Step 1 - Write the Whisper prompt yourself.**
141
+
142
+ Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
143
+
144
+ - Labels: `transformer, attention, encoder, decoder` -> `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
145
+ - Labels: `kubernetes, deployment, pod, helm` -> `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
146
+
147
+ Set it as `GRAPHIFY_WHISPER_PROMPT` in the environment before running the transcription command.
148
+
149
+ **Step 2 - Transcribe:**
150
+
151
+ ```bash
152
+ $(cat graphify-out/.graphify_python) -c "
153
+ import json, os
154
+ from pathlib import Path
155
+ from graphify.transcribe import transcribe_all
156
+
157
+ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
158
+ video_files = detect.get('files', {}).get('video', [])
159
+ prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
160
+
161
+ transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
162
+ print(json.dumps(transcript_paths))
163
+ " > graphify-out/.graphify_transcripts.json
164
+ ```
165
+
166
+ After transcription:
167
+ - Read the transcript paths from `graphify-out/.graphify_transcripts.json`
168
+ - Add them to the docs list before dispatching semantic subagents in Step 3B
169
+ - Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
170
+ - If transcription fails for a file, print a warning and continue with the rest
171
+
172
+ **Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, set `GRAPHIFY_WHISPER_MODEL=<name>` in the environment before running the command above.
173
+
174
+ ### Step 3 - Extract entities and relationships
175
+
176
+ **Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
177
+
178
+ This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
179
+
180
+ > **graphify needs no API key. Never ask the user for one, and never block on one.** Code is extracted structurally (AST) with no LLM and no key at all — a code-only corpus (the common `/graphify .` on a repo) skips semantic extraction entirely, so go straight to Part A and skip Part B. Semantic extraction (only for docs, papers, and images) is done by your own model. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key. If you cannot dispatch subagents, do not stall: a code-only corpus has no semantic work (write the empty semantic file and continue to Part C); for docs/papers/images, extract them inline yourself. If you catch yourself about to prompt for or block on a missing API key, that is a misread of this skill — proceed without one.
181
+
182
+ **Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
183
+
184
+ Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
185
+
186
+ #### Part A - Structural extraction for code files
187
+
188
+ For any code files detected, run AST extraction in parallel with Part B subagents:
189
+
190
+ ```bash
191
+ $(cat graphify-out/.graphify_python) -c "
192
+ import sys, json
193
+ from graphify.extract import collect_files, extract
194
+ from pathlib import Path
195
+ import json
196
+
197
+ code_files = []
198
+ detect = json.loads(Path('.graphify_detect.json').read_text())
199
+ for f in detect.get('files', {}).get('code', []):
200
+ code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
201
+
202
+ if code_files:
203
+ result = extract(code_files)
204
+ Path('.graphify_ast.json').write_text(json.dumps(result, indent=2))
205
+ print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
206
+ else:
207
+ Path('.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
208
+ print('No code files - skipping AST extraction')
209
+ "
210
+ ```
211
+
212
+ #### Part B - Semantic extraction (parallel subagents)
213
+
214
+ **Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do.
215
+
216
+ > **Aider platform:** Multi-agent support is still early on Aider. Extraction runs sequentially — you read and extract each file yourself. This is slower than parallel platforms but fully reliable.
217
+
218
+ Print: `"Semantic extraction: N files (sequential — Aider)"`
219
+
220
+ **Step B0 - Check extraction cache first**
221
+
222
+ Before dispatching any subagents, check which files already have cached extraction results:
223
+
224
+ ```bash
225
+ $(cat graphify-out/.graphify_python) -c "
226
+ import json
227
+ from graphify.cache import check_semantic_cache
228
+ from pathlib import Path
229
+
230
+ detect = json.loads(Path('.graphify_detect.json').read_text())
231
+ # Only content files go to semantic extraction. Code is already covered
232
+ # structurally by the AST pass; flattening every category here makes the
233
+ # extraction step re-read every source file (#1392).
234
+ all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
235
+
236
+ cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
237
+
238
+ # Always (re)write the cache file: write hits, else DELETE any leftover from a
239
+ # prior run so Part C never merges a stale .graphify_cached.json (#1392).
240
+ if cached_nodes or cached_edges or cached_hyperedges:
241
+ Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
242
+ else:
243
+ Path('.graphify_cached.json').unlink(missing_ok=True)
244
+ Path('.graphify_uncached.txt').write_text('\n'.join(uncached))
245
+ print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
246
+ "
247
+ ```
248
+
249
+ Only dispatch subagents for files listed in `.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
250
+
251
+ **Step B1 - Split into chunks**
252
+
253
+ Load files from `.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
254
+
255
+ **Step B2 - Sequential extraction (Aider)**
256
+
257
+ Process each file one at a time. For each file:
258
+
259
+ 1. Read the file contents
260
+ 2. Extract nodes, edges, and hyperedges applying the same rules:
261
+ - EXTRACTED: relationship explicit in source (import, call, citation)
262
+ - INFERRED: reasonable inference (shared structure, implied dependency)
263
+ - AMBIGUOUS: uncertain — flag it, do not omit
264
+ - Code files: semantic edges AST cannot find. Do not re-extract imports.
265
+ - Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms) and `file_type:"concept"` for named concepts. `file_type` MUST be one of exactly these six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`. When adding `calls` edges: source is caller, target is callee.
266
+ - Image files: use vision — understand what the image IS, not just OCR
267
+ - DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
268
+ - Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
269
+ - Hyperedges: if 3+ nodes share a concept/flow not captured by pairwise edges, add a hyperedge. Max 3 per file.
270
+ - confidence_score REQUIRED on every edge: EXTRACTED=1.0, INFERRED=0.6-0.9 (reason individually), AMBIGUOUS=0.1-0.3
271
+ 3. Accumulate results across all files
272
+
273
+ Schema for each file's output:
274
+ {"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
275
+
276
+ After processing all files, write the accumulated result to `.graphify_semantic_new.json`.
277
+
278
+ **Step B3 - Cache and merge**
279
+
280
+ For the accumulated result:
281
+
282
+ If more than half the chunks failed, stop and tell the user.
283
+
284
+ Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
285
+ ```bash
286
+ $(cat graphify-out/.graphify_python) -c "
287
+ import json, glob
288
+ from pathlib import Path
289
+
290
+ chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
291
+ all_nodes, all_edges, all_hyperedges = [], [], []
292
+ total_in, total_out = 0, 0
293
+ for c in chunks:
294
+ d = json.loads(Path(c).read_text())
295
+ all_nodes += d.get('nodes', [])
296
+ all_edges += d.get('edges', [])
297
+ all_hyperedges += d.get('hyperedges', [])
298
+ total_in += d.get('input_tokens', 0)
299
+ total_out += d.get('output_tokens', 0)
300
+ Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
301
+ 'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
302
+ 'input_tokens': total_in, 'output_tokens': total_out,
303
+ }, indent=2))
304
+ print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
305
+ "
306
+ ```
307
+
308
+ Save new results to cache:
309
+ ```bash
310
+ $(cat graphify-out/.graphify_python) -c "
311
+ import json
312
+ from graphify.cache import save_semantic_cache
313
+ from pathlib import Path
314
+
315
+ new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
316
+ uncached = [line for line in Path('.graphify_uncached.txt').read_text().splitlines() if line]
317
+ saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), allowed_source_files=uncached)
318
+ print(f'Cached {saved} files')
319
+ "
320
+ ```
321
+
322
+ Merge cached + new results into `.graphify_semantic.json`:
323
+ ```bash
324
+ $(cat graphify-out/.graphify_python) -c "
325
+ import json
326
+ from pathlib import Path
327
+
328
+ cached = json.loads(Path('.graphify_cached.json').read_text()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
329
+ new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
330
+
331
+ all_nodes = cached['nodes'] + new.get('nodes', [])
332
+ all_edges = cached['edges'] + new.get('edges', [])
333
+ all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
334
+ seen = set()
335
+ deduped = []
336
+ for n in all_nodes:
337
+ if n['id'] not in seen:
338
+ seen.add(n['id'])
339
+ deduped.append(n)
340
+
341
+ merged = {
342
+ 'nodes': deduped,
343
+ 'edges': all_edges,
344
+ 'hyperedges': all_hyperedges,
345
+ 'input_tokens': new.get('input_tokens', 0),
346
+ 'output_tokens': new.get('output_tokens', 0),
347
+ }
348
+ Path('.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
349
+ print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
350
+ "
351
+ ```
352
+ Clean up temp files: `rm -f .graphify_cached.json .graphify_uncached.txt .graphify_semantic_new.json`
353
+
354
+ #### Part C - Merge AST + semantic into final extraction
355
+
356
+ ```bash
357
+ $(cat graphify-out/.graphify_python) -c "
358
+ import sys, json
359
+ from pathlib import Path
360
+
361
+ ast = json.loads(Path('.graphify_ast.json').read_text())
362
+ sem = json.loads(Path('.graphify_semantic.json').read_text())
363
+
364
+ # Merge: AST nodes first, semantic nodes deduplicated by id
365
+ seen = {n['id'] for n in ast['nodes']}
366
+ merged_nodes = list(ast['nodes'])
367
+ for n in sem['nodes']:
368
+ if n['id'] not in seen:
369
+ merged_nodes.append(n)
370
+ seen.add(n['id'])
371
+
372
+ merged_edges = ast['edges'] + sem['edges']
373
+ merged_hyperedges = sem.get('hyperedges', [])
374
+ merged = {
375
+ 'nodes': merged_nodes,
376
+ 'edges': merged_edges,
377
+ 'hyperedges': merged_hyperedges,
378
+ 'input_tokens': sem.get('input_tokens', 0),
379
+ 'output_tokens': sem.get('output_tokens', 0),
380
+ }
381
+ Path('.graphify_extract.json').write_text(json.dumps(merged, indent=2))
382
+ total = len(merged_nodes)
383
+ edges = len(merged_edges)
384
+ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
385
+ "
386
+ ```
387
+
388
+ ### Step 4 - Build graph, cluster, analyze, generate outputs
389
+
390
+ **Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source->target), otherwise `False` (the default undirected `Graph`). Substitute it everywhere it appears, the same way you substitute `INPUT_PATH` - do not leave the literal `IS_DIRECTED` in the code.
391
+
392
+ ```bash
393
+ mkdir -p graphify-out
394
+ $(cat graphify-out/.graphify_python) -c "
395
+ import sys, json
396
+ from graphify.build import build_from_json
397
+ from graphify.cluster import cluster, score_all
398
+ from graphify.analyze import god_nodes, surprising_connections, suggest_questions
399
+ from graphify.report import generate
400
+ from graphify.export import to_json
401
+ from pathlib import Path
402
+
403
+ extraction = json.loads(Path('.graphify_extract.json').read_text())
404
+ detection = json.loads(Path('.graphify_detect.json').read_text())
405
+
406
+ G = build_from_json(extraction, directed=IS_DIRECTED)
407
+ # Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
408
+ # GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
409
+ if G.number_of_nodes() == 0:
410
+ print('ERROR: Graph is empty - extraction produced no nodes.')
411
+ print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
412
+ raise SystemExit(1)
413
+ communities = cluster(G)
414
+ cohesion = score_all(G, communities)
415
+ tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
416
+ gods = god_nodes(G)
417
+ surprises = surprising_connections(G, communities)
418
+ labels = {cid: 'Community ' + str(cid) for cid in communities}
419
+ # Placeholder questions - regenerated with real labels in Step 5
420
+ questions = suggest_questions(G, communities, labels)
421
+
422
+ # Persist the graph first and only write the report/analysis if it actually
423
+ # persisted - to_json refuses to shrink an existing graph.json (#479), and a
424
+ # report describing a graph we did not write would be a lie (#1392).
425
+ wrote = to_json(G, communities, 'graphify-out/graph.json')
426
+ if not wrote:
427
+ print('ERROR: refused to shrink graphify-out/graph.json (fewer nodes than the existing graph). Run a full rebuild to be safe.')
428
+ raise SystemExit(1)
429
+ report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
430
+ Path('graphify-out/GRAPH_REPORT.md').write_text(report)
431
+
432
+ analysis = {
433
+ 'communities': {str(k): v for k, v in communities.items()},
434
+ 'cohesion': {str(k): v for k, v in cohesion.items()},
435
+ 'gods': gods,
436
+ 'surprises': surprises,
437
+ 'questions': questions,
438
+ }
439
+ Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
440
+ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
441
+ "
442
+ ```
443
+
444
+ If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
445
+
446
+ Replace INPUT_PATH with the actual path.
447
+
448
+ ### Step 5 - Label communities
449
+
450
+ Read `.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
451
+
452
+ Then regenerate the report and save the labels for the visualizer:
453
+
454
+ ```bash
455
+ $(cat graphify-out/.graphify_python) -c "
456
+ import sys, json
457
+ from graphify.build import build_from_json
458
+ from graphify.cluster import score_all
459
+ from graphify.analyze import god_nodes, surprising_connections, suggest_questions
460
+ from graphify.report import generate
461
+ from graphify.export import to_json
462
+ from pathlib import Path
463
+
464
+ extraction = json.loads(Path('.graphify_extract.json').read_text())
465
+ detection = json.loads(Path('.graphify_detect.json').read_text())
466
+ analysis = json.loads(Path('.graphify_analysis.json').read_text())
467
+
468
+ G = build_from_json(extraction, directed=IS_DIRECTED)
469
+ communities = {int(k): v for k, v in analysis['communities'].items()}
470
+ cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
471
+ tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
472
+
473
+ # LABELS - replace these with the names you chose above
474
+ labels = LABELS_DICT
475
+
476
+ # Regenerate questions with real community labels (labels affect question phrasing)
477
+ questions = suggest_questions(G, communities, labels)
478
+
479
+ report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
480
+ Path('graphify-out/GRAPH_REPORT.md').write_text(report)
481
+ Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
482
+ # Re-export so graph.json nodes carry the curated community_name (#2490).
483
+ # Same extraction as Step 4, so the #479 shrink-guard passes on node count;
484
+ # if it still refuses, surface the guard message - do not force past it.
485
+ wrote = to_json(G, communities, 'graphify-out/graph.json', community_labels=labels)
486
+ if not wrote:
487
+ print('ERROR: refused to shrink graphify-out/graph.json (fewer nodes than the existing graph). Run a full rebuild to be safe.')
488
+ print('Report updated with community labels')
489
+ "
490
+ ```
491
+
492
+ Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
493
+ Replace INPUT_PATH with the actual path.
494
+
495
+ ### Step 6 - Generate Obsidian vault (opt-in) + HTML
496
+
497
+ **Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
498
+
499
+ If `--obsidian` was given:
500
+
501
+ ```bash
502
+ $(cat graphify-out/.graphify_python) -c "
503
+ import sys, json
504
+ from graphify.build import build_from_json
505
+ from graphify.export import to_obsidian, to_canvas
506
+ from pathlib import Path
507
+
508
+ extraction = json.loads(Path('.graphify_extract.json').read_text())
509
+ analysis = json.loads(Path('.graphify_analysis.json').read_text())
510
+ labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
511
+
512
+ G = build_from_json(extraction, directed=IS_DIRECTED)
513
+ communities = {int(k): v for k, v in analysis['communities'].items()}
514
+ cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
515
+ labels = {int(k): v for k, v in labels_raw.items()}
516
+
517
+ n = to_obsidian(G, communities, 'graphify-out/obsidian', community_labels=labels or None, cohesion=cohesion)
518
+ print(f'Obsidian vault: {n} notes in graphify-out/obsidian/')
519
+
520
+ to_canvas(G, communities, 'graphify-out/obsidian/graph.canvas', community_labels=labels or None)
521
+ print('Canvas: graphify-out/obsidian/graph.canvas - open in Obsidian for structured community layout')
522
+ print()
523
+ print('Open graphify-out/obsidian/ as a vault in Obsidian.')
524
+ print(' Graph view - nodes colored by community (set automatically)')
525
+ print(' graph.canvas - structured layout with communities as groups')
526
+ print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries')
527
+ "
528
+ ```
529
+
530
+ Generate the HTML graph (always, unless `--no-viz`):
531
+
532
+ ```bash
533
+ $(cat graphify-out/.graphify_python) -c "
534
+ import sys, json
535
+ from graphify.build import build_from_json
536
+ from graphify.export import to_html
537
+ from pathlib import Path
538
+
539
+ extraction = json.loads(Path('.graphify_extract.json').read_text())
540
+ analysis = json.loads(Path('.graphify_analysis.json').read_text())
541
+ labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
542
+
543
+ G = build_from_json(extraction, directed=IS_DIRECTED)
544
+ communities = {int(k): v for k, v in analysis['communities'].items()}
545
+ labels = {int(k): v for k, v in labels_raw.items()}
546
+
547
+ if G.number_of_nodes() > 5000:
548
+ print(f'Graph has {G.number_of_nodes()} nodes - too large for HTML viz. Use Obsidian vault instead.')
549
+ else:
550
+ to_html(G, communities, 'graphify-out/graph.html', community_labels=labels or None)
551
+ print('graph.html written - open in any browser, no server needed')
552
+ "
553
+ ```
554
+
555
+ ### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
556
+
557
+ **If `--neo4j`** - generate a Cypher file for manual import:
558
+
559
+ ```bash
560
+ $(cat graphify-out/.graphify_python) -c "
561
+ import sys, json
562
+ from graphify.build import build_from_json
563
+ from graphify.export import to_cypher
564
+ from pathlib import Path
565
+
566
+ G = build_from_json(json.loads(Path('.graphify_extract.json').read_text()), directed=IS_DIRECTED)
567
+ to_cypher(G, 'graphify-out/cypher.txt')
568
+ print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt')
569
+ "
570
+ ```
571
+
572
+ **If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
573
+
574
+ ```bash
575
+ $(cat graphify-out/.graphify_python) -c "
576
+ import sys, json
577
+ from graphify.build import build_from_json
578
+ from graphify.cluster import cluster
579
+ from graphify.export import push_to_neo4j
580
+ from pathlib import Path
581
+
582
+ extraction = json.loads(Path('.graphify_extract.json').read_text())
583
+ analysis = json.loads(Path('.graphify_analysis.json').read_text())
584
+ G = build_from_json(extraction, directed=IS_DIRECTED)
585
+ communities = {int(k): v for k, v in analysis['communities'].items()}
586
+
587
+ result = push_to_neo4j(G, uri='NEO4J_URI', user='NEO4J_USER', password='NEO4J_PASSWORD', communities=communities)
588
+ print(f'Pushed to Neo4j: {result[\"nodes\"]} nodes, {result[\"edges\"]} edges')
589
+ "
590
+ ```
591
+
592
+ Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.
593
+
594
+ ### Step 7b - SVG export (only if --svg flag)
595
+
596
+ ```bash
597
+ $(cat graphify-out/.graphify_python) -c "
598
+ import sys, json
599
+ from graphify.build import build_from_json
600
+ from graphify.export import to_svg
601
+ from pathlib import Path
602
+
603
+ extraction = json.loads(Path('.graphify_extract.json').read_text())
604
+ analysis = json.loads(Path('.graphify_analysis.json').read_text())
605
+ labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
606
+
607
+ G = build_from_json(extraction, directed=IS_DIRECTED)
608
+ communities = {int(k): v for k, v in analysis['communities'].items()}
609
+ labels = {int(k): v for k, v in labels_raw.items()}
610
+
611
+ to_svg(G, communities, 'graphify-out/graph.svg', community_labels=labels or None)
612
+ print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
613
+ "
614
+ ```
615
+
616
+ ### Step 7c - GraphML export (only if --graphml flag)
617
+
618
+ ```bash
619
+ $(cat graphify-out/.graphify_python) -c "
620
+ import json
621
+ from graphify.build import build_from_json
622
+ from graphify.export import to_graphml
623
+ from pathlib import Path
624
+
625
+ extraction = json.loads(Path('.graphify_extract.json').read_text())
626
+ analysis = json.loads(Path('.graphify_analysis.json').read_text())
627
+
628
+ G = build_from_json(extraction, directed=IS_DIRECTED)
629
+ communities = {int(k): v for k, v in analysis['communities'].items()}
630
+
631
+ to_graphml(G, communities, 'graphify-out/graph.graphml')
632
+ print('graph.graphml written - open in Gephi, yEd, or any GraphML tool')
633
+ "
634
+ ```
635
+
636
+ ### Step 7d - MCP server (only if --mcp flag)
637
+
638
+ ```bash
639
+ python3 -m graphify.serve graphify-out/graph.json
640
+ ```
641
+
642
+ This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live.
643
+
644
+ To configure in Claude Desktop, add to `claude_desktop_config.json`:
645
+ ```json
646
+ {
647
+ "mcpServers": {
648
+ "graphify": {
649
+ "command": "python3",
650
+ "args": ["-m", "graphify.serve", "/absolute/path/to/graphify-out/graph.json"]
651
+ }
652
+ }
653
+ }
654
+ ```
655
+
656
+ ### Step 8 - Token reduction benchmark (only if total_words > 5000)
657
+
658
+ If `total_words` from `.graphify_detect.json` is greater than 5,000, run:
659
+
660
+ ```bash
661
+ $(cat graphify-out/.graphify_python) -c "
662
+ import json
663
+ from graphify.benchmark import run_benchmark, print_benchmark
664
+ from pathlib import Path
665
+
666
+ detection = json.loads(Path('.graphify_detect.json').read_text())
667
+ result = run_benchmark('graphify-out/graph.json', corpus_words=detection['total_words'])
668
+ print_benchmark(result)
669
+ "
670
+ ```
671
+
672
+ Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora.
673
+
674
+ ---
675
+
676
+ ### Step 9 - Save manifest, update cost tracker, clean up, and report
677
+
678
+ ```bash
679
+ $(cat graphify-out/.graphify_python) -c "
680
+ import json
681
+ from pathlib import Path
682
+ from datetime import datetime, timezone
683
+ from graphify.detect import save_manifest
684
+
685
+ # Save manifest for --update
686
+ detect = json.loads(Path('.graphify_detect.json').read_text())
687
+ extract = json.loads(Path('.graphify_extract.json').read_text())
688
+ # Stamp only semantic files that produced output so a failed chunk is re-queued next run, not lost (#2015).
689
+ from graphify.cli import _stamped_manifest_files
690
+ _corpus = detect.get('all_files') or detect['files']
691
+ _manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'))
692
+ _sem_types = ('document', 'paper', 'image')
693
+ _dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl}
694
+ _stamped = {f for fl in _manifest_files.values() for f in fl}
695
+ _cleared = _dispatched - _stamped
696
+ _scan = {f for fl in _corpus.values() for f in fl}
697
+ save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
698
+
699
+ # Update cumulative cost tracker
700
+ input_tok = extract.get('input_tokens', 0)
701
+ output_tok = extract.get('output_tokens', 0)
702
+
703
+ cost_path = Path('graphify-out/cost.json')
704
+ if cost_path.exists():
705
+ cost = json.loads(cost_path.read_text())
706
+ else:
707
+ cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
708
+
709
+ cost['runs'].append({
710
+ 'date': datetime.now(timezone.utc).isoformat(),
711
+ 'input_tokens': input_tok,
712
+ 'output_tokens': output_tok,
713
+ 'files': detect.get('total_files', 0),
714
+ })
715
+ cost['total_input_tokens'] += input_tok
716
+ cost['total_output_tokens'] += output_tok
717
+ cost_path.write_text(json.dumps(cost, indent=2))
718
+
719
+ print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
720
+ print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
721
+ "
722
+ rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json; find . -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
723
+ rm -f graphify-out/.needs_update 2>/dev/null || true
724
+ ```
725
+
726
+ Tell the user (omit the obsidian line unless --obsidian was given):
727
+ ```
728
+ Graph complete. Outputs in PATH_TO_DIR/graphify-out/
729
+
730
+ graph.html - interactive graph, open in browser
731
+ GRAPH_REPORT.md - audit report
732
+ graph.json - raw graph data
733
+ obsidian/ - Obsidian vault (only if --obsidian was given)
734
+ ```
735
+
736
+ If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
737
+
738
+ Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
739
+
740
+ Then paste these sections from GRAPH_REPORT.md directly into the chat:
741
+ - God Nodes
742
+ - Surprising Connections
743
+ - Suggested Questions
744
+
745
+ Do NOT paste the full report - just those three sections. Keep it concise.
746
+
747
+ Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:
748
+
749
+ > "The most interesting question this graph can answer: **[question]**. Want me to trace it?"
750
+
751
+ If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report.
752
+
753
+ The graph is the map. Your job after the pipeline is to be the guide.
754
+
755
+ ---
756
+
757
+ ## For --update (incremental re-extraction)
758
+
759
+ Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
760
+
761
+ ```bash
762
+ $(cat graphify-out/.graphify_python) -c "
763
+ import sys, json
764
+ from graphify.detect import detect_incremental, save_manifest
765
+ from pathlib import Path
766
+
767
+ result = detect_incremental(Path('INPUT_PATH'))
768
+ new_total = result.get('new_total', 0)
769
+ print(json.dumps(result, indent=2))
770
+ Path('.graphify_incremental.json').write_text(json.dumps(result))
771
+ deleted = list(result.get('deleted_files', []))
772
+ if new_total == 0 and not deleted:
773
+ print('No files changed since last run. Nothing to update.')
774
+ raise SystemExit(0)
775
+ if deleted:
776
+ print(f'{len(deleted)} deleted file(s) to prune.')
777
+ if new_total > 0:
778
+ print(f'{new_total} new/changed file(s) to re-extract.')
779
+ "
780
+ ```
781
+
782
+ If new files exist, first check whether all changed files are code files:
783
+
784
+ ```bash
785
+ $(cat graphify-out/.graphify_python) -c "
786
+ import json
787
+ from pathlib import Path
788
+
789
+ result = json.loads(open('.graphify_incremental.json').read()) if Path('.graphify_incremental.json').exists() else {}
790
+ code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts'}
791
+ new_files = result.get('new_files', {})
792
+ all_changed = [f for files in new_files.values() for f in files]
793
+ code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
794
+ print('code_only:', code_only)
795
+ "
796
+ ```
797
+
798
+ If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8.
799
+
800
+ If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
801
+
802
+
803
+ If no new files exist (only deletions), create an empty extraction so the merge step can prune:
804
+
805
+ ```bash
806
+ if [ ! -f graphify-out/.graphify_extract.json ]; then
807
+ echo '[graphify update] Only deletions -- creating empty extraction for merge.'
808
+ $(cat graphify-out/.graphify_python) -c "
809
+ import json
810
+ from pathlib import Path
811
+ Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
812
+ "
813
+ fi
814
+ ```
815
+
816
+
817
+ Then:
818
+
819
+ ```bash
820
+ $(cat graphify-out/.graphify_python) -c "
821
+ import sys, json
822
+ from graphify.build import build_from_json
823
+ from graphify.export import to_json
824
+ from networkx.readwrite import json_graph
825
+ import networkx as nx
826
+ from pathlib import Path
827
+
828
+ # Load existing graph
829
+ existing_data = json.loads(Path('graphify-out/graph.json').read_text())
830
+ G_existing = json_graph.node_link_graph(existing_data, edges='links')
831
+
832
+ # Load new extraction
833
+ new_extraction = json.loads(Path('.graphify_extract.json').read_text())
834
+ G_new = build_from_json(new_extraction, directed=IS_DIRECTED)
835
+
836
+ # Merge: new nodes/edges into existing graph
837
+ G_existing.update(G_new)
838
+ print(f'Merged: {G_existing.number_of_nodes()} nodes, {G_existing.number_of_edges()} edges')
839
+ "
840
+ ```
841
+
842
+ Then run Steps 4–8 on the merged graph as normal.
843
+
844
+ After Step 4, show the graph diff:
845
+
846
+ ```bash
847
+ $(cat graphify-out/.graphify_python) -c "
848
+ import json
849
+ from graphify.analyze import graph_diff
850
+ from graphify.build import build_from_json
851
+ from networkx.readwrite import json_graph
852
+ import networkx as nx
853
+ from pathlib import Path
854
+
855
+ # Load old graph (before update) from backup written before merge
856
+ old_data = json.loads(Path('.graphify_old.json').read_text()) if Path('.graphify_old.json').exists() else None
857
+ new_extract = json.loads(Path('.graphify_extract.json').read_text())
858
+ G_new = build_from_json(new_extract, directed=IS_DIRECTED)
859
+
860
+ if old_data:
861
+ G_old = json_graph.node_link_graph(old_data, edges='links')
862
+ diff = graph_diff(G_old, G_new)
863
+ print(diff['summary'])
864
+ if diff['new_nodes']:
865
+ print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5]))
866
+ if diff['new_edges']:
867
+ print('New edges:', len(diff['new_edges']))
868
+ "
869
+ ```
870
+
871
+ Before the merge step, save the old graph: `cp graphify-out/graph.json .graphify_old.json`
872
+ Clean up after: `rm -f .graphify_old.json`
873
+
874
+ ---
875
+
876
+ ## For --cluster-only
877
+
878
+ Skip Steps 1–3. Load the existing graph from `graphify-out/graph.json` and re-run clustering:
879
+
880
+ ```bash
881
+ $(cat graphify-out/.graphify_python) -c "
882
+ import sys, json
883
+ from graphify.cluster import cluster, score_all
884
+ from graphify.analyze import god_nodes, surprising_connections
885
+ from graphify.report import generate
886
+ from graphify.export import to_json
887
+ from networkx.readwrite import json_graph
888
+ import networkx as nx
889
+ from pathlib import Path
890
+
891
+ data = json.loads(Path('graphify-out/graph.json').read_text())
892
+ G = json_graph.node_link_graph(data, edges='links')
893
+
894
+ detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None,
895
+ 'files': {'code': [], 'document': [], 'paper': []}}
896
+ tokens = {'input': 0, 'output': 0}
897
+
898
+ communities = cluster(G)
899
+ cohesion = score_all(G, communities)
900
+ gods = god_nodes(G)
901
+ surprises = surprising_connections(G, communities)
902
+ labels = {cid: 'Community ' + str(cid) for cid in communities}
903
+
904
+ report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, '.')
905
+ Path('graphify-out/GRAPH_REPORT.md').write_text(report)
906
+ # No community_labels here - 'labels' are still placeholders at this point;
907
+ # Step 5 re-exports graph.json with the curated names (#2490).
908
+ to_json(G, communities, 'graphify-out/graph.json')
909
+
910
+ analysis = {
911
+ 'communities': {str(k): v for k, v in communities.items()},
912
+ 'cohesion': {str(k): v for k, v in cohesion.items()},
913
+ 'gods': gods,
914
+ 'surprises': surprises,
915
+ }
916
+ Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
917
+ print(f'Re-clustered: {len(communities)} communities')
918
+ "
919
+ ```
920
+
921
+ Then run Steps 5–9 as normal (label communities, generate viz, benchmark, clean up, report).
922
+
923
+ ---
924
+
925
+ ## For /graphify query
926
+
927
+ Two traversal modes - choose based on the question:
928
+
929
+ | Mode | Flag | Best for |
930
+ |------|------|----------|
931
+ | BFS (default) | _(none)_ | "What is X connected to?" - broad context, nearest neighbors first |
932
+ | DFS | `--dfs` | "How does X reach Y?" - trace a specific chain or dependency path |
933
+
934
+ First check the graph exists:
935
+ ```bash
936
+ $(cat graphify-out/.graphify_python) -c "
937
+ from pathlib import Path
938
+ if not Path('graphify-out/graph.json').exists():
939
+ print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
940
+ raise SystemExit(1)
941
+ "
942
+ ```
943
+ If it fails, stop and tell the user to run `/graphify <path>` first.
944
+
945
+ Load `graphify-out/graph.json`, then:
946
+
947
+ 1. Find the 1-3 nodes whose label best matches key terms in the question.
948
+ 2. Run the appropriate traversal from each starting node.
949
+ 3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
950
+ 4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
951
+ 5. If the graph lacks enough information, say so - do not hallucinate edges.
952
+
953
+ ```bash
954
+ $(cat graphify-out/.graphify_python) -c "
955
+ import sys, json
956
+ from networkx.readwrite import json_graph
957
+ import networkx as nx
958
+ from pathlib import Path
959
+
960
+ data = json.loads(Path('graphify-out/graph.json').read_text())
961
+ G = json_graph.node_link_graph(data, edges='links')
962
+
963
+ question = 'QUESTION'
964
+ mode = 'MODE' # 'bfs' or 'dfs'
965
+ terms = [t.lower() for t in question.split() if len(t) > 3]
966
+
967
+ # Find best-matching start nodes
968
+ scored = []
969
+ for nid, ndata in G.nodes(data=True):
970
+ label = ndata.get('label', '').lower()
971
+ score = sum(1 for t in terms if t in label)
972
+ if score > 0:
973
+ scored.append((score, nid))
974
+ scored.sort(reverse=True)
975
+ start_nodes = [nid for _, nid in scored[:3]]
976
+
977
+ if not start_nodes:
978
+ print('No matching nodes found for query terms:', terms)
979
+ sys.exit(0)
980
+
981
+ subgraph_nodes = set()
982
+ subgraph_edges = []
983
+
984
+ if mode == 'dfs':
985
+ # DFS: follow one path as deep as possible before backtracking.
986
+ # Depth-limited to 6 to avoid traversing the whole graph.
987
+ visited = set()
988
+ stack = [(n, 0) for n in reversed(start_nodes)]
989
+ while stack:
990
+ node, depth = stack.pop()
991
+ if node in visited or depth > 6:
992
+ continue
993
+ visited.add(node)
994
+ subgraph_nodes.add(node)
995
+ for neighbor in G.neighbors(node):
996
+ if neighbor not in visited:
997
+ stack.append((neighbor, depth + 1))
998
+ subgraph_edges.append((node, neighbor))
999
+ else:
1000
+ # BFS: explore all neighbors layer by layer up to depth 3.
1001
+ frontier = set(start_nodes)
1002
+ subgraph_nodes = set(start_nodes)
1003
+ for _ in range(3):
1004
+ next_frontier = set()
1005
+ for n in frontier:
1006
+ for neighbor in G.neighbors(n):
1007
+ if neighbor not in subgraph_nodes:
1008
+ next_frontier.add(neighbor)
1009
+ subgraph_edges.append((n, neighbor))
1010
+ subgraph_nodes.update(next_frontier)
1011
+ frontier = next_frontier
1012
+
1013
+ # Token-budget aware output: rank by relevance, cut at budget (~4 chars/token)
1014
+ token_budget = BUDGET # default 2000
1015
+ char_budget = token_budget * 4
1016
+
1017
+ # Score each node by term overlap for ranked output
1018
+ def relevance(nid):
1019
+ label = G.nodes[nid].get('label', '').lower()
1020
+ return sum(1 for t in terms if t in label)
1021
+
1022
+ ranked_nodes = sorted(subgraph_nodes, key=relevance, reverse=True)
1023
+
1024
+ lines = [f'Traversal: {mode.upper()} | Start: {[G.nodes[n].get(\"label\",n) for n in start_nodes]} | {len(subgraph_nodes)} nodes']
1025
+ for nid in ranked_nodes:
1026
+ d = G.nodes[nid]
1027
+ lines.append(f' NODE {d.get(\"label\", nid)} [src={d.get(\"source_file\",\"\")} loc={d.get(\"source_location\",\"\")}]')
1028
+ for u, v in subgraph_edges:
1029
+ if u in subgraph_nodes and v in subgraph_nodes:
1030
+ _raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
1031
+ lines.append(f' EDGE {G.nodes[u].get(\"label\",u)} --{d.get(\"relation\",\"\")} [{d.get(\"confidence\",\"\")}]--> {G.nodes[v].get(\"label\",v)}')
1032
+
1033
+ output = '\n'.join(lines)
1034
+ if len(output) > char_budget:
1035
+ output = output[:char_budget] + f'\n... (truncated at ~{token_budget} token budget - use --budget N for more)'
1036
+ print(output)
1037
+ "
1038
+ ```
1039
+
1040
+ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
1041
+
1042
+ After writing the answer, save it back into the graph so it improves future queries:
1043
+
1044
+ ```bash
1045
+ $(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
1046
+ ```
1047
+
1048
+ Replace `QUESTION` with the question, `ANSWER` with your full answer text, `SOURCE_NODES` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
1049
+
1050
+ ---
1051
+
1052
+ ## For /graphify path
1053
+
1054
+ Find the shortest path between two named concepts in the graph.
1055
+
1056
+ First check the graph exists:
1057
+ ```bash
1058
+ $(cat graphify-out/.graphify_python) -c "
1059
+ from pathlib import Path
1060
+ if not Path('graphify-out/graph.json').exists():
1061
+ print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
1062
+ raise SystemExit(1)
1063
+ "
1064
+ ```
1065
+ If it fails, stop and tell the user to run `/graphify <path>` first.
1066
+
1067
+ ```bash
1068
+ $(cat graphify-out/.graphify_python) -c "
1069
+ import json, sys
1070
+ import networkx as nx
1071
+ from networkx.readwrite import json_graph
1072
+ from pathlib import Path
1073
+
1074
+ data = json.loads(Path('graphify-out/graph.json').read_text())
1075
+ G = json_graph.node_link_graph(data, edges='links')
1076
+
1077
+ a_term = 'NODE_A'
1078
+ b_term = 'NODE_B'
1079
+
1080
+ def find_node(term):
1081
+ term = term.lower()
1082
+ scored = sorted(
1083
+ [(sum(1 for w in term.split() if w in G.nodes[n].get('label','').lower()), n)
1084
+ for n in G.nodes()],
1085
+ reverse=True
1086
+ )
1087
+ return scored[0][1] if scored and scored[0][0] > 0 else None
1088
+
1089
+ src = find_node(a_term)
1090
+ tgt = find_node(b_term)
1091
+
1092
+ if not src or not tgt:
1093
+ print(f'Could not find nodes matching: {a_term!r} or {b_term!r}')
1094
+ sys.exit(0)
1095
+
1096
+ try:
1097
+ path = nx.shortest_path(G, src, tgt)
1098
+ print(f'Shortest path ({len(path)-1} hops):')
1099
+ for i, nid in enumerate(path):
1100
+ label = G.nodes[nid].get('label', nid)
1101
+ if i < len(path) - 1:
1102
+ _raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
1103
+ rel = edge.get('relation', '')
1104
+ conf = edge.get('confidence', '')
1105
+ print(f' {label} --{rel}--> [{conf}]')
1106
+ else:
1107
+ print(f' {label}')
1108
+ except nx.NetworkXNoPath:
1109
+ print(f'No path found between {a_term!r} and {b_term!r}')
1110
+ except nx.NodeNotFound as e:
1111
+ print(f'Node not found: {e}')
1112
+ "
1113
+ ```
1114
+
1115
+ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then explain the path in plain language - what each hop means, why it's significant.
1116
+
1117
+ After writing the explanation, save it back:
1118
+
1119
+ ```bash
1120
+ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
1121
+ ```
1122
+
1123
+ ---
1124
+
1125
+ ## For /graphify explain
1126
+
1127
+ Give a plain-language explanation of a single node - everything connected to it.
1128
+
1129
+ First check the graph exists:
1130
+ ```bash
1131
+ $(cat graphify-out/.graphify_python) -c "
1132
+ from pathlib import Path
1133
+ if not Path('graphify-out/graph.json').exists():
1134
+ print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
1135
+ raise SystemExit(1)
1136
+ "
1137
+ ```
1138
+ If it fails, stop and tell the user to run `/graphify <path>` first.
1139
+
1140
+ ```bash
1141
+ $(cat graphify-out/.graphify_python) -c "
1142
+ import json, sys
1143
+ import networkx as nx
1144
+ from networkx.readwrite import json_graph
1145
+ from pathlib import Path
1146
+
1147
+ data = json.loads(Path('graphify-out/graph.json').read_text())
1148
+ G = json_graph.node_link_graph(data, edges='links')
1149
+
1150
+ term = 'NODE_NAME'
1151
+ term_lower = term.lower()
1152
+
1153
+ # Find best matching node
1154
+ scored = sorted(
1155
+ [(sum(1 for w in term_lower.split() if w in G.nodes[n].get('label','').lower()), n)
1156
+ for n in G.nodes()],
1157
+ reverse=True
1158
+ )
1159
+ if not scored or scored[0][0] == 0:
1160
+ print(f'No node matching {term!r}')
1161
+ sys.exit(0)
1162
+
1163
+ nid = scored[0][1]
1164
+ data_n = G.nodes[nid]
1165
+ print(f'NODE: {data_n.get(\"label\", nid)}')
1166
+ print(f' source: {data_n.get(\"source_file\",\"unknown\")}')
1167
+ print(f' type: {data_n.get(\"file_type\",\"unknown\")}')
1168
+ print(f' degree: {G.degree(nid)}')
1169
+ print()
1170
+ print('CONNECTIONS:')
1171
+ for neighbor in G.neighbors(nid):
1172
+ _raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
1173
+ nlabel = G.nodes[neighbor].get('label', neighbor)
1174
+ rel = edge.get('relation', '')
1175
+ conf = edge.get('confidence', '')
1176
+ src_file = G.nodes[neighbor].get('source_file', '')
1177
+ print(f' --{rel}--> {nlabel} [{conf}] ({src_file})')
1178
+ "
1179
+ ```
1180
+
1181
+ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations.
1182
+
1183
+ After writing the explanation, save it back:
1184
+
1185
+ ```bash
1186
+ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
1187
+ ```
1188
+
1189
+ ---
1190
+
1191
+ ## For /graphify add
1192
+
1193
+ Fetch a URL and add it to the corpus, then update the graph.
1194
+
1195
+ ```bash
1196
+ $(cat graphify-out/.graphify_python) -c "
1197
+ import sys
1198
+ from graphify.ingest import ingest
1199
+ from pathlib import Path
1200
+
1201
+ try:
1202
+ out = ingest('URL', Path('./raw'), author='AUTHOR', contributor='CONTRIBUTOR')
1203
+ print(f'Saved to {out}')
1204
+ except ValueError as e:
1205
+ print(f'error: {e}', file=sys.stderr)
1206
+ sys.exit(1)
1207
+ except RuntimeError as e:
1208
+ print(f'error: {e}', file=sys.stderr)
1209
+ sys.exit(1)
1210
+ "
1211
+ ```
1212
+
1213
+ Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph.
1214
+
1215
+ Supported URL types (auto-detected):
1216
+ - Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
1217
+ - arXiv → abstract + metadata saved as `.md`
1218
+ - PDF → downloaded as `.pdf`
1219
+ - Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
1220
+ - Any webpage → converted to markdown via html2text
1221
+
1222
+ ---
1223
+
1224
+ ## For --watch
1225
+
1226
+ Start a background watcher that monitors a folder and auto-updates the graph when files change.
1227
+
1228
+ ```bash
1229
+ python3 -m graphify.watch INPUT_PATH --debounce 3
1230
+ ```
1231
+
1232
+ Replace INPUT_PATH with the folder to watch. Behavior depends on what changed:
1233
+
1234
+ - **Code files only (.py, .ts, .go, etc.):** re-runs AST extraction + rebuild + cluster immediately, no LLM needed. `graph.json` and `GRAPH_REPORT.md` are updated automatically.
1235
+ - **Docs, papers, or images:** writes a `graphify-out/needs_update` flag and prints a notification to run `/graphify --update` (LLM semantic re-extraction required).
1236
+
1237
+ Debounce (default 3s): waits until file activity stops before triggering, so a wave of parallel agent writes doesn't trigger a rebuild per file.
1238
+
1239
+ Press Ctrl+C to stop.
1240
+
1241
+ For agentic workflows: run `--watch` in a background terminal. Code changes from agent waves are picked up automatically between waves. If agents are also writing docs or notes, you'll need a manual `/graphify --update` after those waves.
1242
+
1243
+ ---
1244
+
1245
+ ## For git commit hook
1246
+
1247
+ Install a post-commit hook that auto-rebuilds the graph after every commit. No background process needed - triggers once per commit, works with any editor.
1248
+
1249
+ ```bash
1250
+ graphify hook install # install
1251
+ graphify hook uninstall # remove
1252
+ graphify hook status # check
1253
+ ```
1254
+
1255
+ After every `git commit`, the hook detects which code files changed (via `git diff HEAD~1`), re-runs AST extraction on those files, and rebuilds `graph.json` and `GRAPH_REPORT.md`. Doc/image changes are ignored by the hook - run `/graphify --update` manually for those.
1256
+
1257
+ If a post-commit hook already exists, graphify appends to it rather than replacing it.
1258
+
1259
+ ---
1260
+
1261
+ ## For native CLAUDE.md integration
1262
+
1263
+ Run once per project to make graphify always-on in Claude Code sessions:
1264
+
1265
+ ```bash
1266
+ graphify claude install
1267
+ ```
1268
+
1269
+ This writes a `## graphify` section to the local `CLAUDE.md` that instructs Claude to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions.
1270
+
1271
+ ```bash
1272
+ graphify claude uninstall # remove the section
1273
+ ```
1274
+
1275
+ ---
1276
+
1277
+ ## Honesty Rules
1278
+
1279
+ - Never invent an edge. If unsure, use AMBIGUOUS.
1280
+ - Never skip the corpus check warning.
1281
+ - Always show token cost in the report.
1282
+ - Never hide cohesion scores behind symbols - show the raw number.
1283
+ - Never run HTML viz on a graph with more than 5,000 nodes without warning the user.