@xynogen/pix-skills 0.7.16 → 0.8.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.
package/README.md CHANGED
@@ -153,7 +153,6 @@ as `/skill:<name>` slash commands.
153
153
  | `environment` | Detect OS/distro/kernel/arch/user/CPU before running platform-specific commands |
154
154
  | `explain` | Technical deconstruction and logic tracing of existing code |
155
155
  | `finish` | Structured branch completion — verify, decide, clean up |
156
- | `graphify` | Codebase questions via a persistent knowledge graph |
157
156
  | `handoff` | Toggle session handoff — write or read+delete `HANDOFF.md` |
158
157
  | `human` | Audit and rewrite content to remove AI writing patterns ("AI-isms") |
159
158
  | `plan` | Write detailed, bite-sized implementation plans before coding |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xynogen/pix-skills",
3
- "version": "0.7.16",
3
+ "version": "0.8.0",
4
4
  "description": "Pi extension — agent skill loader (skill tool + skills bundle)",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -46,9 +46,8 @@
46
46
  "@earendil-works/pi-tui": "*"
47
47
  },
48
48
  "dependencies": {
49
- "@xynogen/pix-data": "^0.4.3",
50
49
  "@xynogen/pix-gate": "^0.2.6",
51
50
  "@xynogen/pix-pretty": "^1.11.2",
52
- "@xynogen/pix-runtime": "^0.7.0"
51
+ "@xynogen/pix-runtime": "^0.8.0"
53
52
  }
54
53
  }
package/src/index.test.ts CHANGED
@@ -21,6 +21,7 @@ import registerSkills, {
21
21
  interpolateSkill,
22
22
  readSkillResource,
23
23
  replaceSpan,
24
+ scanSiblingPackageSkills,
24
25
  type ThemeLike,
25
26
  tokenizeCommand,
26
27
  } from "./index.ts";
@@ -51,6 +52,42 @@ describe("bundled TOON skill", () => {
51
52
  });
52
53
  });
53
54
 
55
+ describe("scanSiblingPackageSkills", () => {
56
+ let scope: string;
57
+ beforeEach(async () => {
58
+ scope = await mkdtemp(join(tmpdir(), "pix-scope-"));
59
+ });
60
+ afterEach(async () => {
61
+ await rm(scope, { recursive: true, force: true });
62
+ });
63
+
64
+ it("discovers a sibling package's pi.skills entries", async () => {
65
+ const pkg = join(scope, "pix-graph");
66
+ await mkdir(join(pkg, "skills"), { recursive: true });
67
+ await writeFile(
68
+ join(pkg, "package.json"),
69
+ JSON.stringify({ name: "@xynogen/pix-graph", pi: { skills: ["./skills"] } }),
70
+ );
71
+ await writeFile(join(pkg, "skills", "graph.md"), "---\nname: graph\n---\nbody");
72
+
73
+ const found = scanSiblingPackageSkills(scope);
74
+ expect(found.map((s) => s.name)).toContain("graph");
75
+ });
76
+
77
+ it("skips pix-skills itself and packages without pi.skills", async () => {
78
+ await mkdir(join(scope, "pix-skills", "skills"), { recursive: true });
79
+ await writeFile(join(scope, "pix-skills", "skills", "self.md"), "---\nname: self\n---\n");
80
+ await mkdir(join(scope, "pix-footer"), { recursive: true });
81
+ await writeFile(join(scope, "pix-footer", "package.json"), JSON.stringify({ name: "x" }));
82
+
83
+ expect(scanSiblingPackageSkills(scope)).toEqual([]);
84
+ });
85
+
86
+ it("returns empty when the scope dir is absent", () => {
87
+ expect(scanSiblingPackageSkills(join(scope, "nope"))).toEqual([]);
88
+ });
89
+ });
90
+
54
91
  describe("extractName", () => {
55
92
  it("reads name from YAML frontmatter", () => {
56
93
  expect(extractName(FRONTMATTER)).toBe("commit");
package/src/index.ts CHANGED
@@ -99,17 +99,52 @@ function scanSkillsDir(root: string): SkillEntry[] {
99
99
  }
100
100
 
101
101
  /**
102
- * Discover all skills from bundled skills/ AND ~/.pi/agent/skills/.
103
- * Bundled skills take precedence on name collision.
102
+ * Scan sibling `@xynogen/*` packages that declare `pi.skills` in their manifest.
103
+ * pix-skills lives in the same scope dir (node_modules/@xynogen in an install,
104
+ * packages/ in dev), so other pix packages can own their own skills (e.g.
105
+ * pix-graph ships `graph`) and still be found by `read_skills`. Pi's host loads
106
+ * these via the manifest too; this keeps the agent-facing loader in sync.
107
+ */
108
+ export function scanSiblingPackageSkills(scope?: string): SkillEntry[] {
109
+ const scopeDir = scope ?? resolve(skillsRoot(), "..", ".."); // .../@xynogen
110
+ if (!existsSync(scopeDir)) return [];
111
+ const out: SkillEntry[] = [];
112
+ for (const entry of readdirSync(scopeDir, { withFileTypes: true })) {
113
+ if (!entry.isDirectory() || entry.name === "pix-skills") continue;
114
+ const pkgDir = join(scopeDir, entry.name);
115
+ let dirs: string[];
116
+ try {
117
+ const manifest = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8"));
118
+ const skills = manifest?.pi?.skills;
119
+ if (!Array.isArray(skills)) continue;
120
+ dirs = skills.filter((s: unknown): s is string => typeof s === "string");
121
+ } catch {
122
+ continue;
123
+ }
124
+ for (const rel of dirs) out.push(...scanSkillsDir(resolve(pkgDir, rel)));
125
+ }
126
+ return out;
127
+ }
128
+
129
+ /**
130
+ * Discover all skills from bundled skills/, sibling `@xynogen/*` packages that
131
+ * declare `pi.skills`, AND ~/.pi/agent/skills/.
132
+ * Earlier sources win on name collision (bundled > sibling packages > user).
104
133
  * Results sorted alphabetically by name.
105
134
  */
106
135
  function discoverSkills(): SkillEntry[] {
107
136
  const bundled = scanSkillsDir(skillsRoot());
137
+ const siblings = scanSiblingPackageSkills();
108
138
  const user = scanSkillsDir(userSkillsRoot());
109
139
 
110
- // Merge: bundled wins on collision
111
- const seen = new Set(bundled.map((s) => s.name));
112
- const merged = [...bundled, ...user.filter((s) => !seen.has(s.name))];
140
+ // Merge in precedence order; first occurrence of a name wins.
141
+ const seen = new Set<string>();
142
+ const merged: SkillEntry[] = [];
143
+ for (const skill of [...bundled, ...siblings, ...user]) {
144
+ if (seen.has(skill.name)) continue;
145
+ seen.add(skill.name);
146
+ merged.push(skill);
147
+ }
113
148
 
114
149
  return merged.sort((a, b) => a.name.localeCompare(b.name));
115
150
  }
@@ -1,533 +0,0 @@
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
- disable-model-invocation: true
5
- ---
6
-
7
- # /graphify
8
-
9
- 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.
10
-
11
- ## Usage
12
-
13
- ```
14
- /graphify # full pipeline on current directory
15
- /graphify <path> # full pipeline on specific path
16
- /graphify <path> --mode deep # thorough extraction, richer INFERRED edges
17
- /graphify <path> --update # incremental - re-extract only new/changed files
18
- /graphify <path> --cluster-only # rerun clustering on existing graph
19
- /graphify <path> --no-viz # skip visualization, just report + JSON
20
- /graphify query "<question>" # BFS traversal - broad context
21
- /graphify query "<question>" --dfs # DFS - trace a specific path
22
- /graphify path "AuthModule" "Database" # shortest path between two concepts
23
- /graphify explain "SwinTransformer" # plain-language explanation of a node
24
- ```
25
-
26
- ## What graphify is for
27
-
28
- 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.
29
-
30
- ## What You Must Do When Invoked
31
-
32
- 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.
33
-
34
- **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.
35
-
36
- If no path was given, use `.` (current directory). Do not ask the user for a path.
37
-
38
- Follow these steps in order. Do not skip steps.
39
-
40
- ### Step 1 - Ensure graphify is installed
41
-
42
- ```bash
43
- if ! python3 -c "import graphify" 2>/dev/null; then
44
- echo "graphify is not installed. See https://github.com/safishamsi/graphify for install instructions."
45
- echo "Quick install, then re-run this command:"
46
- echo " uv tool install graphifyy # recommended"
47
- echo " # or: pip install graphifyy"
48
- exit 1
49
- fi
50
- mkdir -p graphify-out
51
- python3 -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
52
- echo "$(cd . && pwd)" > graphify-out/.graphify_root
53
- ```
54
-
55
- If the import succeeds, print nothing and move straight to Step 2. If it prints the install message, stop and tell the user to install graphify (see <https://github.com/safishamsi/graphify>) before retrying — do not attempt to install it yourself.
56
-
57
- **In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
58
-
59
- ### Step 2 - Detect files
60
-
61
- ```bash
62
- $(cat graphify-out/.graphify_python) -c "
63
- import json
64
- from graphify.detect import detect
65
- from pathlib import Path
66
- result = detect(Path('INPUT_PATH'))
67
- print(json.dumps(result, ensure_ascii=False))
68
- " > graphify-out/.graphify_detect.json
69
- ```
70
-
71
- Replace INPUT_PATH with the actual path. Do NOT cat or print the JSON — read it silently and present a clean summary:
72
-
73
- ```
74
- Corpus: X files · ~Y words
75
- code: N files (.py .ts .go ...)
76
- docs: N files (.md .txt ...)
77
- papers: N files (.pdf ...)
78
- images: N files
79
- ```
80
-
81
- Omit any category with 0 files.
82
-
83
- Then act on it:
84
-
85
- - If `total_files` is 0: stop with "No supported files found in [path]."
86
- - If `skipped_sensitive` is non-empty: mention file count skipped, not file names.
87
- - If `total_words` > 2,000,000 OR `total_files` > 500: show the warning, compute top 5 subdirectories by file count, ask which to run on.
88
- - Otherwise: proceed to Step 3.
89
-
90
- ### Step 3 - Extract entities and relationships
91
-
92
- This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM).
93
-
94
- #### Part A - Structural extraction for code files
95
-
96
- ```bash
97
- $(cat graphify-out/.graphify_python) -c "
98
- import sys, json
99
- from graphify.extract import collect_files, extract
100
- from pathlib import Path
101
-
102
- code_files = []
103
- detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
104
- for f in detect.get('files', {}).get('code', []):
105
- code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
106
-
107
- if code_files:
108
- result = extract(code_files, cache_root=Path('.'))
109
- Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding='utf-8')
110
- print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
111
- else:
112
- Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding='utf-8')
113
- print('No code files - skipping AST extraction')
114
- "
115
- ```
116
-
117
- #### Part B - Semantic extraction (pi-native)
118
-
119
- **Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely. AST handles code.
120
-
121
- **Pi-native mode:** Pi reads files directly and extracts entities. No API key needed. Sequential processing, zero cost.
122
-
123
- **Step B0 - Check extraction cache**
124
-
125
- ```bash
126
- $(cat graphify-out/.graphify_python) -c "
127
- import json
128
- from graphify.cache import check_semantic_cache
129
- from pathlib import Path
130
-
131
- detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
132
- all_files = [f for files in detect['files'].values() for f in files]
133
-
134
- cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
135
-
136
- if cached_nodes or cached_edges or cached_hyperedges:
137
- 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')
138
- Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding='utf-8')
139
- print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
140
- "
141
- ```
142
-
143
- Only extract from files in `graphify-out/.graphify_uncached.txt`. If all cached, skip to Part C.
144
-
145
- **Step B1 - Split into batches**
146
-
147
- ```bash
148
- $(cat graphify-out/.graphify_python) -c "
149
- from pathlib import Path
150
- import json
151
-
152
- uncached = Path('graphify-out/.graphify_uncached.txt').read_text(encoding='utf-8').strip().split('\n')
153
- detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
154
-
155
- images = [f for f in uncached if any(f.lower().endswith(e) for e in ('.png','.jpg','.jpeg','.gif','.webp','.svg'))]
156
- text_files = [f for f in uncached if f not in images]
157
-
158
- BATCH_SIZE = 10
159
- batches = []
160
- for i in range(0, len(text_files), BATCH_SIZE):
161
- batches.append({'type': 'text', 'files': text_files[i:i+BATCH_SIZE]})
162
- for img in images:
163
- batches.append({'type': 'image', 'files': [img]})
164
-
165
- Path('graphify-out/.graphify_batches.json').write_text(json.dumps(batches, indent=2), encoding='utf-8')
166
- print(f'Batches: {len(batches)} ({len(text_files)} text in {(len(text_files)+BATCH_SIZE-1)//BATCH_SIZE} batches, {len(images)} images)')
167
- "
168
- ```
169
-
170
- **Step B2 - Process each batch sequentially**
171
-
172
- For each batch, you (the pi agent) must:
173
-
174
- 1. **Read all files** in the batch using the `read` tool
175
- 2. **Extract entities** from the file content — you ARE the LLM
176
- 3. **Write chunk JSON** to disk using the `write` tool
177
-
178
- **Extraction rules** (follow these when extracting):
179
-
180
- ```
181
- Extract a knowledge graph fragment from the files.
182
- Output ONLY valid JSON matching the schema — no explanation, no markdown fences.
183
-
184
- Rules:
185
- - EXTRACTED: relationship explicit in source (import, call, citation)
186
- - INFERRED: reasonable inference (shared structure, implied dependency)
187
- - AMBIGUOUS: uncertain — flag it, do not omit
188
- - Doc/paper files: named concepts, entities, citations.
189
- Store rationale as a `rationale` attribute on the relevant node.
190
- file_type must be one of: code, document, paper, image, rationale, concept
191
- - DEEP_MODE: aggressive INFERRED edges — indirect deps, shared assumptions
192
- - Semantic similarity: if two concepts solve the same problem without a
193
- structural link, add semantically_similar_to edge (INFERRED, 0.6-0.95)
194
- - Hyperedges: if 3+ nodes share a concept not captured by pairwise edges,
195
- add hyperedge. Max 3 per batch. Use sparingly.
196
- - confidence_score REQUIRED on every edge:
197
- EXTRACTED = 1.0 always
198
- INFERRED: pick ONE of 0.95/0.85/0.75/0.65/0.55
199
- AMBIGUOUS: 0.1-0.3
200
-
201
- Node ID format: {parent_dir}_{filename_stem}_{entity}
202
- All lowercase, only [a-z0-9_], no dots/slashes
203
- src/auth/session.py + ValidateToken → auth_session_validatetoken
204
- Top-level files: just filename stem
205
-
206
- Output JSON:
207
- {
208
- "nodes": [{"id":"...", "label":"...", "file_type":"document|paper|image|rationale|concept", "source_file":"relative/path", "source_location":null, "source_url":null, "captured_at":null, "author":null, "contributor":null}],
209
- "edges": [{"source":"...", "target":"...", "relation":"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}],
210
- "hyperedges": [{"id":"...", "label":"...", "nodes":["..."], "relation":"participate_in|implement|form", "confidence":"EXTRACTED|INFERRED", "confidence_score":0.75, "source_file":"relative/path"}],
211
- "input_tokens": 0,
212
- "output_tokens": 0
213
- }
214
- ```
215
-
216
- **For each batch:**
217
-
218
- 1. Read the files:
219
-
220
- ```
221
- read file1.md
222
- read file2.md
223
- ...
224
- ```
225
-
226
- 2. Extract entities from the content you just read. Follow the rules above.
227
-
228
- 3. Write the chunk JSON to `graphify-out/.graphify_chunk_NN.json` (zero-padded, 2 digits).
229
-
230
- 4. Print progress:
231
-
232
- ```
233
- Batch 1/N: extracted X nodes, Y edges from [file names]
234
- ```
235
-
236
- **Image batches:** For images, use the `read` tool which supports vision. Understand what the image IS, not just OCR. Extract image-specific nodes with `file_type: "image"`.
237
-
238
- **Step B3 - Collect and merge**
239
-
240
- ```bash
241
- $(cat graphify-out/.graphify_python) -c "
242
- import json, glob
243
- from pathlib import Path
244
-
245
- chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
246
- if not chunks:
247
- print('No chunk files found — extraction may have failed')
248
- else:
249
- all_nodes, all_edges, all_hyperedges = [], [], []
250
- total_in, total_out = 0, 0
251
- for c in chunks:
252
- d = json.loads(Path(c).read_text(encoding='utf-8'))
253
- all_nodes += d.get('nodes', [])
254
- all_edges += d.get('edges', [])
255
- all_hyperedges += d.get('hyperedges', [])
256
- total_in += d.get('input_tokens', 0)
257
- total_out += d.get('output_tokens', 0)
258
- Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
259
- 'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
260
- 'input_tokens': total_in, 'output_tokens': total_out,
261
- }, indent=2, ensure_ascii=False), encoding='utf-8')
262
- print(f'Merged {len(chunks)} chunks: {len(all_nodes)} nodes, {len(all_edges)} edges')
263
- "
264
- ```
265
-
266
- Save to cache and merge with cached results:
267
-
268
- ```bash
269
- $(cat graphify-out/.graphify_python) -c "
270
- import json
271
- from graphify.cache import save_semantic_cache
272
- from pathlib import Path
273
-
274
- 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':[]}
275
- saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
276
- print(f'Cached {saved} files')
277
- "
278
- ```
279
-
280
- Merge cached + new:
281
-
282
- ```bash
283
- $(cat graphify-out/.graphify_python) -c "
284
- import json
285
- from pathlib import Path
286
-
287
- 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':[]}
288
- 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':[]}
289
-
290
- all_nodes = cached['nodes'] + new.get('nodes', [])
291
- all_edges = cached['edges'] + new.get('edges', [])
292
- all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
293
- seen = set()
294
- deduped = []
295
- for n in all_nodes:
296
- if n['id'] not in seen:
297
- seen.add(n['id'])
298
- deduped.append(n)
299
-
300
- Path('graphify-out/.graphify_semantic.json').write_text(json.dumps({
301
- 'nodes': deduped, 'edges': all_edges, 'hyperedges': all_hyperedges,
302
- 'input_tokens': new.get('input_tokens', 0), 'output_tokens': new.get('output_tokens', 0),
303
- }, indent=2, ensure_ascii=False), encoding='utf-8')
304
- print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges')
305
- "
306
- ```
307
-
308
- Clean up: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json graphify-out/.graphify_chunk_*.json graphify-out/.graphify_batches.json`
309
-
310
- #### Part C - Merge AST + semantic into final extraction
311
-
312
- ```bash
313
- $(cat graphify-out/.graphify_python) -c "
314
- import sys, json
315
- from pathlib import Path
316
-
317
- ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding='utf-8'))
318
- sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding='utf-8'))
319
-
320
- seen = {n['id'] for n in ast['nodes']}
321
- merged_nodes = list(ast['nodes'])
322
- for n in sem['nodes']:
323
- if n['id'] not in seen:
324
- merged_nodes.append(n)
325
- seen.add(n['id'])
326
-
327
- merged_edges = ast['edges'] + sem['edges']
328
- merged = {
329
- 'nodes': merged_nodes,
330
- 'edges': merged_edges,
331
- 'hyperedges': sem.get('hyperedges', []),
332
- 'input_tokens': sem.get('input_tokens', 0),
333
- 'output_tokens': sem.get('output_tokens', 0),
334
- }
335
- Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding='utf-8')
336
- print(f'Merged: {len(merged_nodes)} nodes, {len(merged_edges)} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
337
- "
338
- ```
339
-
340
- ### Step 4 - Build graph, cluster, analyze, generate outputs
341
-
342
- ```bash
343
- mkdir -p graphify-out
344
- $(cat graphify-out/.graphify_python) -c "
345
- import sys, json
346
- from graphify.build import build_from_json
347
- from graphify.cluster import cluster, score_all
348
- from graphify.analyze import god_nodes, surprising_connections, suggest_questions
349
- from graphify.report import generate
350
- from graphify.export import to_json
351
- from pathlib import Path
352
-
353
- extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding='utf-8'))
354
- detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
355
-
356
- G = build_from_json(extraction)
357
- communities = cluster(G)
358
- cohesion = score_all(G, communities)
359
- tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
360
- gods = god_nodes(G)
361
- surprises = surprising_connections(G, communities)
362
- labels = {cid: 'Community ' + str(cid) for cid in communities}
363
- questions = suggest_questions(G, communities, labels)
364
-
365
- report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, '.', suggested_questions=questions)
366
- Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding='utf-8')
367
- to_json(G, communities, 'graphify-out/graph.json')
368
-
369
- analysis = {
370
- 'communities': {str(k): v for k, v in communities.items()},
371
- 'cohesion': {str(k): v for k, v in cohesion.items()},
372
- 'gods': gods, 'surprises': surprises, 'questions': questions,
373
- }
374
- Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding='utf-8')
375
- if G.number_of_nodes() == 0:
376
- print('ERROR: Graph is empty - extraction produced no nodes.')
377
- raise SystemExit(1)
378
- print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
379
- "
380
- ```
381
-
382
- If this step prints `ERROR: Graph is empty`, stop and tell the user.
383
-
384
- ### Step 5 - Label communities
385
-
386
- Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name.
387
-
388
- Then regenerate the report:
389
-
390
- ```bash
391
- $(cat graphify-out/.graphify_python) -c "
392
- import sys, json
393
- from graphify.build import build_from_json
394
- from graphify.cluster import score_all
395
- from graphify.analyze import god_nodes, surprising_connections, suggest_questions
396
- from graphify.report import generate
397
- from pathlib import Path
398
-
399
- extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding='utf-8'))
400
- detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
401
- analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding='utf-8'))
402
-
403
- G = build_from_json(extraction)
404
- communities = {int(k): v for k, v in analysis['communities'].items()}
405
- cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
406
- tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
407
-
408
- # LABELS - replace with actual dict
409
- labels = LABELS_DICT
410
-
411
- questions = suggest_questions(G, communities, labels)
412
- report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, '.', suggested_questions=questions)
413
- Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding='utf-8')
414
- 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')
415
- print('Report updated with community labels')
416
- "
417
- ```
418
-
419
- Replace `LABELS_DICT` with the actual dict (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
420
-
421
- ### Step 6 - Generate HTML
422
-
423
- ```bash
424
- graphify export html
425
- ```
426
-
427
- ### Step 7 - Patch HTML: add hyperedge hull toggle
428
-
429
- The generated HTML renders hyperedge hulls as filled convex polygons. When nodes are spread far apart by the force-directed layout, these become large blade-shaped artifacts. Patch the file to add a checkbox that toggles hull visibility (off by default).
430
-
431
- **Find this block** in `graphify-out/graph.html`:
432
-
433
- ```html
434
- <div id="legend-controls">
435
- <label><input type="checkbox" id="select-all-cb" checked onchange="toggleAllCommunities(!this.checked)">Select All</label>
436
- </div>
437
- ```
438
-
439
- **Replace with:**
440
-
441
- ```html
442
- <div id="legend-controls">
443
- <label><input type="checkbox" id="select-all-cb" checked onchange="toggleAllCommunities(!this.checked)">Select All</label>
444
- <label><input type="checkbox" id="hulls-cb" onchange="setHullsVisible(this.checked)">Hyperedge hulls</label>
445
- </div>
446
- ```
447
-
448
- **Then find** the `afterDrawing` handler (near bottom of `<script>`):
449
-
450
- ```js
451
- network.on('afterDrawing', function(ctx) {
452
- hyperedges.forEach(h => {
453
- ```
454
-
455
- **Replace with:**
456
-
457
- ```js
458
- let _hullsVisible = false;
459
- function setHullsVisible(v) { _hullsVisible = v; network.redraw(); }
460
- network.on('afterDrawing', function(ctx) {
461
- if (!_hullsVisible) return;
462
- hyperedges.forEach(h => {
463
- ```
464
-
465
- Do this with two `edit` calls (exact string replacement). The checkbox appears in the legend controls bar; hulls are hidden by default and render on demand.
466
-
467
- ### Step 9 - Save manifest, update cost tracker, clean up
468
-
469
- ```bash
470
- $(cat graphify-out/.graphify_python) -c "
471
- import json
472
- from pathlib import Path
473
- from datetime import datetime, timezone
474
- from graphify.detect import save_manifest
475
-
476
- detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
477
- save_manifest(detect.get('all_files') or detect['files'])
478
-
479
- extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding='utf-8'))
480
- input_tok = extract.get('input_tokens', 0)
481
- output_tok = extract.get('output_tokens', 0)
482
-
483
- cost_path = Path('graphify-out/cost.json')
484
- if cost_path.exists():
485
- cost = json.loads(cost_path.read_text(encoding='utf-8'))
486
- else:
487
- cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
488
-
489
- cost['runs'].append({
490
- 'date': datetime.now(timezone.utc).isoformat(),
491
- 'input_tokens': input_tok, 'output_tokens': output_tok,
492
- 'files': detect.get('total_files', 0),
493
- })
494
- cost['total_input_tokens'] += input_tok
495
- cost['total_output_tokens'] += output_tok
496
- cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding='utf-8')
497
- print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
498
- "
499
- 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
500
- find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
501
- rm -f graphify-out/.needs_update graphify-out/.graphify_batches.json 2>/dev/null || true
502
- ```
503
-
504
- Tell the user:
505
-
506
- ```
507
- Graph complete. Outputs in graphify-out/
508
-
509
- graph.html - interactive graph, open in browser
510
- GRAPH_REPORT.md - audit report
511
- graph.json - raw graph data
512
- ```
513
-
514
- Then paste these sections from GRAPH_REPORT.md:
515
-
516
- - God Nodes
517
- - Surprising Connections
518
- - Suggested Questions
519
-
520
- ## For /graphify query
521
-
522
- When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph:
523
-
524
- ```bash
525
- graphify query "<question>"
526
- ```
527
-
528
- ## Honesty Rules
529
-
530
- - Never invent an edge. If unsure, use AMBIGUOUS.
531
- - Never skip the corpus check warning.
532
- - Always show token cost in the report.
533
- - Never hide cohesion scores behind symbols - show the raw number.