@xynogen/pix-skills 0.2.0 → 0.2.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xynogen/pix-skills",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Pi extension — agent skill loader (skill tool + skills bundle)",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -0,0 +1,504 @@
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
14
+ /graphify <path> # full pipeline on specific path
15
+ /graphify <path> --mode deep # thorough extraction, richer INFERRED edges
16
+ /graphify <path> --update # incremental - re-extract only new/changed files
17
+ /graphify <path> --cluster-only # rerun clustering on existing graph
18
+ /graphify <path> --no-viz # skip visualization, just report + JSON
19
+ /graphify query "<question>" # BFS traversal - broad context
20
+ /graphify query "<question>" --dfs # DFS - trace a specific path
21
+ /graphify path "AuthModule" "Database" # shortest path between two concepts
22
+ /graphify explain "SwinTransformer" # plain-language explanation of a node
23
+ ```
24
+
25
+ ## What graphify is for
26
+
27
+ 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.
28
+
29
+ ## What You Must Do When Invoked
30
+
31
+ 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.
32
+
33
+ **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.
34
+
35
+ If no path was given, use `.` (current directory). Do not ask the user for a path.
36
+
37
+ Follow these steps in order. Do not skip steps.
38
+
39
+ ### Step 1 - Ensure graphify is installed
40
+
41
+ ```bash
42
+ PYTHON=""
43
+ GRAPHIFY_BIN=$(which graphify 2>/dev/null)
44
+ if [ -z "$PYTHON" ] && command -v uv >/dev/null 2>&1; then
45
+ _UV_PY=$(uv tool run graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
46
+ if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
47
+ fi
48
+ if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then
49
+ _SHEBANG=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
50
+ case "$_SHEBANG" in
51
+ *[!a-zA-Z0-9/_.-]*) ;;
52
+ *) "$_SHEBANG" -c "import graphify" 2>/dev/null && PYTHON="$_SHEBANG" ;;
53
+ esac
54
+ fi
55
+ if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
56
+ if ! "$PYTHON" -c "import graphify" 2>/dev/null; then
57
+ if command -v uv >/dev/null 2>&1; then
58
+ uv tool install --upgrade graphifyy -q 2>&1 | tail -3
59
+ _UV_PY=$(uv tool run graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
60
+ if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
61
+ else
62
+ "$PYTHON" -m pip install graphifyy -q 2>/dev/null \
63
+ || "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
64
+ fi
65
+ fi
66
+ mkdir -p graphify-out
67
+ "$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
68
+ echo "$(cd . && pwd)" > graphify-out/.graphify_root
69
+ ```
70
+
71
+ If the import succeeds, print nothing and move straight to Step 2.
72
+
73
+ **In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
74
+
75
+ ### Step 2 - Detect files
76
+
77
+ ```bash
78
+ $(cat graphify-out/.graphify_python) -c "
79
+ import json
80
+ from graphify.detect import detect
81
+ from pathlib import Path
82
+ result = detect(Path('INPUT_PATH'))
83
+ print(json.dumps(result, ensure_ascii=False))
84
+ " > graphify-out/.graphify_detect.json
85
+ ```
86
+
87
+ Replace INPUT_PATH with the actual path. Do NOT cat or print the JSON — read it silently and present a clean summary:
88
+
89
+ ```
90
+ Corpus: X files · ~Y words
91
+ code: N files (.py .ts .go ...)
92
+ docs: N files (.md .txt ...)
93
+ papers: N files (.pdf ...)
94
+ images: N files
95
+ ```
96
+
97
+ Omit any category with 0 files.
98
+
99
+ Then act on it:
100
+ - If `total_files` is 0: stop with "No supported files found in [path]."
101
+ - If `skipped_sensitive` is non-empty: mention file count skipped, not file names.
102
+ - 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.
103
+ - Otherwise: proceed to Step 3.
104
+
105
+ ### Step 3 - Extract entities and relationships
106
+
107
+ This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM).
108
+
109
+ #### Part A - Structural extraction for code files
110
+
111
+ ```bash
112
+ $(cat graphify-out/.graphify_python) -c "
113
+ import sys, json
114
+ from graphify.extract import collect_files, extract
115
+ from pathlib import Path
116
+
117
+ code_files = []
118
+ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
119
+ for f in detect.get('files', {}).get('code', []):
120
+ code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
121
+
122
+ if code_files:
123
+ result = extract(code_files, cache_root=Path('.'))
124
+ Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding='utf-8')
125
+ print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
126
+ else:
127
+ Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding='utf-8')
128
+ print('No code files - skipping AST extraction')
129
+ "
130
+ ```
131
+
132
+ #### Part B - Semantic extraction (pi-native)
133
+
134
+ **Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely. AST handles code.
135
+
136
+ **Pi-native mode:** Pi reads files directly and extracts entities. No API key needed. Sequential processing, zero cost.
137
+
138
+ **Step B0 - Check extraction cache**
139
+
140
+ ```bash
141
+ $(cat graphify-out/.graphify_python) -c "
142
+ import json
143
+ from graphify.cache import check_semantic_cache
144
+ from pathlib import Path
145
+
146
+ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
147
+ all_files = [f for files in detect['files'].values() for f in files]
148
+
149
+ cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
150
+
151
+ if cached_nodes or cached_edges or cached_hyperedges:
152
+ 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')
153
+ Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding='utf-8')
154
+ print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
155
+ "
156
+ ```
157
+
158
+ Only extract from files in `graphify-out/.graphify_uncached.txt`. If all cached, skip to Part C.
159
+
160
+ **Step B1 - Split into batches**
161
+
162
+ ```bash
163
+ $(cat graphify-out/.graphify_python) -c "
164
+ from pathlib import Path
165
+ import json
166
+
167
+ uncached = Path('graphify-out/.graphify_uncached.txt').read_text(encoding='utf-8').strip().split('\n')
168
+ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
169
+
170
+ images = [f for f in uncached if any(f.lower().endswith(e) for e in ('.png','.jpg','.jpeg','.gif','.webp','.svg'))]
171
+ text_files = [f for f in uncached if f not in images]
172
+
173
+ BATCH_SIZE = 10
174
+ batches = []
175
+ for i in range(0, len(text_files), BATCH_SIZE):
176
+ batches.append({'type': 'text', 'files': text_files[i:i+BATCH_SIZE]})
177
+ for img in images:
178
+ batches.append({'type': 'image', 'files': [img]})
179
+
180
+ Path('graphify-out/.graphify_batches.json').write_text(json.dumps(batches, indent=2), encoding='utf-8')
181
+ print(f'Batches: {len(batches)} ({len(text_files)} text in {(len(text_files)+BATCH_SIZE-1)//BATCH_SIZE} batches, {len(images)} images)')
182
+ "
183
+ ```
184
+
185
+ **Step B2 - Process each batch sequentially**
186
+
187
+ For each batch, you (the pi agent) must:
188
+
189
+ 1. **Read all files** in the batch using the `read` tool
190
+ 2. **Extract entities** from the file content — you ARE the LLM
191
+ 3. **Write chunk JSON** to disk using the `write` tool
192
+
193
+ **Extraction rules** (follow these when extracting):
194
+
195
+ ```
196
+ Extract a knowledge graph fragment from the files.
197
+ Output ONLY valid JSON matching the schema — no explanation, no markdown fences.
198
+
199
+ Rules:
200
+ - EXTRACTED: relationship explicit in source (import, call, citation)
201
+ - INFERRED: reasonable inference (shared structure, implied dependency)
202
+ - AMBIGUOUS: uncertain — flag it, do not omit
203
+ - Doc/paper files: named concepts, entities, citations.
204
+ Store rationale as a `rationale` attribute on the relevant node.
205
+ file_type must be one of: code, document, paper, image, rationale, concept
206
+ - DEEP_MODE: aggressive INFERRED edges — indirect deps, shared assumptions
207
+ - Semantic similarity: if two concepts solve the same problem without a
208
+ structural link, add semantically_similar_to edge (INFERRED, 0.6-0.95)
209
+ - Hyperedges: if 3+ nodes share a concept not captured by pairwise edges,
210
+ add hyperedge. Max 3 per batch. Use sparingly.
211
+ - confidence_score REQUIRED on every edge:
212
+ EXTRACTED = 1.0 always
213
+ INFERRED: pick ONE of 0.95/0.85/0.75/0.65/0.55
214
+ AMBIGUOUS: 0.1-0.3
215
+
216
+ Node ID format: {parent_dir}_{filename_stem}_{entity}
217
+ All lowercase, only [a-z0-9_], no dots/slashes
218
+ src/auth/session.py + ValidateToken → auth_session_validatetoken
219
+ Top-level files: just filename stem
220
+
221
+ Output JSON:
222
+ {
223
+ "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}],
224
+ "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}],
225
+ "hyperedges": [{"id":"...", "label":"...", "nodes":["..."], "relation":"participate_in|implement|form", "confidence":"EXTRACTED|INFERRED", "confidence_score":0.75, "source_file":"relative/path"}],
226
+ "input_tokens": 0,
227
+ "output_tokens": 0
228
+ }
229
+ ```
230
+
231
+ **For each batch:**
232
+
233
+ 1. Read the files:
234
+ ```
235
+ read file1.md
236
+ read file2.md
237
+ ...
238
+ ```
239
+
240
+ 2. Extract entities from the content you just read. Follow the rules above.
241
+
242
+ 3. Write the chunk JSON to `graphify-out/.graphify_chunk_NN.json` (zero-padded, 2 digits).
243
+
244
+ 4. Print progress:
245
+ ```
246
+ Batch 1/N: extracted X nodes, Y edges from [file names]
247
+ ```
248
+
249
+ **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"`.
250
+
251
+ **Step B3 - Collect and merge**
252
+
253
+ ```bash
254
+ $(cat graphify-out/.graphify_python) -c "
255
+ import json, glob
256
+ from pathlib import Path
257
+
258
+ chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
259
+ if not chunks:
260
+ print('No chunk files found — extraction may have failed')
261
+ else:
262
+ all_nodes, all_edges, all_hyperedges = [], [], []
263
+ total_in, total_out = 0, 0
264
+ for c in chunks:
265
+ d = json.loads(Path(c).read_text(encoding='utf-8'))
266
+ all_nodes += d.get('nodes', [])
267
+ all_edges += d.get('edges', [])
268
+ all_hyperedges += d.get('hyperedges', [])
269
+ total_in += d.get('input_tokens', 0)
270
+ total_out += d.get('output_tokens', 0)
271
+ Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
272
+ 'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
273
+ 'input_tokens': total_in, 'output_tokens': total_out,
274
+ }, indent=2, ensure_ascii=False), encoding='utf-8')
275
+ print(f'Merged {len(chunks)} chunks: {len(all_nodes)} nodes, {len(all_edges)} edges')
276
+ "
277
+ ```
278
+
279
+ Save to cache and merge with cached results:
280
+
281
+ ```bash
282
+ $(cat graphify-out/.graphify_python) -c "
283
+ import json
284
+ from graphify.cache import save_semantic_cache
285
+ from pathlib import Path
286
+
287
+ 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':[]}
288
+ saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
289
+ print(f'Cached {saved} files')
290
+ "
291
+ ```
292
+
293
+ Merge cached + new:
294
+
295
+ ```bash
296
+ $(cat graphify-out/.graphify_python) -c "
297
+ import json
298
+ from pathlib import Path
299
+
300
+ 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':[]}
301
+ 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':[]}
302
+
303
+ all_nodes = cached['nodes'] + new.get('nodes', [])
304
+ all_edges = cached['edges'] + new.get('edges', [])
305
+ all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
306
+ seen = set()
307
+ deduped = []
308
+ for n in all_nodes:
309
+ if n['id'] not in seen:
310
+ seen.add(n['id'])
311
+ deduped.append(n)
312
+
313
+ Path('graphify-out/.graphify_semantic.json').write_text(json.dumps({
314
+ 'nodes': deduped, 'edges': all_edges, 'hyperedges': all_hyperedges,
315
+ 'input_tokens': new.get('input_tokens', 0), 'output_tokens': new.get('output_tokens', 0),
316
+ }, indent=2, ensure_ascii=False), encoding='utf-8')
317
+ print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges')
318
+ "
319
+ ```
320
+
321
+ 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`
322
+
323
+ #### Part C - Merge AST + semantic into final extraction
324
+
325
+ ```bash
326
+ $(cat graphify-out/.graphify_python) -c "
327
+ import sys, json
328
+ from pathlib import Path
329
+
330
+ ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding='utf-8'))
331
+ sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding='utf-8'))
332
+
333
+ seen = {n['id'] for n in ast['nodes']}
334
+ merged_nodes = list(ast['nodes'])
335
+ for n in sem['nodes']:
336
+ if n['id'] not in seen:
337
+ merged_nodes.append(n)
338
+ seen.add(n['id'])
339
+
340
+ merged_edges = ast['edges'] + sem['edges']
341
+ merged = {
342
+ 'nodes': merged_nodes,
343
+ 'edges': merged_edges,
344
+ 'hyperedges': sem.get('hyperedges', []),
345
+ 'input_tokens': sem.get('input_tokens', 0),
346
+ 'output_tokens': sem.get('output_tokens', 0),
347
+ }
348
+ Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding='utf-8')
349
+ print(f'Merged: {len(merged_nodes)} nodes, {len(merged_edges)} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
350
+ "
351
+ ```
352
+
353
+ ### Step 4 - Build graph, cluster, analyze, generate outputs
354
+
355
+ ```bash
356
+ mkdir -p graphify-out
357
+ $(cat graphify-out/.graphify_python) -c "
358
+ import sys, json
359
+ from graphify.build import build_from_json
360
+ from graphify.cluster import cluster, score_all
361
+ from graphify.analyze import god_nodes, surprising_connections, suggest_questions
362
+ from graphify.report import generate
363
+ from graphify.export import to_json
364
+ from pathlib import Path
365
+
366
+ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding='utf-8'))
367
+ detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
368
+
369
+ G = build_from_json(extraction)
370
+ communities = cluster(G)
371
+ cohesion = score_all(G, communities)
372
+ tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
373
+ gods = god_nodes(G)
374
+ surprises = surprising_connections(G, communities)
375
+ labels = {cid: 'Community ' + str(cid) for cid in communities}
376
+ questions = suggest_questions(G, communities, labels)
377
+
378
+ report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, '.', suggested_questions=questions)
379
+ Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding='utf-8')
380
+ to_json(G, communities, 'graphify-out/graph.json')
381
+
382
+ analysis = {
383
+ 'communities': {str(k): v for k, v in communities.items()},
384
+ 'cohesion': {str(k): v for k, v in cohesion.items()},
385
+ 'gods': gods, 'surprises': surprises, 'questions': questions,
386
+ }
387
+ Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding='utf-8')
388
+ if G.number_of_nodes() == 0:
389
+ print('ERROR: Graph is empty - extraction produced no nodes.')
390
+ raise SystemExit(1)
391
+ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
392
+ "
393
+ ```
394
+
395
+ If this step prints `ERROR: Graph is empty`, stop and tell the user.
396
+
397
+ ### Step 5 - Label communities
398
+
399
+ Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name.
400
+
401
+ Then regenerate the report:
402
+
403
+ ```bash
404
+ $(cat graphify-out/.graphify_python) -c "
405
+ import sys, json
406
+ from graphify.build import build_from_json
407
+ from graphify.cluster import score_all
408
+ from graphify.analyze import god_nodes, surprising_connections, suggest_questions
409
+ from graphify.report import generate
410
+ from pathlib import Path
411
+
412
+ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding='utf-8'))
413
+ detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
414
+ analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding='utf-8'))
415
+
416
+ G = build_from_json(extraction)
417
+ communities = {int(k): v for k, v in analysis['communities'].items()}
418
+ cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
419
+ tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
420
+
421
+ # LABELS - replace with actual dict
422
+ labels = LABELS_DICT
423
+
424
+ questions = suggest_questions(G, communities, labels)
425
+ report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, '.', suggested_questions=questions)
426
+ Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding='utf-8')
427
+ 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')
428
+ print('Report updated with community labels')
429
+ "
430
+ ```
431
+
432
+ Replace `LABELS_DICT` with the actual dict (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
433
+
434
+ ### Step 6 - Generate HTML
435
+
436
+ ```bash
437
+ graphify export html
438
+ ```
439
+
440
+ ### Step 9 - Save manifest, update cost tracker, clean up
441
+
442
+ ```bash
443
+ $(cat graphify-out/.graphify_python) -c "
444
+ import json
445
+ from pathlib import Path
446
+ from datetime import datetime, timezone
447
+ from graphify.detect import save_manifest
448
+
449
+ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
450
+ save_manifest(detect.get('all_files') or detect['files'])
451
+
452
+ extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding='utf-8'))
453
+ input_tok = extract.get('input_tokens', 0)
454
+ output_tok = extract.get('output_tokens', 0)
455
+
456
+ cost_path = Path('graphify-out/cost.json')
457
+ if cost_path.exists():
458
+ cost = json.loads(cost_path.read_text(encoding='utf-8'))
459
+ else:
460
+ cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
461
+
462
+ cost['runs'].append({
463
+ 'date': datetime.now(timezone.utc).isoformat(),
464
+ 'input_tokens': input_tok, 'output_tokens': output_tok,
465
+ 'files': detect.get('total_files', 0),
466
+ })
467
+ cost['total_input_tokens'] += input_tok
468
+ cost['total_output_tokens'] += output_tok
469
+ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding='utf-8')
470
+ print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
471
+ "
472
+ 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
473
+ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
474
+ rm -f graphify-out/.needs_update graphify-out/.graphify_batches.json 2>/dev/null || true
475
+ ```
476
+
477
+ Tell the user:
478
+ ```
479
+ Graph complete. Outputs in graphify-out/
480
+
481
+ graph.html - interactive graph, open in browser
482
+ GRAPH_REPORT.md - audit report
483
+ graph.json - raw graph data
484
+ ```
485
+
486
+ Then paste these sections from GRAPH_REPORT.md:
487
+ - God Nodes
488
+ - Surprising Connections
489
+ - Suggested Questions
490
+
491
+ ## For /graphify query
492
+
493
+ When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph:
494
+
495
+ ```bash
496
+ graphify query "<question>"
497
+ ```
498
+
499
+ ## Honesty Rules
500
+
501
+ - Never invent an edge. If unsure, use AMBIGUOUS.
502
+ - Never skip the corpus check warning.
503
+ - Always show token cost in the report.
504
+ - Never hide cohesion scores behind symbols - show the raw number.
@@ -0,0 +1,90 @@
1
+ import { describe, expect, it } from "bun:test";
2
+
3
+ import {
4
+ extractDescription,
5
+ extractName,
6
+ formatSkillSummary,
7
+ type ThemeLike,
8
+ } from "./index.ts";
9
+
10
+ // Stub theme tags fragments so assertions verify which color/bold applied
11
+ // without depending on real ANSI codes.
12
+ const tagTheme: ThemeLike = {
13
+ fg: (key, text) => `[${key}]${text}[/]`,
14
+ bold: (text) => `<b>${text}</b>`,
15
+ };
16
+
17
+ const FRONTMATTER = `---
18
+ name: commit
19
+ description: Split, write, and maintain commits.
20
+ ---
21
+ # Commit Directive
22
+ body...`;
23
+
24
+ describe("extractName", () => {
25
+ it("reads name from YAML frontmatter", () => {
26
+ expect(extractName(FRONTMATTER)).toBe("commit");
27
+ });
28
+
29
+ it("strips surrounding quotes", () => {
30
+ expect(extractName('---\nname: "debug"\n---\n')).toBe("debug");
31
+ });
32
+
33
+ it("returns null when no frontmatter", () => {
34
+ expect(extractName("# Just a heading")).toBeNull();
35
+ });
36
+
37
+ it("returns null when frontmatter lacks a name", () => {
38
+ expect(extractName("---\ndescription: x\n---\n")).toBeNull();
39
+ });
40
+ });
41
+
42
+ describe("extractDescription", () => {
43
+ it("reads description from frontmatter", () => {
44
+ expect(extractDescription(FRONTMATTER)).toBe(
45
+ "Split, write, and maintain commits.",
46
+ );
47
+ });
48
+
49
+ it("returns null when absent", () => {
50
+ expect(extractDescription("---\nname: x\n---\n")).toBeNull();
51
+ });
52
+
53
+ it("returns null when no frontmatter", () => {
54
+ expect(extractDescription("plain text")).toBeNull();
55
+ });
56
+ });
57
+
58
+ describe("formatSkillSummary", () => {
59
+ it("renders muted placeholder for empty input", () => {
60
+ expect(formatSkillSummary("", tagTheme)).toBe("[muted]No skills found.[/]");
61
+ });
62
+
63
+ it("renders single skill as bold-accent name + muted description", () => {
64
+ const out = formatSkillSummary(FRONTMATTER, tagTheme);
65
+ expect(out).toBe(
66
+ "[accent]<b>commit</b>[/] [muted]Split, write, and maintain commits.[/]",
67
+ );
68
+ });
69
+
70
+ it("falls back to (no description) when frontmatter has name only", () => {
71
+ const out = formatSkillSummary("---\nname: solo\n---\n", tagTheme);
72
+ expect(out).toBe("[accent]<b>solo</b>[/] [muted](no description)[/]");
73
+ });
74
+
75
+ it("renders a list of 'name: desc' lines, each colored", () => {
76
+ const list = "commit: write commits\ndebug: root cause analysis";
77
+ const out = formatSkillSummary(list, tagTheme);
78
+ const lines = out.split("\n");
79
+ expect(lines).toHaveLength(2);
80
+ expect(lines[0]).toBe("[accent]<b>commit</b>[/] [muted]write commits[/]");
81
+ expect(lines[1]).toBe(
82
+ "[accent]<b>debug</b>[/] [muted]root cause analysis[/]",
83
+ );
84
+ });
85
+
86
+ it("passes non 'name: desc' lines through as muted", () => {
87
+ const out = formatSkillSummary("Available skills (3):", tagTheme);
88
+ expect(out).toBe("[muted]Available skills (3):[/]");
89
+ });
90
+ });
package/src/index.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * pix-skills — skill loader extension
3
3
  *
4
- * Registers a `skill` tool that lets the agent load any bundled skill's
4
+ * Registers a `read_skills` tool that lets the agent load any bundled skill's
5
5
  * full SKILL.md (or flat .md) by name. This is the safe "agent prompts itself"
6
6
  * pattern: the agent calls the tool explicitly; no autonomous injection.
7
7
  *
@@ -81,13 +81,48 @@ function discoverSkills(): SkillEntry[] {
81
81
  }
82
82
 
83
83
  /** Extract the `description` from YAML frontmatter, or null. */
84
- function extractDescription(content: string): string | null {
84
+ export function extractDescription(content: string): string | null {
85
85
  const m = content.match(/^---\s*\n([\s\S]*?)\n---/);
86
86
  if (!m) return null;
87
87
  const dm = m[1]!.match(/^description\s*:\s*["']?(.+?)["']?\s*$/m);
88
88
  return dm ? dm[1]!.trim() : null;
89
89
  }
90
90
 
91
+ export function extractName(content: string): string | null {
92
+ const m = content.match(/^---\s*\n([\s\S]*?)\n---/);
93
+ if (!m) return null;
94
+ const nm = m[1]!.match(/^name\s*:\s*["']?(.+?)["']?\s*$/m);
95
+ return nm ? nm[1]!.trim() : null;
96
+ }
97
+
98
+ export type ThemeLike = {
99
+ bold: (text: string) => string;
100
+ fg: (key: "accent" | "muted" | "toolTitle", text: string) => string;
101
+ };
102
+
103
+ export function formatSkillSummary(text: string, theme: ThemeLike): string {
104
+ const trimmed = text.trim();
105
+ if (!trimmed) return theme.fg("muted", "No skills found.");
106
+
107
+ const name = extractName(trimmed);
108
+ const desc = extractDescription(trimmed);
109
+ if (name) {
110
+ return `${theme.fg("accent", theme.bold(name))} ${theme.fg("muted", desc ?? "(no description)")}`;
111
+ }
112
+
113
+ // List form: each skill is a single-token name followed by ": <desc>".
114
+ // Lines without that exact shape (headers, blanks) pass through muted so
115
+ // we don't mis-tint "Available skills (3):" as a skill entry.
116
+ const lines = trimmed.split("\n");
117
+ return lines
118
+ .map((line) => {
119
+ const match = line.match(/^(\S+):\s+(.+)$/);
120
+ if (!match) return theme.fg("muted", line);
121
+ return `${theme.fg("accent", theme.bold(match[1]!))} ${theme.fg("muted", match[2]!)}`;
122
+ })
123
+ .join("\n");
124
+ }
125
+
91
126
  // ─── Tool registration ────────────────────────────────────────────────────────
92
127
 
93
128
  const ParamsSchema = Type.Object({
@@ -108,16 +143,16 @@ const ParamsSchema = Type.Object({
108
143
 
109
144
  export default function registerSkillLoader(pi: ExtensionAPI): void {
110
145
  pi.registerTool({
111
- name: "skill",
112
- label: "Read Skill",
146
+ name: "read_skills",
147
+ label: "Read Skills",
113
148
  description:
114
149
  "Browse and load bundled skills. No args → list all skills with descriptions. name only → description for that skill. name + full=true → full instructions.",
115
150
  promptSnippet: "Browse and load bundled skill instructions",
116
151
  promptGuidelines: [
117
- "Call skill() with no arguments to list all available skills and their descriptions.",
118
- "Call skill(name=<skill>) to read the description of a specific skill before deciding to load it.",
119
- "Call skill(name=<skill>, full=true) to load the full procedure for a skill before executing it.",
120
- "Prefer skill() over the read tool for skills — it resolves the correct path regardless of install location.",
152
+ "Call read_skills() with no arguments to list all available skills and their descriptions.",
153
+ "Call read_skills(name=<skill>) to read the description of a specific skill before deciding to load it.",
154
+ "Call read_skills(name=<skill>, full=true) to load the full procedure for a skill before executing it.",
155
+ "Prefer read_skills() over the read tool for skills — it resolves the correct path regardless of install location.",
121
156
  ],
122
157
  executionMode: "sequential",
123
158
  parameters: ParamsSchema,
@@ -194,10 +229,18 @@ export default function registerSkillLoader(pi: ExtensionAPI): void {
194
229
  const { name, full } = args as { name?: string; full?: boolean };
195
230
  const label = name ? `${name}${full ? " (full)" : ""}` : "list";
196
231
  return new Text(
197
- `${theme.fg("toolTitle", theme.bold("skill"))} ${theme.fg("muted", label)}`,
232
+ `${theme.fg("toolTitle", theme.bold("read_skills"))} ${theme.fg("muted", label)}`,
198
233
  0,
199
234
  0,
200
235
  );
201
236
  },
237
+
238
+ renderResult(result, _options, theme) {
239
+ const text = result.content
240
+ ?.filter((content) => content.type === "text")
241
+ .map((content) => content.text || "")
242
+ .join("\n");
243
+ return new Text(formatSkillSummary(text ?? "", theme), 0, 0);
244
+ },
202
245
  });
203
246
  }