@xynogen/pix-skills 0.2.1 → 0.2.3

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.1",
3
+ "version": "0.2.3",
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,487 @@
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
+ if ! python3 -c "import graphify" 2>/dev/null; then
43
+ echo "graphify is not installed. See https://github.com/safishamsi/graphify for install instructions."
44
+ echo "Quick install, then re-run this command:"
45
+ echo " uv tool install graphifyy # recommended"
46
+ echo " # or: pip install graphifyy"
47
+ exit 1
48
+ fi
49
+ mkdir -p graphify-out
50
+ python3 -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
51
+ echo "$(cd . && pwd)" > graphify-out/.graphify_root
52
+ ```
53
+
54
+ 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.
55
+
56
+ **In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
57
+
58
+ ### Step 2 - Detect files
59
+
60
+ ```bash
61
+ $(cat graphify-out/.graphify_python) -c "
62
+ import json
63
+ from graphify.detect import detect
64
+ from pathlib import Path
65
+ result = detect(Path('INPUT_PATH'))
66
+ print(json.dumps(result, ensure_ascii=False))
67
+ " > graphify-out/.graphify_detect.json
68
+ ```
69
+
70
+ Replace INPUT_PATH with the actual path. Do NOT cat or print the JSON — read it silently and present a clean summary:
71
+
72
+ ```
73
+ Corpus: X files · ~Y words
74
+ code: N files (.py .ts .go ...)
75
+ docs: N files (.md .txt ...)
76
+ papers: N files (.pdf ...)
77
+ images: N files
78
+ ```
79
+
80
+ Omit any category with 0 files.
81
+
82
+ Then act on it:
83
+ - If `total_files` is 0: stop with "No supported files found in [path]."
84
+ - If `skipped_sensitive` is non-empty: mention file count skipped, not file names.
85
+ - 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.
86
+ - Otherwise: proceed to Step 3.
87
+
88
+ ### Step 3 - Extract entities and relationships
89
+
90
+ This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM).
91
+
92
+ #### Part A - Structural extraction for code files
93
+
94
+ ```bash
95
+ $(cat graphify-out/.graphify_python) -c "
96
+ import sys, json
97
+ from graphify.extract import collect_files, extract
98
+ from pathlib import Path
99
+
100
+ code_files = []
101
+ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
102
+ for f in detect.get('files', {}).get('code', []):
103
+ code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
104
+
105
+ if code_files:
106
+ result = extract(code_files, cache_root=Path('.'))
107
+ Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding='utf-8')
108
+ print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
109
+ else:
110
+ Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding='utf-8')
111
+ print('No code files - skipping AST extraction')
112
+ "
113
+ ```
114
+
115
+ #### Part B - Semantic extraction (pi-native)
116
+
117
+ **Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely. AST handles code.
118
+
119
+ **Pi-native mode:** Pi reads files directly and extracts entities. No API key needed. Sequential processing, zero cost.
120
+
121
+ **Step B0 - Check extraction cache**
122
+
123
+ ```bash
124
+ $(cat graphify-out/.graphify_python) -c "
125
+ import json
126
+ from graphify.cache import check_semantic_cache
127
+ from pathlib import Path
128
+
129
+ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
130
+ all_files = [f for files in detect['files'].values() for f in files]
131
+
132
+ cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
133
+
134
+ if cached_nodes or cached_edges or cached_hyperedges:
135
+ 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')
136
+ Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding='utf-8')
137
+ print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
138
+ "
139
+ ```
140
+
141
+ Only extract from files in `graphify-out/.graphify_uncached.txt`. If all cached, skip to Part C.
142
+
143
+ **Step B1 - Split into batches**
144
+
145
+ ```bash
146
+ $(cat graphify-out/.graphify_python) -c "
147
+ from pathlib import Path
148
+ import json
149
+
150
+ uncached = Path('graphify-out/.graphify_uncached.txt').read_text(encoding='utf-8').strip().split('\n')
151
+ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
152
+
153
+ images = [f for f in uncached if any(f.lower().endswith(e) for e in ('.png','.jpg','.jpeg','.gif','.webp','.svg'))]
154
+ text_files = [f for f in uncached if f not in images]
155
+
156
+ BATCH_SIZE = 10
157
+ batches = []
158
+ for i in range(0, len(text_files), BATCH_SIZE):
159
+ batches.append({'type': 'text', 'files': text_files[i:i+BATCH_SIZE]})
160
+ for img in images:
161
+ batches.append({'type': 'image', 'files': [img]})
162
+
163
+ Path('graphify-out/.graphify_batches.json').write_text(json.dumps(batches, indent=2), encoding='utf-8')
164
+ print(f'Batches: {len(batches)} ({len(text_files)} text in {(len(text_files)+BATCH_SIZE-1)//BATCH_SIZE} batches, {len(images)} images)')
165
+ "
166
+ ```
167
+
168
+ **Step B2 - Process each batch sequentially**
169
+
170
+ For each batch, you (the pi agent) must:
171
+
172
+ 1. **Read all files** in the batch using the `read` tool
173
+ 2. **Extract entities** from the file content — you ARE the LLM
174
+ 3. **Write chunk JSON** to disk using the `write` tool
175
+
176
+ **Extraction rules** (follow these when extracting):
177
+
178
+ ```
179
+ Extract a knowledge graph fragment from the files.
180
+ Output ONLY valid JSON matching the schema — no explanation, no markdown fences.
181
+
182
+ Rules:
183
+ - EXTRACTED: relationship explicit in source (import, call, citation)
184
+ - INFERRED: reasonable inference (shared structure, implied dependency)
185
+ - AMBIGUOUS: uncertain — flag it, do not omit
186
+ - Doc/paper files: named concepts, entities, citations.
187
+ Store rationale as a `rationale` attribute on the relevant node.
188
+ file_type must be one of: code, document, paper, image, rationale, concept
189
+ - DEEP_MODE: aggressive INFERRED edges — indirect deps, shared assumptions
190
+ - Semantic similarity: if two concepts solve the same problem without a
191
+ structural link, add semantically_similar_to edge (INFERRED, 0.6-0.95)
192
+ - Hyperedges: if 3+ nodes share a concept not captured by pairwise edges,
193
+ add hyperedge. Max 3 per batch. Use sparingly.
194
+ - confidence_score REQUIRED on every edge:
195
+ EXTRACTED = 1.0 always
196
+ INFERRED: pick ONE of 0.95/0.85/0.75/0.65/0.55
197
+ AMBIGUOUS: 0.1-0.3
198
+
199
+ Node ID format: {parent_dir}_{filename_stem}_{entity}
200
+ All lowercase, only [a-z0-9_], no dots/slashes
201
+ src/auth/session.py + ValidateToken → auth_session_validatetoken
202
+ Top-level files: just filename stem
203
+
204
+ Output JSON:
205
+ {
206
+ "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}],
207
+ "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}],
208
+ "hyperedges": [{"id":"...", "label":"...", "nodes":["..."], "relation":"participate_in|implement|form", "confidence":"EXTRACTED|INFERRED", "confidence_score":0.75, "source_file":"relative/path"}],
209
+ "input_tokens": 0,
210
+ "output_tokens": 0
211
+ }
212
+ ```
213
+
214
+ **For each batch:**
215
+
216
+ 1. Read the files:
217
+ ```
218
+ read file1.md
219
+ read file2.md
220
+ ...
221
+ ```
222
+
223
+ 2. Extract entities from the content you just read. Follow the rules above.
224
+
225
+ 3. Write the chunk JSON to `graphify-out/.graphify_chunk_NN.json` (zero-padded, 2 digits).
226
+
227
+ 4. Print progress:
228
+ ```
229
+ Batch 1/N: extracted X nodes, Y edges from [file names]
230
+ ```
231
+
232
+ **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"`.
233
+
234
+ **Step B3 - Collect and merge**
235
+
236
+ ```bash
237
+ $(cat graphify-out/.graphify_python) -c "
238
+ import json, glob
239
+ from pathlib import Path
240
+
241
+ chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
242
+ if not chunks:
243
+ print('No chunk files found — extraction may have failed')
244
+ else:
245
+ all_nodes, all_edges, all_hyperedges = [], [], []
246
+ total_in, total_out = 0, 0
247
+ for c in chunks:
248
+ d = json.loads(Path(c).read_text(encoding='utf-8'))
249
+ all_nodes += d.get('nodes', [])
250
+ all_edges += d.get('edges', [])
251
+ all_hyperedges += d.get('hyperedges', [])
252
+ total_in += d.get('input_tokens', 0)
253
+ total_out += d.get('output_tokens', 0)
254
+ Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
255
+ 'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
256
+ 'input_tokens': total_in, 'output_tokens': total_out,
257
+ }, indent=2, ensure_ascii=False), encoding='utf-8')
258
+ print(f'Merged {len(chunks)} chunks: {len(all_nodes)} nodes, {len(all_edges)} edges')
259
+ "
260
+ ```
261
+
262
+ Save to cache and merge with cached results:
263
+
264
+ ```bash
265
+ $(cat graphify-out/.graphify_python) -c "
266
+ import json
267
+ from graphify.cache import save_semantic_cache
268
+ from pathlib import Path
269
+
270
+ 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':[]}
271
+ saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
272
+ print(f'Cached {saved} files')
273
+ "
274
+ ```
275
+
276
+ Merge cached + new:
277
+
278
+ ```bash
279
+ $(cat graphify-out/.graphify_python) -c "
280
+ import json
281
+ from pathlib import Path
282
+
283
+ 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':[]}
284
+ 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':[]}
285
+
286
+ all_nodes = cached['nodes'] + new.get('nodes', [])
287
+ all_edges = cached['edges'] + new.get('edges', [])
288
+ all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
289
+ seen = set()
290
+ deduped = []
291
+ for n in all_nodes:
292
+ if n['id'] not in seen:
293
+ seen.add(n['id'])
294
+ deduped.append(n)
295
+
296
+ Path('graphify-out/.graphify_semantic.json').write_text(json.dumps({
297
+ 'nodes': deduped, 'edges': all_edges, 'hyperedges': all_hyperedges,
298
+ 'input_tokens': new.get('input_tokens', 0), 'output_tokens': new.get('output_tokens', 0),
299
+ }, indent=2, ensure_ascii=False), encoding='utf-8')
300
+ print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges')
301
+ "
302
+ ```
303
+
304
+ 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`
305
+
306
+ #### Part C - Merge AST + semantic into final extraction
307
+
308
+ ```bash
309
+ $(cat graphify-out/.graphify_python) -c "
310
+ import sys, json
311
+ from pathlib import Path
312
+
313
+ ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding='utf-8'))
314
+ sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding='utf-8'))
315
+
316
+ seen = {n['id'] for n in ast['nodes']}
317
+ merged_nodes = list(ast['nodes'])
318
+ for n in sem['nodes']:
319
+ if n['id'] not in seen:
320
+ merged_nodes.append(n)
321
+ seen.add(n['id'])
322
+
323
+ merged_edges = ast['edges'] + sem['edges']
324
+ merged = {
325
+ 'nodes': merged_nodes,
326
+ 'edges': merged_edges,
327
+ 'hyperedges': sem.get('hyperedges', []),
328
+ 'input_tokens': sem.get('input_tokens', 0),
329
+ 'output_tokens': sem.get('output_tokens', 0),
330
+ }
331
+ Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding='utf-8')
332
+ print(f'Merged: {len(merged_nodes)} nodes, {len(merged_edges)} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
333
+ "
334
+ ```
335
+
336
+ ### Step 4 - Build graph, cluster, analyze, generate outputs
337
+
338
+ ```bash
339
+ mkdir -p graphify-out
340
+ $(cat graphify-out/.graphify_python) -c "
341
+ import sys, json
342
+ from graphify.build import build_from_json
343
+ from graphify.cluster import cluster, score_all
344
+ from graphify.analyze import god_nodes, surprising_connections, suggest_questions
345
+ from graphify.report import generate
346
+ from graphify.export import to_json
347
+ from pathlib import Path
348
+
349
+ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding='utf-8'))
350
+ detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
351
+
352
+ G = build_from_json(extraction)
353
+ communities = cluster(G)
354
+ cohesion = score_all(G, communities)
355
+ tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
356
+ gods = god_nodes(G)
357
+ surprises = surprising_connections(G, communities)
358
+ labels = {cid: 'Community ' + str(cid) for cid in communities}
359
+ questions = suggest_questions(G, communities, labels)
360
+
361
+ report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, '.', suggested_questions=questions)
362
+ Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding='utf-8')
363
+ to_json(G, communities, 'graphify-out/graph.json')
364
+
365
+ analysis = {
366
+ 'communities': {str(k): v for k, v in communities.items()},
367
+ 'cohesion': {str(k): v for k, v in cohesion.items()},
368
+ 'gods': gods, 'surprises': surprises, 'questions': questions,
369
+ }
370
+ Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding='utf-8')
371
+ if G.number_of_nodes() == 0:
372
+ print('ERROR: Graph is empty - extraction produced no nodes.')
373
+ raise SystemExit(1)
374
+ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
375
+ "
376
+ ```
377
+
378
+ If this step prints `ERROR: Graph is empty`, stop and tell the user.
379
+
380
+ ### Step 5 - Label communities
381
+
382
+ Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name.
383
+
384
+ Then regenerate the report:
385
+
386
+ ```bash
387
+ $(cat graphify-out/.graphify_python) -c "
388
+ import sys, json
389
+ from graphify.build import build_from_json
390
+ from graphify.cluster import score_all
391
+ from graphify.analyze import god_nodes, surprising_connections, suggest_questions
392
+ from graphify.report import generate
393
+ from pathlib import Path
394
+
395
+ extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding='utf-8'))
396
+ detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
397
+ analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding='utf-8'))
398
+
399
+ G = build_from_json(extraction)
400
+ communities = {int(k): v for k, v in analysis['communities'].items()}
401
+ cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
402
+ tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
403
+
404
+ # LABELS - replace with actual dict
405
+ labels = LABELS_DICT
406
+
407
+ questions = suggest_questions(G, communities, labels)
408
+ report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, '.', suggested_questions=questions)
409
+ Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding='utf-8')
410
+ 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')
411
+ print('Report updated with community labels')
412
+ "
413
+ ```
414
+
415
+ Replace `LABELS_DICT` with the actual dict (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
416
+
417
+ ### Step 6 - Generate HTML
418
+
419
+ ```bash
420
+ graphify export html
421
+ ```
422
+
423
+ ### Step 9 - Save manifest, update cost tracker, clean up
424
+
425
+ ```bash
426
+ $(cat graphify-out/.graphify_python) -c "
427
+ import json
428
+ from pathlib import Path
429
+ from datetime import datetime, timezone
430
+ from graphify.detect import save_manifest
431
+
432
+ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding='utf-8'))
433
+ save_manifest(detect.get('all_files') or detect['files'])
434
+
435
+ extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding='utf-8'))
436
+ input_tok = extract.get('input_tokens', 0)
437
+ output_tok = extract.get('output_tokens', 0)
438
+
439
+ cost_path = Path('graphify-out/cost.json')
440
+ if cost_path.exists():
441
+ cost = json.loads(cost_path.read_text(encoding='utf-8'))
442
+ else:
443
+ cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
444
+
445
+ cost['runs'].append({
446
+ 'date': datetime.now(timezone.utc).isoformat(),
447
+ 'input_tokens': input_tok, 'output_tokens': output_tok,
448
+ 'files': detect.get('total_files', 0),
449
+ })
450
+ cost['total_input_tokens'] += input_tok
451
+ cost['total_output_tokens'] += output_tok
452
+ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding='utf-8')
453
+ print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
454
+ "
455
+ 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
456
+ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
457
+ rm -f graphify-out/.needs_update graphify-out/.graphify_batches.json 2>/dev/null || true
458
+ ```
459
+
460
+ Tell the user:
461
+ ```
462
+ Graph complete. Outputs in graphify-out/
463
+
464
+ graph.html - interactive graph, open in browser
465
+ GRAPH_REPORT.md - audit report
466
+ graph.json - raw graph data
467
+ ```
468
+
469
+ Then paste these sections from GRAPH_REPORT.md:
470
+ - God Nodes
471
+ - Surprising Connections
472
+ - Suggested Questions
473
+
474
+ ## For /graphify query
475
+
476
+ When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph:
477
+
478
+ ```bash
479
+ graphify query "<question>"
480
+ ```
481
+
482
+ ## Honesty Rules
483
+
484
+ - Never invent an edge. If unsure, use AMBIGUOUS.
485
+ - Never skip the corpus check warning.
486
+ - Always show token cost in the report.
487
+ - 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
@@ -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({
@@ -199,5 +234,13 @@ export default function registerSkillLoader(pi: ExtensionAPI): void {
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
  }