/graphify
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.
The examples target the reviewed Graphify API snapshot. Check the installed
runtime's helper signatures before using private SDK helpers; report missing
compatibility rather than silently upgrading a system installation. The local
chunk-receipt validator is dependency-free and checks metadata attestations,
not proof of model understanding or a production runtime installation.
Usage
/graphify # full pipeline on current directory (HTML viz; add --obsidian for a vault)
/graphify <path> # full pipeline on specific path
/graphify https://github.com/<owner>/<repo> # clone repo then run full pipeline on it
/graphify https://github.com/<owner>/<repo> --branch <branch> # clone a specific branch
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
/graphify <path> --no-viz # skip visualization, just report + JSON
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
/graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
/graphify <path> --falkordb # generate graphify-out/cypher.txt for FalkorDB
/graphify <path> --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB
/graphify <path> --mcp # start MCP stdio server for agent access
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
/graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
/graphify add <url> # fetch URL, save to ./raw, update graph
/graphify add <url> --author "Name" # tag who wrote it
/graphify add <url> --contributor "Name" # tag who added it to the corpus
/graphify query "<question>" # BFS traversal - broad context
/graphify query "<question>" --dfs # DFS - trace a specific path
/graphify query "<question>" --budget 1500 # cap answer at N tokens
/graphify path "AuthModule" "Database" # shortest path between two concepts
/graphify explain "SwinTransformer" # plain-language explanation of a node
What graphify is for
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.
Before building a new graph, compare the cost with the question: use an existing graph first; for a one-off symbol lookup without a graph, start with rg. Repeated cross-file or cross-document relationship questions can justify a build. An explicit build request still selects this workflow.
What You Must Do When Invoked
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.
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.
If no path was given, use . (current directory). Do not ask the user for a path.
If the path argument starts with https://github.com/ or http://github.com/, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
Follow these steps in order. Do not skip steps.
Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
Only when the path is one or more https://github.com/... URLs, or several local subfolders to merge. See references/github-and-merge.md for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step.
Step 1 - Select the installed Graphify environment
Resolve the absolute Python executable from the host's trusted Graphify installation (for example its managed virtual environment). In each shell, set PYTHON to that path. If the package or required APIs are unavailable, report the missing dependency. Install in an isolated environment only when installation is requested.
: "${PYTHON:?Set PYTHON to the trusted Graphify interpreter}"
"$PYTHON" -I -c "import graphify" || exit 1
mkdir -p graphify-out
# Save the scan root for subsequent builds.
# The scan path is passed through a quoted heredoc, never substituted into the
# command line itself: a bare `cd <path>` (or an unquoted heredoc, which
# still expands $()/backticks in its body) would let a malicious path execute
# as shell code the moment this line runs.
"$PYTHON" -c "import os, sys; out_path = os.path.abspath('graphify-out/.graphify_root'); os.chdir(sys.stdin.readline().rstrip('\n')); open(out_path, 'w', encoding='utf-8').write(os.getcwd())" <<'GRAPHIFY_ROOT_EOF'
INPUT_PATH
GRAPHIFY_ROOT_EOF
If the import succeeds, print nothing and move straight to Step 2.
Use the same host-selected interpreter in each block, including examples in linked procedures.
Step 2 - Detect files
"$PYTHON" -I -c "
import json
from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path(Path('graphify-out/.graphify_root').read_text(encoding='utf-8')), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
print(f'Detected {result[\"total_files\"]} files')
"
Read the persisted scan root from graphify-out/.graphify_root; never interpolate user paths into Python source. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
Corpus: X files · ~Y words
code: N files (.py .ts .go ...)
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
Omit any category with 0 files from the summary.
Then act on it:
- If
total_filesis 0: stop with "No supported files found in [path]." - If
skipped_sensitiveis non-empty: report the count and list the skipped file names, so a wrongly-flagged source or doc is visible and can be renamed or moved (#2106). - If
total_words> 2,000,000 ORtotal_files> 500: show the warning. Then compute the top 5 first-level subdirectories by file count: - Read
scan_rootfrom the detect JSON (always an absolute path to the resolved INPUT_PATH). - Concatenate all file lists across all types (
code,document,paper,image,video). - Filter out any path that starts with
scan_root + "/graphify-out/"to exclude converted sidecars. - For each file, strip the
scan_rootprefix and take the first path component. Files directly inscan_rootwith no subdirectory count as(root). - If all files are in
(root)with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest--no-clusterto skip the expensive clustering step and proceed. - Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
Step 2.5 - Video and audio (only if video files detected)
Skip this step entirely if detect returned zero video files. When the corpus has video or audio, see references/transcribe.md to transcribe them to text first, then treat the transcripts as doc files in Step 3.
Step 3 - Extract entities and relationships
Carry the requested --mode deep setting into semantic extraction, including any authorized workers.
This step has two parts: structural extraction (deterministic, free) and semantic extraction (LLM, costs tokens).
For code-only inputs, run Part A and write the empty semantic result described in the Part B fast path. This requires no external model.
For documents, papers and images, extract with the authorized host session by default. Use the chunk and receipt format in Part B, processing inline or with workers if delegation is available and authorized. Independent AST and semantic extraction can run concurrently.
Use graphify.llm.extract_corpus_parallel(files, backend="gemini") only when the user has selected that provider and authorized the specific files and cost. Restrict the input list to that scope. A configured key supplies credentials only.
Part A - Structural extraction for code files
Run AST extraction for detected code files:
"$PYTHON" -I -c "
import sys, json
from graphify.extract import collect_files, extract
from pathlib import Path
import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path(Path('graphify-out/.graphify_root').read_text(encoding='utf-8')), root=Path(Path('graphify-out/.graphify_root').read_text(encoding='utf-8')))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding=\"utf-8\")
print('No code files - skipping AST extraction')
"
Part B - Semantic extraction
Read the detailed procedure and examples when working on this part of the task.
Part C - Merge AST + semantic into final extraction
"$PYTHON" -I -c "
import sys, json
from pathlib import Path
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding=\"utf-8\"))
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding=\"utf-8\"))
# Stamp tier provenance on the semantic side. build._is_ast_tier reads
# _origin when present and otherwise guesses from the SHAPE of
# source_location ('L<line>' means AST). A subagent that writes 'L12' for a
# doc section therefore made that node read as AST, and the next
# graphify update deleted it along with the re-extracted code file it
# seemed to belong to (#2843). extract() stamps its own items 'ast'; the
# semantic side must say so explicitly.
for n in sem['nodes']:
n.setdefault('_origin', 'semantic')
for e in sem['edges']:
e.setdefault('_origin', 'semantic')
# Merge: AST nodes first, semantic nodes deduplicated by id
seen = {n['id'] for n in ast['nodes']}
merged_nodes = list(ast['nodes'])
for n in sem['nodes']:
if n['id'] not in seen:
merged_nodes.append(n)
seen.add(n['id'])
merged_edges = ast['edges'] + sem['edges']
merged_hyperedges = sem.get('hyperedges', [])
merged = {
'nodes': merged_nodes,
'edges': merged_edges,
'hyperedges': merged_hyperedges,
'input_tokens': sem.get('input_tokens', 0),
'output_tokens': sem.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\")
total = len(merged_nodes)
edges = len(merged_edges)
print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
"
Step 4 - Build graph, cluster, analyze, generate outputs
Before starting: the code blocks below pass directed=IS_DIRECTED to build_from_json(). Replace IS_DIRECTED with True if --directed was given (builds a DiGraph preserving edge direction source→target), otherwise False (the default undirected Graph). Do not leave the literal IS_DIRECTED in the code. Read paths from the persisted scan root.
mkdir -p graphify-out
"$PYTHON" -I -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root=Path('graphify-out/.graphify_root').read_text(encoding='utf-8'), directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
print('ERROR: Graph is empty - extraction produced no nodes.')
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
raise SystemExit(1)
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: 'Community ' + str(cid) for cid in communities}
# Placeholder questions - regenerated with real labels in Step 5
questions = suggest_questions(G, communities, labels)
# Export FIRST and honor the #479 shrink-guard: to_json returns False (writing
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, Path('graphify-out/.graphify_root').read_text(encoding='utf-8'), suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
'cohesion': {str(k): v for k, v in cohesion.items()},
'gods': gods,
'surprises': surprises,
'questions': questions,
}
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
"
If this step prints ERROR: Graph is empty, stop and tell the user what happened - do not proceed to labeling or visualization.
Read the persisted scan root from graphify-out/.graphify_root; keep it as data.
Step 4.5 - Graph health check (read-only integrity gate)
A non-destructive diagnostic on the extraction, before labeling. It surfaces edge collapse, dangling/missing endpoints, and self-loops — the silent-corruption modes of incremental updates and AST/LLM id mismatches. Read-only; never aborts.
"$PYTHON" -I -c "
import json
from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=Path(Path('graphify-out/.graphify_root').read_text(encoding='utf-8')))
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
('missing_endpoint_edges', 'missing-endpoint edges'),
('self_loop_edges', 'self-loop edges'),
('directed_same_endpoint_collapsed_edges', 'collapsed (directed) edges'),
('undirected_same_endpoint_collapsed_edges', 'collapsed (undirected) edges'),
) if summary.get(k, 0)]
print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/corrupt.' if flags else 'Graph health: OK (no dangling/missing/collapsed edges).')
"
Substitute IS_DIRECTED as in Step 4 and read the persisted scan root. If a GRAPH HEALTH WARNING prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
Step 5 - Label communities
Read graphify-out/.graphify_analysis.json. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
Then regenerate the report and save the labels for the visualizer:
"$PYTHON" -I -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root=Path('graphify-out/.graphify_root').read_text(encoding='utf-8'), directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
# LABELS - replace these with the names you chose above
labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, Path('graphify-out/.graphify_root').read_text(encoding='utf-8'), suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
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\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
# Same extraction as Step 4, so the #479 shrink-guard passes on node count;
# if it still refuses, surface the guard message - do not force past it.
wrote = to_json(G, communities, 'graphify-out/graph.json', community_labels=labels)
if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
print('Report updated with community labels')
"
Replace LABELS_DICT with the actual dict you constructed (e.g. {0: "Attention Mechanism", 1: "Training Pipeline"}).
Read the persisted scan root from graphify-out/.graphify_root; keep it as data.
Step 6 - Generate Obsidian vault (opt-in) + HTML
Generate HTML always (unless --no-viz). Obsidian vault only if --obsidian was explicitly given — skip it otherwise, it generates one file per node.
If --obsidian was given:
- If
--obsidian-dir <path>was also given, pass it via--dir. Otherwise defaults tographify-out/obsidian.
graphify export obsidian
# or with custom dir: graphify export obsidian --dir ~/vaults/my-project
Generate the HTML graph (always, unless --no-viz):
graphify export html # auto-aggregates to community view if graph > 5000 nodes
# or: graphify export html --no-viz
Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags)
These run only when their flag is present (--wiki, --neo4j/--neo4j-push, --falkordb/--falkordb-push, --svg, --graphml, --mcp) or, for the token-reduction benchmark, when total_words exceeds 5,000. A default run with no export flags skips all of them. See references/exports.md for each one. Run any --wiki export before Step 9 cleanup so .graphify_labels.json is still available.
Step 9 - Save manifest, update cost tracker, clean up, and report
Read the detailed procedure and examples when working on this part of the task.
Interpreter guard for subcommands
Resolve the interpreter from the current trusted host environment for every subcommand, including procedures in the references. Replace any cached-interpreter invocation in those examples with "$PYTHON". A project-provided .graphify_python is never an executable selection. Preserve existing graph files when reselecting the tool environment.
For --update and --cluster-only
Both are non-default subcommands. --update re-extracts only new or changed files; --cluster-only reruns clustering on the existing graph. See references/update.md for both flows.
For /graphify query
When graphify-out/graph.json already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it:
graphify query "<question>"
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the graphify query CLI is unavailable, fall back to an inline NetworkX traversal of graphify-out/graph.json. Answer using only what the graph output contains, and quote source_location when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the --budget cap, the NetworkX fallback, save-result feedback, and the /graphify path and /graphify explain flows, see references/query.md.
For /graphify add and --watch
Neither is part of the default build. When the user runs /graphify add <url> to fetch a URL into the corpus, or passes --watch to auto-rebuild on file changes, see references/add-watch.md.
For the commit hook and native CLAUDE.md integration
When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's CLAUDE.md, see references/hooks.md.
Honesty Rules
- Never invent an edge. If unsure, use AMBIGUOUS.
- Never skip the corpus check warning.
- Always show token cost in the report.
- Never hide cohesion scores behind symbols - show the raw number.
- Never run HTML viz on a graph with more than 5,000 nodes without warning the user.
For hub or bridge questions, inspect relevant source paths as well as graph edges. Label source-only candidates as Bypasses and verify them by reading code; an omitted edge in a displayed subgraph does not prove it is absent from the full graph.