Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b938ef0df1 | ||
|
|
387f92d4df |
No files matched your search
@@ -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:
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# graphify
|
||||
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://pypi.org/project/graphifyy/)
|
||||
[](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.
|
||||
|
||||
@@ -21,12 +20,6 @@ graphify-out/
|
||||
└── 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+
|
||||
@@ -43,30 +36,12 @@ 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
|
||||
```
|
||||
|
||||
@@ -103,14 +78,14 @@ When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"`
|
||||
/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 claude install # write graphify rules to local CLAUDE.md + install PreToolUse hook
|
||||
```
|
||||
|
||||
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 |
|
||||
| Code | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php` | AST via tree-sitter + call-graph pass + docstring/comment rationale |
|
||||
| Docs | `.md .txt .rst` | Concepts + relationships + design rationale via Claude |
|
||||
| Papers | `.pdf` | Citation mining + concept extraction |
|
||||
| Images | `.png .jpg .webp .gif` | Claude vision - screenshots, diagrams, any language |
|
||||
@@ -127,7 +102,7 @@ Works with any mix of file types:
|
||||
|
||||
**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.
|
||||
**Semantic similarity edges** - cross-file conceptual links that have 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.
|
||||
|
||||
@@ -137,8 +112,12 @@ Works with any mix of file types:
|
||||
|
||||
**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.
|
||||
|
||||
**Always-on for Claude** (`graphify claude install`) - writes a `CLAUDE.md` section so Claude checks the graph before answering architecture questions, plus a `.claude/settings.json` PreToolUse hook that fires before every Glob/Grep - Claude is reminded to check the graph before searching raw files.
|
||||
|
||||
**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 +128,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.
|
||||
|
||||
@@ -171,11 +171,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
|
||||
|
||||
print(f"graphify section removed from {target.resolve()}")
|
||||
_uninstall_claude_hook(project_dir or Path("."))
|
||||
|
||||
|
||||
|
||||
+7
-20
@@ -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:
|
||||
|
||||
+50
-55
@@ -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
|
||||
@@ -255,7 +244,7 @@ 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
|
||||
@@ -268,7 +257,7 @@ 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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -336,7 +325,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 +378,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 +411,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:
|
||||
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was given** — it generates one file per node which creates thousands of files in large repos. Skip it by default.
|
||||
|
||||
```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 +444,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 +474,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 +489,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 +511,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 +533,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 +575,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 +593,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 +627,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 +673,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 +692,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 +712,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 +739,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 +773,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 +826,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 +844,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 +935,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 +959,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 +969,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 +1021,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 +1043,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 +1053,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 +1098,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 +1119,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
|
||||
|
||||
+3
-3
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "graphifyy"
|
||||
version = "0.2.2"
|
||||
version = "0.2.0"
|
||||
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"
|
||||
|
||||
@@ -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)
|
||||
+1
-33
@@ -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:
|
||||
@@ -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
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user