@pilllesss/yorn 1.0.0

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 (95) hide show
  1. package/README.md +84 -0
  2. package/dist/modes/interactive/theme/dark.json +90 -0
  3. package/dist/modes/interactive/theme/light.json +89 -0
  4. package/dist/modes/interactive/theme/theme-schema.json +352 -0
  5. package/dist/providers/data/.manifest.json +1 -0
  6. package/dist/providers/data/amazon-bedrock.json +1 -0
  7. package/dist/providers/data/ant-ling.json +1 -0
  8. package/dist/providers/data/anthropic.json +1 -0
  9. package/dist/providers/data/azure-openai-responses.json +1 -0
  10. package/dist/providers/data/baseten.json +1 -0
  11. package/dist/providers/data/cerebras.json +1 -0
  12. package/dist/providers/data/cloudflare-ai-gateway.json +1 -0
  13. package/dist/providers/data/cloudflare-workers-ai.json +1 -0
  14. package/dist/providers/data/deepseek.json +1 -0
  15. package/dist/providers/data/fireworks.json +1 -0
  16. package/dist/providers/data/github-copilot.json +1 -0
  17. package/dist/providers/data/google-vertex.json +1 -0
  18. package/dist/providers/data/google.json +1 -0
  19. package/dist/providers/data/groq.json +1 -0
  20. package/dist/providers/data/huggingface.json +1 -0
  21. package/dist/providers/data/kimi-coding.json +1 -0
  22. package/dist/providers/data/minimax-cn.json +1 -0
  23. package/dist/providers/data/minimax.json +1 -0
  24. package/dist/providers/data/mistral.json +1 -0
  25. package/dist/providers/data/moonshotai-cn.json +1 -0
  26. package/dist/providers/data/moonshotai.json +1 -0
  27. package/dist/providers/data/nvidia.json +1 -0
  28. package/dist/providers/data/openai-codex.json +1 -0
  29. package/dist/providers/data/openai.json +1 -0
  30. package/dist/providers/data/opencode-go.json +1 -0
  31. package/dist/providers/data/opencode.json +1 -0
  32. package/dist/providers/data/openrouter.json +1 -0
  33. package/dist/providers/data/qwen-token-plan-cn.json +1 -0
  34. package/dist/providers/data/qwen-token-plan-individual.json +1 -0
  35. package/dist/providers/data/qwen-token-plan.json +1 -0
  36. package/dist/providers/data/together.json +1 -0
  37. package/dist/providers/data/vercel-ai-gateway.json +1 -0
  38. package/dist/providers/data/xai.json +1 -0
  39. package/dist/providers/data/xiaomi-token-plan-ams.json +1 -0
  40. package/dist/providers/data/xiaomi-token-plan-cn.json +1 -0
  41. package/dist/providers/data/xiaomi-token-plan-sgp.json +1 -0
  42. package/dist/providers/data/xiaomi.json +1 -0
  43. package/dist/providers/data/zai-coding-cn.json +1 -0
  44. package/dist/providers/data/zai.json +1 -0
  45. package/dist/skills/add-provider/SKILL.md +151 -0
  46. package/dist/skills/agent-browser/SKILL.md +51 -0
  47. package/dist/skills/frontend-design/LICENSE.txt +177 -0
  48. package/dist/skills/frontend-design/SKILL.md +55 -0
  49. package/dist/skills/goal/SKILL.md +44 -0
  50. package/dist/skills/goal/pyproject.toml +17 -0
  51. package/dist/skills/goal/src/goal/__init__.py +52 -0
  52. package/dist/skills/graphify/SKILL.md +710 -0
  53. package/dist/skills/graphify/references/add-watch.md +56 -0
  54. package/dist/skills/graphify/references/exports.md +87 -0
  55. package/dist/skills/graphify/references/extraction-spec.md +70 -0
  56. package/dist/skills/graphify/references/github-and-merge.md +46 -0
  57. package/dist/skills/graphify/references/hooks.md +33 -0
  58. package/dist/skills/graphify/references/query.md +311 -0
  59. package/dist/skills/graphify/references/transcribe.md +52 -0
  60. package/dist/skills/graphify/references/update.md +210 -0
  61. package/dist/skills/screenshot/SKILL.md +267 -0
  62. package/dist/skills/screenshot/scripts/ensure_macos_permissions.sh +54 -0
  63. package/dist/skills/screenshot/scripts/macos_display_info.swift +22 -0
  64. package/dist/skills/screenshot/scripts/macos_permissions.swift +40 -0
  65. package/dist/skills/screenshot/scripts/macos_window_info.swift +126 -0
  66. package/dist/skills/screenshot/scripts/take_screenshot.ps1 +163 -0
  67. package/dist/skills/screenshot/scripts/take_screenshot.py +585 -0
  68. package/dist/skills/security-best-practices/LICENSE.txt +201 -0
  69. package/dist/skills/security-best-practices/SKILL.md +86 -0
  70. package/dist/skills/security-best-practices/agents/openai.yaml +4 -0
  71. package/dist/skills/security-best-practices/references/golang-general-backend-security.md +826 -0
  72. package/dist/skills/security-best-practices/references/javascript-express-web-server-security.md +1158 -0
  73. package/dist/skills/security-best-practices/references/javascript-general-web-frontend-security.md +747 -0
  74. package/dist/skills/security-best-practices/references/javascript-jquery-web-frontend-security.md +678 -0
  75. package/dist/skills/security-best-practices/references/javascript-typescript-nextjs-web-server-security.md +1144 -0
  76. package/dist/skills/security-best-practices/references/javascript-typescript-react-web-frontend-security.md +990 -0
  77. package/dist/skills/security-best-practices/references/javascript-typescript-vue-web-frontend-security.md +791 -0
  78. package/dist/skills/security-best-practices/references/python-django-web-server-security.md +882 -0
  79. package/dist/skills/security-best-practices/references/python-fastapi-web-server-security.md +1036 -0
  80. package/dist/skills/security-best-practices/references/python-flask-web-server-security.md +705 -0
  81. package/dist/skills/theme-factory/LICENSE.txt +202 -0
  82. package/dist/skills/theme-factory/SKILL.md +59 -0
  83. package/dist/skills/theme-factory/theme-showcase.pdf +0 -0
  84. package/dist/skills/theme-factory/themes/arctic-frost.md +19 -0
  85. package/dist/skills/theme-factory/themes/botanical-garden.md +19 -0
  86. package/dist/skills/theme-factory/themes/desert-rose.md +19 -0
  87. package/dist/skills/theme-factory/themes/forest-canopy.md +19 -0
  88. package/dist/skills/theme-factory/themes/golden-hour.md +19 -0
  89. package/dist/skills/theme-factory/themes/midnight-galaxy.md +19 -0
  90. package/dist/skills/theme-factory/themes/modern-minimalist.md +19 -0
  91. package/dist/skills/theme-factory/themes/ocean-depths.md +19 -0
  92. package/dist/skills/theme-factory/themes/sunset-boulevard.md +19 -0
  93. package/dist/skills/theme-factory/themes/tech-innovation.md +19 -0
  94. package/dist/yorn.cjs +1773 -0
  95. package/package.json +86 -0
@@ -0,0 +1,710 @@
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 https://github.com/<owner>/<repo> # clone repo then run full pipeline on it
16
+ /graphify https://github.com/<owner>/<repo> --branch <branch> # clone a specific branch
17
+ /graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
18
+ /graphify <path> --mode deep # thorough extraction, richer INFERRED edges
19
+ /graphify <path> --update # incremental - re-extract only new/changed files
20
+ /graphify <path> --directed # build directed graph (preserves edge direction: source→target)
21
+ /graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
22
+ /graphify <path> --cluster-only # rerun clustering on existing graph
23
+ /graphify <path> --no-viz # skip visualization, just report + JSON
24
+ /graphify <path> --html # (HTML is generated by default - this flag is a no-op)
25
+ /graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
26
+ /graphify <path> --graphml # export graph.graphml (Gephi, yEd)
27
+ /graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
28
+ /graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
29
+ /graphify <path> --falkordb # generate graphify-out/cypher.txt for FalkorDB
30
+ /graphify <path> --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB
31
+ /graphify <path> --mcp # start MCP stdio server for agent access
32
+ /graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
33
+ /graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
34
+ /graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
35
+ /graphify add <url> # fetch URL, save to ./raw, update graph
36
+ /graphify add <url> --author "Name" # tag who wrote it
37
+ /graphify add <url> --contributor "Name" # tag who added it to the corpus
38
+ /graphify query "<question>" # BFS traversal - broad context
39
+ /graphify query "<question>" --dfs # DFS - trace a specific path
40
+ /graphify query "<question>" --budget 1500 # cap answer at N tokens
41
+ /graphify path "AuthModule" "Database" # shortest path between two concepts
42
+ /graphify explain "SwinTransformer" # plain-language explanation of a node
43
+ ```
44
+
45
+ ## What graphify is for
46
+
47
+ Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
48
+
49
+ ## What You Must Do When Invoked
50
+
51
+ 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.
52
+
53
+ **Fast path — existing graph:** Before doing anything else, check whether `graphify-out/graph.json` exists. The expected location is `graphify-out/graph.json` relative to the **current working directory** (i.e. the project root where you are running commands). If it exists AND the user's request is a natural-language question about the codebase (e.g. "How does X work?", "What calls Y?", "Trace the data flow through Z") and NOT an explicit rebuild command (`--update`, `--cluster-only`, or a bare path/URL that implies fresh extraction): **skip Steps 1–5 entirely and jump straight to `## For /graphify query`.** Run `graphify query "<question>"` immediately. Do not run detect. Do not check corpus size. Do not ask the user to narrow. The graph is already built — use it.
54
+
55
+ If no path was given, use `.` (current directory). Do not ask the user for a path.
56
+
57
+ If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
58
+
59
+ Follow these steps in order. Do not skip steps.
60
+
61
+ ### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
62
+
63
+ Only when the path is one or more `https://github.com/...` URLs, or several local subfolders to merge. See `references/github-and-merge.md` for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step.
64
+
65
+ ### Step 1 - Ensure graphify is installed
66
+
67
+ ```bash
68
+ # Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs)
69
+ PYTHON=""
70
+ GRAPHIFY_BIN=$(which graphify 2>/dev/null)
71
+ # 1. uv tool installs — most reliable on modern Mac/Linux
72
+ if [ -z "$PYTHON" ] && command -v uv >/dev/null 2>&1; then
73
+ _UV_PY=$(uv tool run --from graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
74
+ if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
75
+ fi
76
+ # 2. Read shebang from graphify binary (pipx and direct pip installs)
77
+ if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then
78
+ _SHEBANG=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
79
+ case "$_SHEBANG" in
80
+ *[!a-zA-Z0-9/_.@-]*) ;;
81
+ *) "$_SHEBANG" -c "import graphify" 2>/dev/null && PYTHON="$_SHEBANG" ;;
82
+ esac
83
+ fi
84
+ # 3. Fall back to python3
85
+ if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
86
+ if ! "$PYTHON" -c "import graphify" 2>/dev/null; then
87
+ if command -v uv >/dev/null 2>&1; then
88
+ uv tool install --upgrade graphifyy -q 2>&1 | tail -3
89
+ _UV_PY=$(uv tool run --from graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
90
+ if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
91
+ else
92
+ "$PYTHON" -m pip install graphifyy -q 2>/dev/null \
93
+ || "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
94
+ fi
95
+ fi
96
+ # Write interpreter path for all subsequent steps (persists across invocations)
97
+ mkdir -p graphify-out
98
+ "$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
99
+ # Save scan root so `graphify update` (no args) knows where to look next time
100
+ echo "$(cd INPUT_PATH && pwd)" > graphify-out/.graphify_root
101
+ ```
102
+
103
+ If the import succeeds, print nothing and move straight to Step 2.
104
+
105
+ **In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
106
+
107
+ ### Step 2 - Detect files
108
+
109
+ ```bash
110
+ $(cat graphify-out/.graphify_python) -c "
111
+ import json
112
+ from graphify.detect import detect
113
+ from pathlib import Path
114
+ result = detect(Path('INPUT_PATH'))
115
+ # Write the sidecar from Python, not a shell redirect, so the same block renders
116
+ # on PowerShell hosts without console-encoding drift (#2528).
117
+ Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
118
+ print(f'Detected {result[\"total_files\"]} files')
119
+ "
120
+ ```
121
+
122
+ 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:
123
+
124
+ ```
125
+ Corpus: X files · ~Y words
126
+ code: N files (.py .ts .go ...)
127
+ docs: N files (.md .txt ...)
128
+ papers: N files (.pdf ...)
129
+ images: N files
130
+ video: N files (.mp4 .mp3 ...)
131
+ ```
132
+
133
+ Omit any category with 0 files from the summary.
134
+
135
+ Then act on it:
136
+ - If `total_files` is 0: stop with "No supported files found in [path]."
137
+ - 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).
138
+ - If `total_words` > 2,000,000 OR `total_files` > 500: show the warning. Then compute the top 5 first-level subdirectories by file count:
139
+ - Read `scan_root` from the detect JSON (always an absolute path to the resolved INPUT_PATH).
140
+ - Concatenate all file lists across all types (`code`, `document`, `paper`, `image`, `video`).
141
+ - Filter out any path that starts with `scan_root + "/graphify-out/"` to exclude converted sidecars.
142
+ - For each file, strip the `scan_root` prefix and take the first path component. Files directly in `scan_root` with no subdirectory count as `(root)`.
143
+ - If all files are in `(root)` with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest `--no-cluster` to skip the expensive clustering step and proceed.
144
+ - Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding.
145
+ - Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
146
+
147
+ ### Step 2.5 - Video and audio (only if video files detected)
148
+
149
+ Skip this step entirely if `detect` returned zero `video` files. When the corpus has video or audio, see `references/transcribe.md` to transcribe them to text first, then treat the transcripts as doc files in Step 3.
150
+
151
+ ### Step 3 - Extract entities and relationships
152
+
153
+ **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.
154
+
155
+ This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens).
156
+
157
+ > **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 it needs nothing here: go straight to Part A and skip Part B. Semantic extraction (only for docs, papers, and images) uses Gemini **only if** `GEMINI_API_KEY`/`GOOGLE_API_KEY` is already set; otherwise the host agent itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key. If you catch yourself about to prompt for, wait on, or stop because of a missing API key, that is a misread of this skill — proceed without one.
158
+
159
+ **Before semantic extraction:** check whether `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user:
160
+ > Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`).
161
+
162
+ Print it once, then continue — do not wait for the user to supply a key. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="gemini")` for semantic extraction instead of dispatching subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it.
163
+
164
+ > **No other API keys are read.** When `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, semantic extraction falls to the host agent itself — the running session is the LLM. On a host that dispatches subagents (e.g. Claude Code), dispatch them as written in Part B. On a host that runs the CLI directly in a terminal and cannot dispatch subagents, do not stall: a code-only corpus has no semantic work, so write the empty semantic file (Part B "Fast path") and continue to Part C; for a corpus with docs/papers/images, either set a Gemini key or extract those inline yourself, but in no case prompt for `ANTHROPIC_API_KEY` — that prompt is a misread of this skill.
165
+
166
+ **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.**
167
+
168
+ Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
169
+
170
+ #### Part A - Structural extraction for code files
171
+
172
+ For any code files detected, run AST extraction in parallel with Part B subagents:
173
+
174
+ ```bash
175
+ $(cat graphify-out/.graphify_python) -c "
176
+ import sys, json
177
+ from graphify.extract import collect_files, extract
178
+ from pathlib import Path
179
+ import json
180
+
181
+ code_files = []
182
+ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
183
+ for f in detect.get('files', {}).get('code', []):
184
+ code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
185
+
186
+ if code_files:
187
+ result = extract(code_files, cache_root=Path('INPUT_PATH'))
188
+ Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
189
+ print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
190
+ else:
191
+ Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding=\"utf-8\")
192
+ print('No code files - skipping AST extraction')
193
+ "
194
+ ```
195
+
196
+ #### Part B - Semantic extraction (parallel subagents)
197
+
198
+ **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. **First write an empty semantic file** so Part C's merge has its input (it reads `.graphify_semantic.json` unconditionally; without this a code-only run hits `FileNotFoundError`):
199
+
200
+ ```bash
201
+ $(cat graphify-out/.graphify_python) -c "
202
+ import json
203
+ from pathlib import Path
204
+ Path('graphify-out/.graphify_semantic.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
205
+ "
206
+ ```
207
+
208
+ **MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
209
+
210
+ Before dispatching subagents, print a timing estimate:
211
+ - Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
212
+ - Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
213
+ - Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
214
+ - Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
215
+
216
+ **Step B0 - Check extraction cache first**
217
+
218
+ Before dispatching any subagents, check which files already have cached extraction results:
219
+
220
+ SPEC_PATH below is the **absolute** path of the `references/extraction-spec.md` that ships beside this SKILL.md — the same file Step B2 loads and hands to every subagent. It is the extraction prompt, so cache entries are attributed to it: when a graphify upgrade changes the prompt, entries produced by the old one are re-extracted instead of replayed, and unchanged prompts keep their entries (#1939). Substitute the real path in both Step B0 and Step B3 — pass the same one to each, and do not drop the argument.
221
+
222
+ ```bash
223
+ $(cat graphify-out/.graphify_python) -c "
224
+ import json
225
+ from graphify.cache import check_semantic_cache
226
+ from pathlib import Path
227
+
228
+ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
229
+ # Only content files go to semantic extraction. Code is already covered structurally
230
+ # by the AST pass (Part A); flattening every category here makes subagents re-read
231
+ # every source file (#1392). Video is transcribed to a document in Step 2.5 first.
232
+ all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
233
+
234
+ cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
235
+
236
+ # Always (re)write the cache file: write hits, else DELETE any leftover from a prior
237
+ # run so Part C never merges a stale .graphify_cached.json (#1392).
238
+ if cached_nodes or cached_edges or cached_hyperedges:
239
+ Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding=\"utf-8\")
240
+ else:
241
+ Path('graphify-out/.graphify_cached.json').unlink(missing_ok=True)
242
+ Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding=\"utf-8\")
243
+ print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
244
+ "
245
+ ```
246
+
247
+ Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
248
+
249
+ **Step B1 - Split into chunks**
250
+
251
+ 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.
252
+
253
+ **Step B2 - Dispatch ALL subagents in a single message**
254
+
255
+ > Uses the `Task` tool for parallel subagent dispatch.
256
+ > Call `Task` once per chunk — ALL in the same response so they run in parallel.
257
+
258
+ Pass the extraction prompt as the task description:
259
+
260
+ ```
261
+ Task(description="Your task is to perform the following. Follow the instructions below exactly.\n\n<agent-instructions>\n[extraction prompt, with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE substituted]\n</agent-instructions>\n\nExecute this now. Output ONLY the structured JSON response.")
262
+ ```
263
+
264
+ Each subagent writes its result to its own `graphify-out/.graphify_chunk_NN.json`. Collect results as each `Task` completes and parse each as JSON.
265
+
266
+ CHUNK_PATH must be an **absolute** path — derive it before dispatching:
267
+ ```bash
268
+ PROJECT_ROOT=$(pwd) # cwd — where Part C globs graphify-out/ (NOT .graphify_root/scan dir, #1392)
269
+ # Then for chunk N: CHUNK_PATH="${PROJECT_ROOT}/graphify-out/.graphify_chunk_0N.json"
270
+ ```
271
+
272
+ Subagent prompt template:
273
+
274
+ See `references/extraction-spec.md` for the exact subagent prompt (JSON schema, node-ID rules, confidence rubric, hyperedge, and vision rules). Load it only here, only when at least one chunk holds a doc, paper, or image; a pure-code corpus has skipped Part B and never reads it. Pass each subagent that prompt verbatim with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH substituted, and have it write the result to CHUNK_PATH.
275
+
276
+ **Step B3 - Collect, cache, and merge**
277
+
278
+ Wait for all subagents. For each result:
279
+ - Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
280
+ - If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
281
+ - If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
282
+ - If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
283
+
284
+ 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.
285
+
286
+ 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:
287
+ ```bash
288
+ $(cat graphify-out/.graphify_python) -c "
289
+ import json, glob
290
+ from pathlib import Path
291
+
292
+ chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
293
+ all_nodes, all_edges, all_hyperedges = [], [], []
294
+ total_in, total_out = 0, 0
295
+ for c in chunks:
296
+ d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
297
+ all_nodes += d.get('nodes', [])
298
+ all_edges += d.get('edges', [])
299
+ all_hyperedges += d.get('hyperedges', [])
300
+ total_in += d.get('input_tokens', 0)
301
+ total_out += d.get('output_tokens', 0)
302
+ Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
303
+ 'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
304
+ 'input_tokens': total_in, 'output_tokens': total_out,
305
+ }, indent=2, ensure_ascii=False), encoding=\"utf-8\")
306
+ print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
307
+ "
308
+ ```
309
+
310
+ Save new results to cache. Pass the same SPEC_PATH as Step B0 — it stamps each entry with the prompt that produced it, and a write under a different prompt than the read lands where the next run won't look (#1939):
311
+ ```bash
312
+ $(cat graphify-out/.graphify_python) -c "
313
+ import json
314
+ from graphify.cache import save_semantic_cache
315
+ from pathlib import Path
316
+
317
+ new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
318
+ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_text(encoding=\"utf-8\").splitlines() if line]
319
+ saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH')
320
+ print(f'Cached {saved} files')
321
+ "
322
+ ```
323
+
324
+ Merge cached + new results into `graphify-out/.graphify_semantic.json`:
325
+ ```bash
326
+ $(cat graphify-out/.graphify_python) -c "
327
+ import json
328
+ from pathlib import Path
329
+
330
+ cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
331
+ new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
332
+
333
+ all_nodes = cached['nodes'] + new.get('nodes', [])
334
+ all_edges = cached['edges'] + new.get('edges', [])
335
+ all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
336
+ seen = set()
337
+ deduped = []
338
+ for n in all_nodes:
339
+ if n['id'] not in seen:
340
+ seen.add(n['id'])
341
+ deduped.append(n)
342
+
343
+ merged = {
344
+ 'nodes': deduped,
345
+ 'edges': all_edges,
346
+ 'hyperedges': all_hyperedges,
347
+ 'input_tokens': new.get('input_tokens', 0),
348
+ 'output_tokens': new.get('output_tokens', 0),
349
+ }
350
+ Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\")
351
+ print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
352
+ "
353
+ ```
354
+ Clean up temp files: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json`
355
+
356
+ #### Part C - Merge AST + semantic into final extraction
357
+
358
+ ```bash
359
+ $(cat graphify-out/.graphify_python) -c "
360
+ import sys, json
361
+ from pathlib import Path
362
+
363
+ ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding=\"utf-8\"))
364
+ sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding=\"utf-8\"))
365
+
366
+ # Merge: AST nodes first, semantic nodes deduplicated by id
367
+ seen = {n['id'] for n in ast['nodes']}
368
+ merged_nodes = list(ast['nodes'])
369
+ for n in sem['nodes']:
370
+ if n['id'] not in seen:
371
+ merged_nodes.append(n)
372
+ seen.add(n['id'])
373
+
374
+ merged_edges = ast['edges'] + sem['edges']
375
+ merged_hyperedges = sem.get('hyperedges', [])
376
+ merged = {
377
+ 'nodes': merged_nodes,
378
+ 'edges': merged_edges,
379
+ 'hyperedges': merged_hyperedges,
380
+ 'input_tokens': sem.get('input_tokens', 0),
381
+ 'output_tokens': sem.get('output_tokens', 0),
382
+ }
383
+ Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\")
384
+ total = len(merged_nodes)
385
+ edges = len(merged_edges)
386
+ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
387
+ "
388
+ ```
389
+
390
+ ### Step 4 - Build graph, cluster, analyze, generate outputs
391
+
392
+ **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 the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
393
+
394
+ ```bash
395
+ mkdir -p graphify-out
396
+ $(cat graphify-out/.graphify_python) -c "
397
+ import sys, json
398
+ from graphify.build import build_from_json
399
+ from graphify.cluster import cluster, score_all
400
+ from graphify.analyze import god_nodes, surprising_connections, suggest_questions
401
+ from graphify.report import generate
402
+ from graphify.export import to_json
403
+ from pathlib import Path
404
+
405
+ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
406
+ detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
407
+
408
+ # root= mirrors the --update runbook (#1361): relativize source_file to the same
409
+ # base so the full build and incremental --update never drift apart on re-extract.
410
+ G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
411
+ # Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
412
+ # GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
413
+ if G.number_of_nodes() == 0:
414
+ print('ERROR: Graph is empty - extraction produced no nodes.')
415
+ print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
416
+ raise SystemExit(1)
417
+ communities = cluster(G)
418
+ cohesion = score_all(G, communities)
419
+ tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
420
+ gods = god_nodes(G)
421
+ surprises = surprising_connections(G, communities)
422
+ labels = {cid: 'Community ' + str(cid) for cid in communities}
423
+ # Placeholder questions - regenerated with real labels in Step 5
424
+ questions = suggest_questions(G, communities, labels)
425
+
426
+ # Export FIRST and honor the #479 shrink-guard: to_json returns False (writing
427
+ # nothing) when the new graph is smaller than the existing graph.json. Only write
428
+ # GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
429
+ # they never describe a graph that graph.json doesn't contain (#1392).
430
+ wrote = to_json(G, communities, 'graphify-out/graph.json')
431
+ if not wrote:
432
+ print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
433
+ print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
434
+ raise SystemExit(1)
435
+ report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
436
+ Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
437
+ analysis = {
438
+ 'communities': {str(k): v for k, v in communities.items()},
439
+ 'cohesion': {str(k): v for k, v in cohesion.items()},
440
+ 'gods': gods,
441
+ 'surprises': surprises,
442
+ 'questions': questions,
443
+ }
444
+ Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding=\"utf-8\")
445
+ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
446
+ "
447
+ ```
448
+
449
+ If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
450
+
451
+ Replace INPUT_PATH with the actual path.
452
+
453
+ ### Step 4.5 - Graph health check (read-only integrity gate)
454
+
455
+ A non-destructive diagnostic on the extraction, before labeling. It surfaces edge collapse, dangling/missing endpoints, and self-loops — the silent-corruption modes of incremental updates and AST/LLM id mismatches. Read-only; never aborts.
456
+
457
+ ```bash
458
+ $(cat graphify-out/.graphify_python) -c "
459
+ import json
460
+ from pathlib import Path
461
+ from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
462
+
463
+ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
464
+ summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
465
+ print(format_diagnostic_report(summary))
466
+ flags = [f'{summary[k]} {label}' for k, label in (
467
+ ('dangling_endpoint_edges', 'dangling-endpoint edges'),
468
+ ('missing_endpoint_edges', 'missing-endpoint edges'),
469
+ ('self_loop_edges', 'self-loop edges'),
470
+ ('directed_same_endpoint_collapsed_edges', 'collapsed (directed) edges'),
471
+ ('undirected_same_endpoint_collapsed_edges', 'collapsed (undirected) edges'),
472
+ ) if summary.get(k, 0)]
473
+ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/corrupt.' if flags else 'Graph health: OK (no dangling/missing/collapsed edges).')
474
+ "
475
+ ```
476
+
477
+ Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
478
+
479
+ ### Step 5 - Label communities
480
+
481
+ 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").
482
+
483
+ Then regenerate the report and save the labels for the visualizer:
484
+
485
+ ```bash
486
+ $(cat graphify-out/.graphify_python) -c "
487
+ import sys, json
488
+ from graphify.build import build_from_json
489
+ from graphify.cluster import score_all
490
+ from graphify.analyze import god_nodes, surprising_connections, suggest_questions
491
+ from graphify.report import generate
492
+ from graphify.export import to_json
493
+ from pathlib import Path
494
+
495
+ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
496
+ detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
497
+ analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
498
+
499
+ # root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
500
+ G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
501
+ communities = {int(k): v for k, v in analysis['communities'].items()}
502
+ cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
503
+ tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
504
+
505
+ # LABELS - replace these with the names you chose above
506
+ labels = LABELS_DICT
507
+
508
+ # Regenerate questions with real community labels (labels affect question phrasing)
509
+ questions = suggest_questions(G, communities, labels)
510
+
511
+ report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
512
+ Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
513
+ Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
514
+ # Re-export so graph.json nodes carry the curated community_name (#2490).
515
+ # Same extraction as Step 4, so the #479 shrink-guard passes on node count;
516
+ # if it still refuses, surface the guard message - do not force past it.
517
+ wrote = to_json(G, communities, 'graphify-out/graph.json', community_labels=labels)
518
+ if not wrote:
519
+ print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
520
+ print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
521
+ print('Report updated with community labels')
522
+ "
523
+ ```
524
+
525
+ Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
526
+ Replace INPUT_PATH with the actual path.
527
+
528
+ ### Step 6 - Generate Obsidian vault (opt-in) + HTML
529
+
530
+ **Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
531
+
532
+ If `--obsidian` was given:
533
+
534
+ - If `--obsidian-dir <path>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`.
535
+
536
+ ```bash
537
+ graphify export obsidian
538
+ # or with custom dir: graphify export obsidian --dir ~/vaults/my-project
539
+ ```
540
+
541
+ Generate the HTML graph (always, unless `--no-viz`):
542
+
543
+ ```bash
544
+ graphify export html # auto-aggregates to community view if graph > 5000 nodes
545
+ # or: graphify export html --no-viz
546
+ ```
547
+
548
+ ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags)
549
+
550
+ These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-push`, `--falkordb`/`--falkordb-push`, `--svg`, `--graphml`, `--mcp`) or, for the token-reduction benchmark, when `total_words` exceeds 5,000. A default run with no export flags skips all of them. See `references/exports.md` for each one. Run any `--wiki` export before Step 9 cleanup so `.graphify_labels.json` is still available.
551
+
552
+ ---
553
+
554
+ ### Step 9 - Save manifest, update cost tracker, clean up, and report
555
+
556
+ ```bash
557
+ $(cat graphify-out/.graphify_python) -c "
558
+ import json
559
+ from pathlib import Path
560
+ from datetime import datetime, timezone
561
+ from graphify.detect import save_manifest
562
+
563
+ # Save manifest for --update
564
+ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
565
+ extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
566
+ # In --update mode, 'all_files' carries the full corpus; 'files' is the changed
567
+ # subset. Full-rebuild mode populates only 'files', so the fallback handles that.
568
+ # root= relativizes the manifest keys to the scan root (same base as the build),
569
+ # so the on-disk manifest is portable across clones/machines and a later --update
570
+ # matches cached files instead of missing every one (#1417).
571
+ #
572
+ # Only stamp semantic files (docs/papers/images) that ACTUALLY produced output:
573
+ # a detected file whose chunk failed or was omitted must stay unstamped so the
574
+ # next --update re-queues it, otherwise it is marked done and its content is lost
575
+ # forever (#2015). This mirrors the library extract path exactly
576
+ # (cli._stamped_manifest_files + clear_semantic + scan_corpus); do not stamp the
577
+ # raw corpus. Code files are always stamped (AST is deterministic); only semantic
578
+ # types are gated on output.
579
+ from graphify.cli import _stamped_manifest_files
580
+ _corpus = detect.get('all_files') or detect['files']
581
+ _manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'))
582
+ # Files dispatched this run (the changed subset) but NOT stamped above still carry
583
+ # a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
584
+ # them instead of reading them as unchanged (#1948).
585
+ _sem_types = ('document', 'paper', 'image')
586
+ _dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl}
587
+ _stamped = {f for fl in _manifest_files.values() for f in fl}
588
+ _cleared = _dispatched - _stamped
589
+ # scan_corpus = the RAW full corpus (not the stamp-filtered subset) so in-root
590
+ # files newly excluded since last run are dropped rather than masquerading as
591
+ # deletions; untouched files' prior rows are still preserved (#1908).
592
+ _scan = {f for fl in _corpus.values() for f in fl}
593
+ save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
594
+
595
+ # Update cumulative cost tracker
596
+ input_tok = extract.get('input_tokens', 0)
597
+ output_tok = extract.get('output_tokens', 0)
598
+
599
+ cost_path = Path('graphify-out/cost.json')
600
+ if cost_path.exists():
601
+ cost = json.loads(cost_path.read_text(encoding=\"utf-8\"))
602
+ else:
603
+ cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
604
+
605
+ cost['runs'].append({
606
+ 'date': datetime.now(timezone.utc).isoformat(),
607
+ 'input_tokens': input_tok,
608
+ 'output_tokens': output_tok,
609
+ 'files': detect.get('total_files', 0),
610
+ })
611
+ cost['total_input_tokens'] += input_tok
612
+ cost['total_output_tokens'] += output_tok
613
+ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"utf-8\")
614
+
615
+ print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
616
+ print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
617
+ "
618
+ 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
619
+ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
620
+ rm -f graphify-out/.needs_update 2>/dev/null || true
621
+ ```
622
+
623
+ Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
624
+
625
+ Tell the user (omit the obsidian line unless --obsidian was given):
626
+ ```
627
+ Graph complete. Outputs in PATH_TO_DIR/graphify-out/
628
+
629
+ graph.html - interactive graph, open in browser
630
+ GRAPH_REPORT.md - audit report
631
+ graph.json - raw graph data
632
+ obsidian/ - Obsidian vault (only if --obsidian was given)
633
+ ```
634
+
635
+ If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
636
+
637
+ Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
638
+
639
+ Then paste these sections from GRAPH_REPORT.md directly into the chat:
640
+ - God Nodes
641
+ - Surprising Connections
642
+ - Suggested Questions
643
+
644
+ Do NOT paste the full report - just those three sections. Keep it concise.
645
+
646
+ 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:
647
+
648
+ > "The most interesting question this graph can answer: **[question]**. Want me to trace it?"
649
+
650
+ 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.
651
+
652
+ The graph is the map. Your job after the pipeline is to be the guide.
653
+
654
+ ---
655
+
656
+ ## Interpreter guard for subcommands
657
+
658
+ 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:
659
+
660
+ ```bash
661
+ if [ ! -f graphify-out/.graphify_python ]; then
662
+ GRAPHIFY_BIN=$(which graphify 2>/dev/null)
663
+ if [ -n "$GRAPHIFY_BIN" ]; then
664
+ PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
665
+ case "$PYTHON" in *[!a-zA-Z0-9/_.@-]*) PYTHON="python3" ;; esac
666
+ else
667
+ PYTHON="python3"
668
+ fi
669
+ mkdir -p graphify-out
670
+ "$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
671
+ fi
672
+ ```
673
+
674
+ ## For --update and --cluster-only
675
+
676
+ Both are non-default subcommands. `--update` re-extracts only new or changed files; `--cluster-only` reruns clustering on the existing graph. See `references/update.md` for both flows.
677
+
678
+ ---
679
+
680
+ ## For /graphify query
681
+
682
+ When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it:
683
+
684
+ ```bash
685
+ graphify query "<question>"
686
+ ```
687
+
688
+ Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
689
+
690
+ ---
691
+
692
+ ## For /graphify add and --watch
693
+
694
+ Neither is part of the default build. When the user runs `/graphify add <url>` to fetch a URL into the corpus, or passes `--watch` to auto-rebuild on file changes, see `references/add-watch.md`.
695
+
696
+ ---
697
+
698
+ ## For the commit hook and native AGENTS.md integration
699
+
700
+ When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's AGENTS.md, see `references/hooks.md`.
701
+
702
+ ---
703
+
704
+ ## Honesty Rules
705
+
706
+ - Never invent an edge. If unsure, use AMBIGUOUS.
707
+ - Never skip the corpus check warning.
708
+ - Always show token cost in the report.
709
+ - Never hide cohesion scores behind symbols - show the raw number.
710
+ - Never run HTML viz on a graph with more than 5,000 nodes without warning the user.