Compare commits

..
2 Commits
Author SHA1 Message Date
SafiandClaude Sonnet 4.6 91f4d120b6 fix worktree hook crash, prune isolated code nodes, restore rationale-node prohibition
- hooks.py: use git rev-parse --git-path hooks so install/status/uninstall
  work in linked worktrees where .git is a file not a directory (fixes #865)
- build.py: prune degree-0 code nodes after graph assembly to remove
  bundled/synthetic symbols with no connections (fixes #728)
- skill.md: restore explicit rule prohibiting file_type:"rationale" nodes
  and remind model to store rationale as an attribute instead (fixes #751)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 23:03:21 +01:00
Safi a01e0981ed fix #374 #401 #410 #413 #385: vscode install cmd, core.hooksPath, absolute cache root, Windows PATH docs, Kiro YAML colon 2026-04-17 08:33:02 +01:00
14 changed files with 232 additions and 552 deletions

No files matched your search

+2 -2
View File
@@ -2,9 +2,9 @@ name: CI
on:
push:
branches: ["v1", "v2", "main"]
branches: ["v1", "main"]
pull_request:
branches: ["v1", "v2", "main"]
branches: ["v1", "main"]
jobs:
test:
+15 -47
View File
@@ -1,9 +1,8 @@
# graphify
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v2)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v1)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
**A Claude Code skill.** Type `/graphify` in Claude Code - it reads your files, builds a knowledge graph, and gives you back structure you didn't know was there. Understand a codebase faster. Find the "why" behind architectural decisions.
**A Claude Code skill.** Type `/graphify` in Claude Code - it reads your files, builds a knowledge graph, and gives you back structure you didn't know was there.
Fully multimodal. Drop in code, PDFs, markdown, screenshots, diagrams, whiteboard photos, even images in other languages - graphify uses Claude vision to extract concepts and relationships from all of it and connects them into one graph.
@@ -16,17 +15,13 @@ Fully multimodal. Drop in code, PDFs, markdown, screenshots, diagrams, whiteboar
```
graphify-out/
├── graph.html interactive graph - click nodes, search, filter by community
├── obsidian/ open as Obsidian vault
├── wiki/ Wikipedia-style articles for agent navigation (--wiki)
├── GRAPH_REPORT.md god nodes, surprising connections, suggested questions
├── graph.json persistent graph - query weeks later without re-reading
└── cache/ SHA256 cache - re-runs only process changed files
```
## How it works
graphify runs in two passes. First, a deterministic AST pass extracts structure from code files (classes, functions, imports, call graphs, docstrings, rationale comments) with no LLM needed. Second, Claude subagents run in parallel over docs, papers, and images to extract concepts, relationships, and design rationale. The results are merged into a NetworkX graph, clustered with Leiden community detection, and exported as interactive HTML, queryable JSON, and a plain-language audit report.
Every relationship is tagged `EXTRACTED` (found directly in source), `INFERRED` (reasonable inference, with a confidence score), or `AMBIGUOUS` (flagged for review). You always know what was found vs guessed.
## Install
**Requires:** [Claude Code](https://claude.ai/code) and Python 3.10+
@@ -37,36 +32,21 @@ pip install graphifyy && graphify install
> The PyPI package is temporarily named `graphifyy` while the `graphify` name is being reclaimed. The CLI and skill command are still `graphify`.
> **Windows:** If `graphify` is not recognized after install, add the Python Scripts folder to your PATH: `%APPDATA%\Python\Python3xx\Scripts` (replace `3xx` with your Python version, e.g. `313`). Or use `pipx install graphifyy` which handles PATH automatically.
> **macOS (externally managed):** Use `pipx install graphifyy` if `pip install` fails with an "externally-managed-environment" error.
Then open Claude Code in any directory and type:
```
/graphify .
```
### Make Claude always use the graph (recommended)
After building a graph, run this once in your project:
```bash
graphify claude install
```
This does two things:
1. **CLAUDE.md rules** - tells Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and to rebuild the graph after editing code files.
2. **PreToolUse hook** (`settings.json`) - fires automatically before every Glob and Grep call. If a knowledge graph exists, Claude sees: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ This means Claude navigates via the graph instead of grepping through every file - faster answers, fewer wasted tool calls, and responses grounded in the actual structure of your codebase rather than keyword matches.
Without this, Claude will grep raw files by default even when a graph exists. With it, the graph becomes the first thing Claude reaches for.
Uninstall with `graphify claude uninstall`.
<details>
<summary>Manual install (curl)</summary>
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v2/graphify/skill.md \
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v1/skills/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
```
@@ -86,7 +66,6 @@ When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"`
/graphify ./raw # run on a specific folder
/graphify ./raw --mode deep # more aggressive INFERRED edge extraction
/graphify ./raw --update # re-extract only changed files, merge into existing graph
/graphify ./raw --obsidian # also generate Obsidian vault (opt-in)
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper, save, update graph
/graphify add https://x.com/karpathy/status/... # fetch a tweet
@@ -102,16 +81,15 @@ When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"`
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
/graphify ./raw --mcp # start MCP stdio server
graphify hook install # git hooks - rebuilds graph on commit and branch switch
graphify claude install # always-on: CLAUDE.md + PreToolUse hook for this project
graphify hook install # post-commit git hook - rebuilds graph on every commit automatically
```
Works with any mix of file types:
| Type | Extensions | Extraction |
|------|-----------|------------|
| Code | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php` | AST via tree-sitter + call-graph + docstring/comment rationale |
| Docs | `.md .txt .rst` | Concepts + relationships + design rationale via Claude |
| Code | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php` | AST via tree-sitter + call-graph pass |
| Docs | `.md .txt .rst` | Concepts + relationships via Claude |
| Papers | `.pdf` | Citation mining + concept extraction |
| Images | `.png .jpg .webp .gif` | Claude vision - screenshots, diagrams, any language |
@@ -123,22 +101,16 @@ Works with any mix of file types:
**Suggested questions** - 4-5 questions the graph is uniquely positioned to answer
**The "why"** - docstrings, inline comments (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), and design rationale from docs are extracted as `rationale_for` nodes. Not just what the code does - why it was written that way.
**Confidence scores** - every INFERRED edge has a `confidence_score` (0.0-1.0). You know not just what was guessed but how confident the model was. EXTRACTED edges are always 1.0.
**Semantic similarity edges** - cross-file conceptual links with no structural connection. Two functions solving the same problem without calling each other, a class in code and a concept in a paper describing the same algorithm.
**Hyperedges** - group relationships connecting 3+ nodes that pairwise edges can't express. All classes implementing a shared protocol, all functions in an auth flow, all concepts from a paper section forming one idea.
**Token benchmark** - printed automatically after every run. On a mixed corpus (Karpathy repos + papers + images): **71.5x** fewer tokens per query vs reading raw files.
**Auto-sync** (`--watch`) - run in a background terminal and the graph updates itself as your codebase changes. Code file saves trigger an instant rebuild (AST only, no LLM). Doc/image changes notify you to run `--update` for the LLM re-pass.
**Auto-sync** (`--watch`) - run in a background terminal and the graph updates itself as your codebase changes. Code file saves trigger an instant rebuild (AST only, no LLM). Doc/image changes notify you to run `--update` for the LLM re-pass. Useful for agentic workflows where multiple agents are writing code in parallel - the graph stays current between waves automatically.
**Git hooks** (`graphify hook install`) - installs post-commit and post-checkout hooks. Graph rebuilds automatically after every commit and every branch switch. No background process needed.
**Git commit hook** (`graphify hook install`) - installs a post-commit hook that rebuilds the graph after every commit. No background process needed. Triggers once per commit, works with any editor, safe to add alongside existing hooks.
**Wiki** (`--wiki`) - Wikipedia-style markdown articles per community and god node, with an `index.md` entry point. Point any agent at `index.md` and it can navigate the knowledge base by reading files instead of parsing JSON.
Every edge is tagged `EXTRACTED`, `INFERRED`, or `AMBIGUOUS` - you always know what was found vs guessed.
## Worked examples
| Corpus | Files | Reduction | Output |
@@ -149,10 +121,6 @@ Works with any mix of file types:
Token reduction scales with corpus size. 6 files fits in a context window anyway, so graph value there is structural clarity, not compression. At 52 files (code + papers + images) you get 71x+. Each `worked/` folder has the raw input files and the actual output (`GRAPH_REPORT.md`, `graph.json`) so you can run it yourself and verify the numbers.
## Privacy
graphify sends file contents to the Claude API (Anthropic) for semantic extraction of docs, papers, and images. Code files are processed locally via tree-sitter AST — no file contents leave your machine for code. No telemetry, usage tracking, or analytics of any kind. The only network calls are to Anthropic's API during extraction, using your own API key via Claude Code.
## Tech stack
NetworkX + Leiden (graspologic) + tree-sitter + Claude + vis.js. No Neo4j required, no server, runs entirely locally.
+40 -59
View File
@@ -6,20 +6,6 @@ import shutil
import sys
from pathlib import Path
_SETTINGS_HOOK = {
"matcher": "Glob|Grep",
"hooks": [
{
"type": "command",
"command": (
"[ -f graphify-out/graph.json ] && "
"echo 'graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md "
"for god nodes and community structure before searching raw files.' || true"
),
}
],
}
_SKILL_REGISTRATION = (
"\n# graphify\n"
"- **graphify** (`~/.claude/skills/graphify/SKILL.md`) "
@@ -96,57 +82,44 @@ def claude_install(project_dir: Path | None = None) -> None:
target.write_text(new_content)
print(f"graphify section written to {target.resolve()}")
# Also write Claude Code PreToolUse hook to .claude/settings.json
_install_claude_hook(project_dir or Path("."))
print()
print("Claude Code will now check the knowledge graph before answering")
print("codebase questions and rebuild it after code changes.")
def _install_claude_hook(project_dir: Path) -> None:
"""Add graphify PreToolUse hook to .claude/settings.json."""
settings_path = project_dir / ".claude" / "settings.json"
settings_path.parent.mkdir(parents=True, exist_ok=True)
_COPILOT_INSTRUCTIONS = """\
## graphify knowledge graph
if settings_path.exists():
try:
settings = json.loads(settings_path.read_text())
except json.JSONDecodeError:
settings = {}
This project has a graphify knowledge graph at graphify-out/.
- Before answering architecture or codebase questions, read graphify-out/GRAPH_REPORT.md for god nodes and community structure
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
- After modifying code files, run: python3 -c "from graphify.watch import _rebuild_code; from pathlib import Path; _rebuild_code(Path('.'))"
"""
_COPILOT_MARKER = "## graphify knowledge graph"
def vscode_install(project_dir: Path | None = None) -> None:
"""Write graphify context to .github/copilot-instructions.md."""
base = (project_dir or Path(".")).resolve()
github_dir = base / ".github"
github_dir.mkdir(exist_ok=True)
target = github_dir / "copilot-instructions.md"
if target.exists():
content = target.read_text()
if _COPILOT_MARKER in content:
print("graphify already configured in .github/copilot-instructions.md")
return
target.write_text(content.rstrip() + "\n\n" + _COPILOT_INSTRUCTIONS)
else:
settings = {}
target.write_text(_COPILOT_INSTRUCTIONS)
hooks = settings.setdefault("hooks", {})
pre_tool = hooks.setdefault("PreToolUse", [])
# Check if already installed
if any(h.get("matcher") == "Glob|Grep" and "graphify" in str(h) for h in pre_tool):
print(f" .claude/settings.json → hook already registered (no change)")
return
pre_tool.append(_SETTINGS_HOOK)
settings_path.write_text(json.dumps(settings, indent=2))
print(f" .claude/settings.json → PreToolUse hook registered")
def _uninstall_claude_hook(project_dir: Path) -> None:
"""Remove graphify PreToolUse hook from .claude/settings.json."""
settings_path = project_dir / ".claude" / "settings.json"
if not settings_path.exists():
return
try:
settings = json.loads(settings_path.read_text())
except json.JSONDecodeError:
return
pre_tool = settings.get("hooks", {}).get("PreToolUse", [])
filtered = [h for h in pre_tool if not (h.get("matcher") == "Glob|Grep" and "graphify" in str(h))]
if len(filtered) == len(pre_tool):
return
settings["hooks"]["PreToolUse"] = filtered
settings_path.write_text(json.dumps(settings, indent=2))
print(f" .claude/settings.json → PreToolUse hook removed")
print(f"graphify instructions written to {target}")
print()
print("GitHub Copilot Chat will now use the knowledge graph when answering")
print("questions about this codebase.")
def claude_uninstall(project_dir: Path | None = None) -> None:
@@ -171,12 +144,12 @@ def claude_uninstall(project_dir: Path | None = None) -> None:
).rstrip()
if cleaned:
target.write_text(cleaned + "\n")
print(f"graphify section removed from {target.resolve()}")
else:
target.unlink()
print(f"CLAUDE.md was empty after removal - deleted {target.resolve()}")
return
_uninstall_claude_hook(project_dir or Path("."))
print(f"graphify section removed from {target.resolve()}")
def main() -> None:
@@ -185,6 +158,7 @@ def main() -> None:
print()
print("Commands:")
print(" install copy skill to ~/.claude/skills/ and register in CLAUDE.md")
print(" vscode install write graphify context to .github/copilot-instructions.md")
print(" benchmark [graph.json] measure token reduction vs naive full-corpus approach")
print(" hook install install post-commit git hook (auto-rebuilds graph on commit)")
print(" hook uninstall remove post-commit git hook")
@@ -197,6 +171,13 @@ def main() -> None:
cmd = sys.argv[1]
if cmd == "install":
install()
elif cmd == "vscode":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
vscode_install()
else:
print("Usage: graphify vscode install", file=sys.stderr)
sys.exit(1)
elif cmd == "claude":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
+9
View File
@@ -28,6 +28,15 @@ def build_from_json(extraction: dict) -> nx.Graph:
hyperedges = extraction.get("hyperedges", [])
if hyperedges:
G.graph["hyperedges"] = hyperedges
# Strip degree-0 code nodes — they are bundled/synthetic symbols with no
# connections and only inflate god-node centrality and clustering noise.
# Document, paper, and image nodes are kept even when isolated since they
# may be leaf concepts intentionally referenced by the skill.
isolated_code = [
n for n in list(G.nodes())
if G.degree(n) == 0 and G.nodes[n].get("file_type") == "code"
]
G.remove_nodes_from(isolated_code)
return G
+5 -12
View File
@@ -13,7 +13,7 @@ def file_hash(path: Path) -> str:
def cache_dir(root: Path = Path(".")) -> Path:
"""Returns graphify-out/cache/ - creates it if needed."""
d = Path(root) / "graphify-out" / "cache"
d = Path(root).resolve() / "graphify-out" / "cache"
d.mkdir(parents=True, exist_ok=True)
return d
@@ -65,15 +65,14 @@ def clear_cache(root: Path = Path(".")) -> None:
def check_semantic_cache(
files: list[str],
root: Path = Path("."),
) -> tuple[list[dict], list[dict], list[dict], list[str]]:
) -> tuple[list[dict], list[dict], list[str]]:
"""Check semantic extraction cache for a list of absolute file paths.
Returns (cached_nodes, cached_edges, cached_hyperedges, uncached_files).
Returns (cached_nodes, cached_edges, uncached_files).
Uncached files need Claude extraction; cached files are merged directly.
"""
cached_nodes: list[dict] = []
cached_edges: list[dict] = []
cached_hyperedges: list[dict] = []
uncached: list[str] = []
for fpath in files:
@@ -81,17 +80,15 @@ def check_semantic_cache(
if result is not None:
cached_nodes.extend(result.get("nodes", []))
cached_edges.extend(result.get("edges", []))
cached_hyperedges.extend(result.get("hyperedges", []))
else:
uncached.append(fpath)
return cached_nodes, cached_edges, cached_hyperedges, uncached
return cached_nodes, cached_edges, uncached
def save_semantic_cache(
nodes: list[dict],
edges: list[dict],
hyperedges: list[dict] | None = None,
root: Path = Path("."),
) -> int:
"""Save semantic extraction results to cache, keyed by source_file.
@@ -101,7 +98,7 @@ def save_semantic_cache(
"""
from collections import defaultdict
by_file: dict[str, dict] = defaultdict(lambda: {"nodes": [], "edges": [], "hyperedges": []})
by_file: dict[str, dict] = defaultdict(lambda: {"nodes": [], "edges": []})
for n in nodes:
src = n.get("source_file", "")
if src:
@@ -110,10 +107,6 @@ def save_semantic_cache(
src = e.get("source_file", "")
if src:
by_file[src]["edges"].append(e)
for h in (hyperedges or []):
src = h.get("source_file", "")
if src:
by_file[src]["hyperedges"].append(h)
saved = 0
for fpath, result in by_file.items():
+7 -20
View File
@@ -1,25 +1,8 @@
"""Community detection on NetworkX graphs. Uses Leiden (graspologic) if available, falls back to Louvain (networkx). Splits oversized communities. Returns cohesion scores."""
"""Leiden community detection on NetworkX graphs. Splits oversized communities. Returns cohesion scores."""
from __future__ import annotations
import networkx as nx
def _partition(G: nx.Graph) -> dict[str, int]:
"""Run community detection. Returns {node_id: community_id}.
Tries Leiden (graspologic) first — best quality.
Falls back to Louvain (built into networkx) if graspologic is not installed.
"""
try:
from graspologic.partition import leiden
return leiden(G)
except ImportError:
pass
# Fallback: networkx louvain (available since networkx 2.7)
communities = nx.community.louvain_communities(G, seed=42)
return {node: cid for cid, nodes in enumerate(communities) for node in nodes}
def build_graph(nodes: list[dict], edges: list[dict]) -> nx.Graph:
"""Build a NetworkX graph from graphify node/edge dicts.
@@ -53,6 +36,8 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
if G.number_of_edges() == 0:
return {i: [n] for i, n in enumerate(sorted(G.nodes))}
from graspologic.partition import leiden # lazy - avoids 15s numba JIT on import
# Leiden warns and drops isolates - handle them separately
isolates = [n for n in G.nodes() if G.degree(n) == 0]
connected_nodes = [n for n in G.nodes() if G.degree(n) > 0]
@@ -60,7 +45,7 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
raw: dict[int, list[str]] = {}
if connected.number_of_nodes() > 0:
partition = _partition(connected)
partition: dict[str, int] = leiden(connected)
for node, cid in partition.items():
raw.setdefault(cid, []).append(node)
@@ -91,11 +76,13 @@ def _split_community(G: nx.Graph, nodes: list[str]) -> list[list[str]]:
# No edges - split into individual nodes
return [[n] for n in sorted(nodes)]
try:
sub_partition = _partition(subgraph)
from graspologic.partition import leiden
sub_partition: dict[str, int] = leiden(subgraph)
sub_communities: dict[int, list[str]] = {}
for node, cid in sub_partition.items():
sub_communities.setdefault(cid, []).append(node)
if len(sub_communities) <= 1:
# Leiden couldn't split it - return as-is
return [sorted(nodes)]
return [sorted(v) for v in sub_communities.values()]
except Exception:
-86
View File
@@ -149,92 +149,6 @@ def extract_python(path: Path) -> dict:
function_bodies: list[tuple[str, object]] = []
walk(root)
# ── Docstring + rationale comment extraction ──────────────────────────────
# Extract module/class/function docstrings and inline rationale comments.
# These become rationale nodes connected to their parent entity via rationale_for.
_RATIONALE_PREFIXES = ("# NOTE:", "# IMPORTANT:", "# HACK:", "# WHY:", "# RATIONALE:", "# TODO:", "# FIXME:")
def _get_docstring(body_node) -> tuple[str, int] | None:
"""Return (text, line) of the first string literal in a body node, or None."""
if not body_node:
return None
for child in body_node.children:
if child.type == "expression_statement":
for sub in child.children:
if sub.type in ("string", "concatenated_string"):
text = source[sub.start_byte:sub.end_byte].decode("utf-8", errors="replace")
text = text.strip("\"'").strip('"""').strip("'''").strip()
if len(text) > 20:
return text, child.start_point[0] + 1
break # docstring must be the first statement
return None
def _add_rationale(text: str, line: int, parent_nid: str) -> None:
label = text[:80].replace("\n", " ").strip()
rid = _make_id(stem, "rationale", str(line))
if rid not in seen_ids:
seen_ids.add(rid)
nodes.append({
"id": rid,
"label": label,
"file_type": "rationale",
"source_file": str_path,
"source_location": f"L{line}",
})
edges.append({
"source": rid,
"target": parent_nid,
"relation": "rationale_for",
"confidence": "EXTRACTED",
"source_file": str_path,
"source_location": f"L{line}",
"weight": 1.0,
})
# Module-level docstring
module_body = root # module itself acts as the body
ds = _get_docstring(module_body)
if ds:
_add_rationale(ds[0], ds[1], file_nid)
# Class and function docstrings (re-walk tree for body nodes)
def walk_docstrings(node, parent_nid: str) -> None:
t = node.type
if t == "class_definition":
name_node = node.child_by_field_name("name")
body = node.child_by_field_name("body")
if name_node and body:
class_name = source[name_node.start_byte:name_node.end_byte].decode("utf-8", errors="replace")
nid = _make_id(stem, class_name)
ds = _get_docstring(body)
if ds:
_add_rationale(ds[0], ds[1], nid)
for child in body.children:
walk_docstrings(child, nid)
return
if t == "function_definition":
name_node = node.child_by_field_name("name")
body = node.child_by_field_name("body")
if name_node and body:
func_name = source[name_node.start_byte:name_node.end_byte].decode("utf-8", errors="replace")
nid = _make_id(parent_nid, func_name) if parent_nid != file_nid else _make_id(stem, func_name)
ds = _get_docstring(body)
if ds:
_add_rationale(ds[0], ds[1], nid)
return
for child in node.children:
walk_docstrings(child, parent_nid)
walk_docstrings(root, file_nid)
# Rationale comments (# NOTE:, # IMPORTANT:, etc.)
source_text = source.decode("utf-8", errors="replace")
for lineno, line_text in enumerate(source_text.splitlines(), start=1):
stripped = line_text.strip()
if any(stripped.startswith(p) for p in _RATIONALE_PREFIXES):
_add_rationale(stripped, lineno, file_nid)
# ── Call-graph pass ───────────────────────────────────────────────────────
# Build label→nid lookup from all nodes collected above.
# Normalise: strip "()" suffix and leading "." so "cohesion_score()" and
+79 -85
View File
@@ -1,9 +1,9 @@
# git hook integration - install/uninstall graphify post-commit and post-checkout hooks
# git hook integration - install/uninstall graphify post-commit hook
from __future__ import annotations
import subprocess
from pathlib import Path
_HOOK_MARKER = "# graphify-hook"
_CHECKOUT_MARKER = "# graphify-checkout-hook"
_HOOK_SCRIPT = """\
#!/bin/bash
@@ -45,38 +45,6 @@ except Exception as exc:
"""
_CHECKOUT_SCRIPT = """\
#!/bin/bash
# graphify-checkout-hook
# Auto-rebuilds the knowledge graph (code only) when switching branches.
# Installed by: graphify hook install
PREV_HEAD=$1
NEW_HEAD=$2
BRANCH_SWITCH=$3
# Only run on branch switches, not file checkouts
if [ "$BRANCH_SWITCH" != "1" ]; then
exit 0
fi
# Only run if graphify-out/ exists (graph has been built before)
if [ ! -d "graphify-out" ]; then
exit 0
fi
echo "[graphify] Branch switched - rebuilding knowledge graph (code files)..."
python3 -c "
from graphify.watch import _rebuild_code
from pathlib import Path
try:
_rebuild_code(Path('.'))
except Exception as exc:
print(f'[graphify] Rebuild failed: {exc}')
"
"""
def _git_root(path: Path) -> Path | None:
"""Walk up to find .git directory."""
current = path.resolve()
@@ -86,78 +54,104 @@ def _git_root(path: Path) -> Path | None:
return None
def _install_hook(hooks_dir: Path, name: str, script: str, marker: str) -> str:
"""Install a single git hook, appending if an existing hook is present."""
hook_path = hooks_dir / name
if hook_path.exists():
content = hook_path.read_text()
if marker in content:
return f"already installed at {hook_path}"
hook_path.write_text(content.rstrip() + "\n\n" + script)
return f"appended to existing {name} hook at {hook_path}"
hook_path.write_text(script)
hook_path.chmod(0o755)
return f"installed at {hook_path}"
def _hooks_dir(root: Path) -> Path:
"""Return the active hooks directory for this repo.
def _uninstall_hook(hooks_dir: Path, name: str, marker: str) -> str:
"""Remove graphify section from a git hook."""
hook_path = hooks_dir / name
if not hook_path.exists():
return f"no {name} hook found - nothing to remove."
content = hook_path.read_text()
if marker not in content:
return f"graphify hook not found in {name} - nothing to remove."
before = content.split(marker)[0].rstrip()
non_empty = [l for l in before.splitlines() if l.strip() and not l.startswith("#!")]
if not non_empty:
hook_path.unlink()
return f"removed {name} hook at {hook_path}"
hook_path.write_text(before + "\n")
return f"graphify removed from {name} at {hook_path} (other hook content preserved)"
Respects core.hooksPath if set (e.g. repos using Husky). Falls back to
.git/hooks so we never write hooks into the wrong location.
"""
try:
result = subprocess.run(
["git", "-C", str(root), "config", "core.hooksPath"],
capture_output=True, text=True,
)
if result.returncode == 0:
custom = result.stdout.strip()
if custom:
p = Path(custom)
if not p.is_absolute():
p = root / p
p.mkdir(parents=True, exist_ok=True)
return p
except (OSError, FileNotFoundError):
pass
# In a linked worktree .git is a file not a directory, so we ask git
# for the real hooks path rather than constructing it ourselves.
try:
result = subprocess.run(
["git", "-C", str(root), "rev-parse", "--path-format=absolute", "--git-path", "hooks"],
capture_output=True, text=True,
)
if result.returncode == 0:
d = Path(result.stdout.strip())
d.mkdir(parents=True, exist_ok=True)
return d
except (OSError, FileNotFoundError):
pass
d = root / ".git" / "hooks"
d.mkdir(parents=True, exist_ok=True)
return d
def install(path: Path = Path(".")) -> str:
"""Install graphify post-commit and post-checkout hooks in the nearest git repo."""
"""Install graphify post-commit hook in the nearest git repo.
Returns a message describing what was done.
"""
root = _git_root(path)
if root is None:
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
hooks_dir = root / ".git" / "hooks"
hooks_dir.mkdir(exist_ok=True)
hooks_dir = _hooks_dir(root)
hook_path = hooks_dir / "post-commit"
commit_msg = _install_hook(hooks_dir, "post-commit", _HOOK_SCRIPT, _HOOK_MARKER)
checkout_msg = _install_hook(hooks_dir, "post-checkout", _CHECKOUT_SCRIPT, _CHECKOUT_MARKER)
if hook_path.exists():
content = hook_path.read_text()
if _HOOK_MARKER in content:
return f"graphify hook already installed at {hook_path}"
# Append to existing hook
hook_path.write_text(content.rstrip() + "\n\n" + _HOOK_SCRIPT)
return f"graphify hook appended to existing post-commit hook at {hook_path}"
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
hook_path.write_text(_HOOK_SCRIPT)
hook_path.chmod(0o755)
return f"graphify hook installed at {hook_path}"
def uninstall(path: Path = Path(".")) -> str:
"""Remove graphify post-commit and post-checkout hooks."""
"""Remove graphify post-commit hook."""
root = _git_root(path)
if root is None:
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
hooks_dir = root / ".git" / "hooks"
commit_msg = _uninstall_hook(hooks_dir, "post-commit", _HOOK_MARKER)
checkout_msg = _uninstall_hook(hooks_dir, "post-checkout", _CHECKOUT_MARKER)
hook_path = _hooks_dir(root) / "post-commit"
if not hook_path.exists():
return "No post-commit hook found - nothing to remove."
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
content = hook_path.read_text()
if _HOOK_MARKER not in content:
return "graphify hook not found in post-commit - nothing to remove."
# Strip everything from our marker onwards
before = content.split(_HOOK_MARKER)[0].rstrip()
# 'before' is empty or just a shebang line if the whole file was ours
non_empty = [l for l in before.splitlines() if l.strip() and not l.startswith("#!")]
if not non_empty:
hook_path.unlink()
return f"Removed post-commit hook at {hook_path}"
else:
hook_path.write_text(before + "\n")
return f"graphify hook removed from {hook_path} (other hook content preserved)"
def status(path: Path = Path(".")) -> str:
"""Check if graphify hooks are installed."""
"""Check if graphify hook is installed."""
root = _git_root(path)
if root is None:
return "Not in a git repository."
hooks_dir = root / ".git" / "hooks"
def _check(name: str, marker: str) -> str:
p = hooks_dir / name
if not p.exists():
return "not installed"
return "installed" if marker in p.read_text() else "not installed (hook exists but graphify not found)"
commit = _check("post-commit", _HOOK_MARKER)
checkout = _check("post-checkout", _CHECKOUT_MARKER)
return f"post-commit: {commit}\npost-checkout: {checkout}"
hook_path = _hooks_dir(root) / "post-commit"
if not hook_path.exists():
return "graphify hook: not installed"
if _HOOK_MARKER in hook_path.read_text():
return f"graphify hook: installed at {hook_path}"
return "graphify hook: not installed (post-commit exists but graphify hook not found)"
+69 -76
View File
@@ -1,6 +1,6 @@
---
name: graphify
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
description: "any input (code, docs, papers, images) - knowledge graph - clustered communities - HTML + JSON + audit report"
trigger: /graphify
---
@@ -58,26 +58,15 @@ Follow these steps in order. Do not skip steps.
### Step 1 - Ensure graphify is installed
```bash
# Detect the correct Python interpreter (handles pipx, venv, system installs)
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
if [ -n "$GRAPHIFY_BIN" ]; then
PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
else
PYTHON="python3"
fi
$PYTHON -c "import graphify" 2>/dev/null || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
# Write interpreter path for all subsequent steps
$PYTHON -c "import sys; open('.graphify_python', 'w').write(sys.executable)"
python3 -c "import graphify" 2>/dev/null || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
```
If the import succeeds, print nothing and move straight to Step 2.
**In every subsequent bash block, replace `python3` with `$(cat .graphify_python)` to use the correct interpreter.**
### Step 2 - Detect files
```bash
$(cat .graphify_python) -c "
python3 -c "
import json
from graphify.detect import detect
from pathlib import Path
@@ -117,7 +106,7 @@ Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is determin
For any code files detected, run AST extraction in parallel with Part B subagents:
```bash
$(cat .graphify_python) -c "
python3 -c "
import sys, json
from graphify.extract import collect_files, extract
from pathlib import Path
@@ -155,7 +144,7 @@ Before dispatching subagents, print a timing estimate:
Before dispatching any subagents, check which files already have cached extraction results:
```bash
$(cat .graphify_python) -c "
python3 -c "
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
@@ -163,10 +152,10 @@ from pathlib import Path
detect = json.loads(Path('.graphify_detect.json').read_text())
all_files = [f for files in detect['files'].values() for f in files]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
cached_nodes, cached_edges, uncached = check_semantic_cache(all_files)
if cached_nodes or cached_edges or cached_hyperedges:
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
if cached_nodes or cached_edges:
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges}))
Path('.graphify_uncached.txt').write_text('\n'.join(uncached))
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
"
@@ -206,7 +195,10 @@ Rules:
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made,
trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT
create a separate rationale node. Valid `file_type` values are ONLY `code|document|paper|image` —
never emit `file_type:"rationale"` or `file_type:"concept"`.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
Chart: metric, trend/insight, data source.
@@ -233,16 +225,15 @@ Use sparingly — only when the group relationship adds information beyond the p
If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author,
contributor onto every node from that file.
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- AMBIGUOUS edges: 0.1-0.3
confidence_score rules:
- EXTRACTED edges: confidence_score must be 1.0
- INFERRED edges: score 0.4-0.9 based on how certain you are.
Strong structural inference (e.g. two classes clearly share data): 0.8-0.9.
Reasonable but not certain: 0.6-0.7. Weak inference: 0.4-0.5.
- AMBIGUOUS edges: score 0.1-0.3
Output exactly this JSON (no other text):
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|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}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
```
**Step B3 - Collect, cache, and merge**
@@ -255,29 +246,28 @@ If more than half the chunks failed, stop and tell the user.
Save new results to cache:
```bash
$(cat .graphify_python) -c "
python3 -c "
import json
from graphify.cache import save_semantic_cache
from pathlib import Path
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[]}
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []))
print(f'Cached {saved} files')
"
```
Merge cached + new results into `.graphify_semantic.json`:
```bash
$(cat .graphify_python) -c "
python3 -c "
import json
from pathlib import Path
cached = json.loads(Path('.graphify_cached.json').read_text()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
cached = json.loads(Path('.graphify_cached.json').read_text()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[]}
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[]}
all_nodes = cached['nodes'] + new.get('nodes', [])
all_edges = cached['edges'] + new.get('edges', [])
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
seen = set()
deduped = []
for n in all_nodes:
@@ -288,7 +278,6 @@ for n in all_nodes:
merged = {
'nodes': deduped,
'edges': all_edges,
'hyperedges': all_hyperedges,
'input_tokens': new.get('input_tokens', 0),
'output_tokens': new.get('output_tokens', 0),
}
@@ -301,7 +290,7 @@ Clean up temp files: `rm -f .graphify_cached.json .graphify_uncached.txt .graphi
#### Part C - Merge AST + semantic into final extraction
```bash
$(cat .graphify_python) -c "
python3 -c "
import sys, json
from pathlib import Path
@@ -317,11 +306,9 @@ for n in sem['nodes']:
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),
}
@@ -336,7 +323,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
```bash
mkdir -p graphify-out
$(cat .graphify_python) -c "
python3 -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
@@ -389,7 +376,7 @@ Read `.graphify_analysis.json`. For each community key, look at its node labels
Then regenerate the report and save the labels for the visualizer:
```bash
$(cat .graphify_python) -c "
python3 -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import score_all
@@ -422,14 +409,12 @@ print('Report updated with community labels')
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
### Step 6 - Generate Obsidian vault (default) + optional 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:
**Always generate the Obsidian vault and HTML** - they are the primary visualizations. Skip both if `--no-viz` (report + JSON only).
```bash
$(cat .graphify_python) -c "
python3 -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_obsidian, to_canvas
@@ -457,10 +442,10 @@ print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries
"
```
Generate the HTML graph (always, unless `--no-viz`):
Also generate the HTML graph (always, unless `--no-viz`):
```bash
$(cat .graphify_python) -c "
python3 -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_html
@@ -487,7 +472,7 @@ else:
**If `--neo4j`** - generate a Cypher file for manual import:
```bash
$(cat .graphify_python) -c "
python3 -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_cypher
@@ -502,7 +487,7 @@ print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt'
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
```bash
$(cat .graphify_python) -c "
python3 -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster
@@ -524,7 +509,7 @@ Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default
### Step 7b - SVG export (only if --svg flag)
```bash
$(cat .graphify_python) -c "
python3 -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_svg
@@ -546,7 +531,7 @@ print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
### Step 7c - GraphML export (only if --graphml flag)
```bash
$(cat .graphify_python) -c "
python3 -c "
import json
from graphify.build import build_from_json
from graphify.export import to_graphml
@@ -588,7 +573,7 @@ To configure in Claude Desktop, add to `claude_desktop_config.json`:
If `total_words` from `.graphify_detect.json` is greater than 5,000, run:
```bash
$(cat .graphify_python) -c "
python3 -c "
import json
from graphify.benchmark import run_benchmark, print_benchmark
from pathlib import Path
@@ -606,7 +591,7 @@ Print the output directly in chat. If `total_words <= 5000`, skip silently - the
### Step 9 - Save manifest, update cost tracker, clean up, and report
```bash
$(cat .graphify_python) -c "
python3 -c "
import json
from pathlib import Path
from datetime import datetime, timezone
@@ -640,18 +625,26 @@ cost_path.write_text(json.dumps(cost, indent=2))
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_python
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Tell the user (omit the obsidian line unless --obsidian was given):
Tell the user:
```
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
Graph complete. Outputs are in a hidden folder called graphify-out/ inside the directory you ran this on.
graph.html - interactive graph, open in browser
GRAPH_REPORT.md - audit report
graph.json - raw graph data
obsidian/ - Obsidian vault (only if --obsidian was given)
The folder is hidden (dot prefix) so it won't show in Finder or a normal ls.
To see it:
Mac/Linux: ls -la graphify-out/
VS Code: the Explorer panel shows hidden files by default
Finder: Cmd+Shift+. to toggle hidden files
What's inside:
graphify-out/obsidian/ - open this folder as a vault in Obsidian (File > Open Vault)
graphify-out/GRAPH_REPORT.md - full audit report, also readable here in Claude
graphify-out/graph.json - persistent graph, query it later with /graphify query "..."
Full path: PATH_TO_DIR/graphify-out/
```
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
@@ -678,7 +671,7 @@ The graph is the map. Your job after the pipeline is to be the guide.
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
```bash
$(cat .graphify_python) -c "
python3 -c "
import sys, json
from graphify.detect import detect_incremental, save_manifest
from pathlib import Path
@@ -697,7 +690,7 @@ print(f'{new_total} new/changed file(s) to re-extract.')
If new files exist, first check whether all changed files are code files:
```bash
$(cat .graphify_python) -c "
python3 -c "
import json
from pathlib import Path
@@ -717,7 +710,7 @@ If `code_only` is False (any changed file is a doc/paper/image): run the full St
Then:
```bash
$(cat .graphify_python) -c "
python3 -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_json
@@ -744,7 +737,7 @@ Then run Steps 4–8 on the merged graph as normal.
After Step 4, show the graph diff:
```bash
$(cat .graphify_python) -c "
python3 -c "
import json
from graphify.analyze import graph_diff
from graphify.build import build_from_json
@@ -778,7 +771,7 @@ Clean up after: `rm -f .graphify_old.json`
Skip Steps 1–3. Load the existing graph from `graphify-out/graph.json` and re-run clustering:
```bash
$(cat .graphify_python) -c "
python3 -c "
import sys, json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections
@@ -831,7 +824,7 @@ Two traversal modes - choose based on the question:
First check the graph exists:
```bash
$(cat .graphify_python) -c "
python3 -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
@@ -849,7 +842,7 @@ Load `graphify-out/graph.json`, then:
5. If the graph lacks enough information, say so - do not hallucinate edges.
```bash
$(cat .graphify_python) -c "
python3 -c "
import sys, json
from networkx.readwrite import json_graph
import networkx as nx
@@ -940,7 +933,7 @@ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`,
After writing the answer, save it back into the graph so it improves future queries:
```bash
$(cat .graphify_python) -c "
python3 -c "
from graphify.ingest import save_query_result
from pathlib import Path
save_query_result(
@@ -964,7 +957,7 @@ Find the shortest path between two named concepts in the graph.
First check the graph exists:
```bash
$(cat .graphify_python) -c "
python3 -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
@@ -974,7 +967,7 @@ if not Path('graphify-out/graph.json').exists():
If it fails, stop and tell the user to run `/graphify <path>` first.
```bash
$(cat .graphify_python) -c "
python3 -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
@@ -1026,7 +1019,7 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
After writing the explanation, save it back:
```bash
$(cat .graphify_python) -c "
python3 -c "
from graphify.ingest import save_query_result
from pathlib import Path
save_query_result(
@@ -1048,7 +1041,7 @@ Give a plain-language explanation of a single node - everything connected to it.
First check the graph exists:
```bash
$(cat .graphify_python) -c "
python3 -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
@@ -1058,7 +1051,7 @@ if not Path('graphify-out/graph.json').exists():
If it fails, stop and tell the user to run `/graphify <path>` first.
```bash
$(cat .graphify_python) -c "
python3 -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
@@ -1103,7 +1096,7 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
After writing the explanation, save it back:
```bash
$(cat .graphify_python) -c "
python3 -c "
from graphify.ingest import save_query_result
from pathlib import Path
save_query_result(
@@ -1124,7 +1117,7 @@ print('Explanation saved to graphify-out/memory/')
Fetch a URL and add it to the corpus, then update the graph.
```bash
$(cat .graphify_python) -c "
python3 -c "
import sys
from graphify.ingest import ingest
from pathlib import Path
+1
View File
@@ -23,6 +23,7 @@ def _rebuild_code(watch_path: Path) -> bool:
Returns True on success, False on error.
"""
watch_path = Path(watch_path).resolve()
try:
from graphify.extract import collect_files, extract
from graphify.build import build_from_json
+3 -3
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.2.2"
version = "0.1.14"
description = "Claude Code skill - turn any folder of code, docs, papers, images, or tweets into a queryable knowledge graph"
readme = "README.md"
license = { text = "MIT" }
@@ -12,6 +12,7 @@ keywords = ["claude", "claude-code", "knowledge-graph", "rag", "graphrag", "obsi
requires-python = ">=3.10"
dependencies = [
"networkx",
"graspologic",
"tree-sitter",
"tree-sitter-python",
"tree-sitter-javascript",
@@ -38,8 +39,7 @@ mcp = ["mcp"]
neo4j = ["neo4j"]
pdf = ["pypdf", "html2text"]
watch = ["watchdog"]
leiden = ["graspologic"]
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic"]
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog"]
[project.scripts]
graphify = "graphify.__main__:main"
-39
View File
@@ -95,42 +95,3 @@ def test_uninstall_no_op_when_no_file(tmp_path, capsys):
claude_uninstall(tmp_path)
out = capsys.readouterr().out
assert "No CLAUDE.md" in out or "nothing to do" in out
# ---------------------------------------------------------------------------
# settings.json PreToolUse hook
# ---------------------------------------------------------------------------
def test_install_creates_settings_json(tmp_path):
"""claude_install also writes .claude/settings.json with PreToolUse hook."""
import json
claude_install(tmp_path)
settings_path = tmp_path / ".claude" / "settings.json"
assert settings_path.exists()
settings = json.loads(settings_path.read_text())
hooks = settings.get("hooks", {}).get("PreToolUse", [])
assert any("Glob|Grep" in h.get("matcher", "") for h in hooks)
def test_install_settings_json_idempotent(tmp_path):
"""Running claude_install twice does not duplicate the PreToolUse hook."""
import json
claude_install(tmp_path)
claude_install(tmp_path)
settings_path = tmp_path / ".claude" / "settings.json"
settings = json.loads(settings_path.read_text())
hooks = settings.get("hooks", {}).get("PreToolUse", [])
glob_grep_hooks = [h for h in hooks if "Glob|Grep" in h.get("matcher", "")]
assert len(glob_grep_hooks) == 1
def test_uninstall_removes_settings_hook(tmp_path):
"""claude_uninstall removes the PreToolUse hook from settings.json."""
import json
claude_install(tmp_path)
claude_uninstall(tmp_path)
settings_path = tmp_path / ".claude" / "settings.json"
if settings_path.exists():
settings = json.loads(settings_path.read_text())
hooks = settings.get("hooks", {}).get("PreToolUse", [])
assert not any("Glob|Grep" in h.get("matcher", "") for h in hooks)
+2 -34
View File
@@ -2,7 +2,7 @@
import subprocess
from pathlib import Path
import pytest
from graphify.hooks import install, uninstall, status, _HOOK_MARKER, _CHECKOUT_MARKER
from graphify.hooks import install, uninstall, status, _HOOK_MARKER
def _make_git_repo(tmp_path: Path) -> Path:
@@ -53,7 +53,7 @@ def test_uninstall_removes_hook(tmp_path):
result = uninstall(repo)
hook = repo / ".git" / "hooks" / "post-commit"
assert not hook.exists()
assert "removed" in result.lower()
assert "Removed" in result
def test_uninstall_no_hook(tmp_path):
@@ -78,35 +78,3 @@ def test_status_not_installed(tmp_path):
def test_no_git_repo_raises(tmp_path):
with pytest.raises(RuntimeError, match="No git repository"):
install(tmp_path / "not_a_repo")
def test_install_creates_post_checkout_hook(tmp_path):
repo = _make_git_repo(tmp_path)
install(repo)
hook = repo / ".git" / "hooks" / "post-checkout"
assert hook.exists()
assert _CHECKOUT_MARKER in hook.read_text()
def test_install_post_checkout_is_executable(tmp_path):
repo = _make_git_repo(tmp_path)
install(repo)
hook = repo / ".git" / "hooks" / "post-checkout"
assert hook.stat().st_mode & 0o111
def test_uninstall_removes_post_checkout_hook(tmp_path):
repo = _make_git_repo(tmp_path)
install(repo)
uninstall(repo)
hook = repo / ".git" / "hooks" / "post-checkout"
assert not hook.exists()
def test_status_shows_both_hooks(tmp_path):
repo = _make_git_repo(tmp_path)
install(repo)
result = status(repo)
assert "post-commit" in result
assert "post-checkout" in result
assert result.count("installed") >= 2
-89
View File
@@ -1,89 +0,0 @@
"""Tests for rationale/docstring extraction in extract.py."""
import textwrap
from pathlib import Path
import pytest
from graphify.extract import extract_python
def _write_py(tmp_path: Path, code: str) -> Path:
p = tmp_path / "sample.py"
p.write_text(textwrap.dedent(code))
return p
def test_module_docstring_extracted(tmp_path):
path = _write_py(tmp_path, '''
"""This module handles authentication because legacy sessions were insecure."""
def login(): pass
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
assert len(rationale) >= 1
assert any("authentication" in n["label"] for n in rationale)
def test_function_docstring_extracted(tmp_path):
path = _write_py(tmp_path, '''
def process():
"""We use chunked processing here because the full dataset exceeds RAM."""
pass
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
assert any("chunked" in n["label"] for n in rationale)
def test_class_docstring_extracted(tmp_path):
path = _write_py(tmp_path, '''
class Cache:
"""Chosen over Redis because we need zero external dependencies in the test env."""
pass
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
assert any("Redis" in n["label"] for n in rationale)
def test_rationale_comment_extracted(tmp_path):
path = _write_py(tmp_path, '''
def build():
# NOTE: must run before compile() or linker will fail
pass
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
assert any("NOTE" in n["label"] for n in rationale)
def test_rationale_for_edges_present(tmp_path):
path = _write_py(tmp_path, '''
"""Module docstring explaining the why."""
def foo():
"""Function docstring with rationale."""
pass
''')
result = extract_python(path)
rationale_edges = [e for e in result["edges"] if e.get("relation") == "rationale_for"]
assert len(rationale_edges) >= 1
def test_short_docstring_ignored(tmp_path):
"""Trivial docstrings under 20 chars should not become rationale nodes."""
path = _write_py(tmp_path, '''
def foo():
"""Constructor."""
pass
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
assert len(rationale) == 0
def test_rationale_confidence_is_extracted(tmp_path):
path = _write_py(tmp_path, '''
"""This module exists because we needed a standalone parser."""
def parse(): pass
''')
result = extract_python(path)
rationale_edges = [e for e in result["edges"] if e.get("relation") == "rationale_for"]
assert all(e.get("confidence") == "EXTRACTED" for e in rationale_edges)