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