Compare commits

..
57 Commits
Author SHA1 Message Date
Safi 3d5da6039a Add Elixir language support (.ex/.exs)
Extracts defmodule, def/defp, alias/import/require/use, and call graph.
Follows same custom-walk pattern as Zig and PowerShell extractors.
2026-04-07 12:54:12 +01:00
Safi f6dd049cb0 Add .docx and .xlsx support via optional [office] extra
python-docx converts .docx to markdown (headings, lists, tables).
openpyxl converts .xlsx sheets to markdown tables. Both are
pre-converted to .md sidecars in graphify-out/converted/ before
semantic extraction - no skill changes needed. Graceful fallback
if [office] not installed: file is skipped with an install hint.
2026-04-07 12:38:03 +01:00
Safi a06313a0f9 Fix UnicodeDecodeError on Windows GBK locale: add encoding=utf-8 to all read_text/write_text calls 2026-04-07 11:54:54 +01:00
Safi db2d297296 Add Windows support: skill-windows.md with PowerShell-compatible commands
graphify install now auto-detects Windows and installs the Windows skill
variant. skill-windows.md replaces bash-specific commands (which, head, tr,
rm -f, mkdir -p) with PowerShell equivalents. Bumps to v0.3.3.
2026-04-07 11:30:08 +01:00
Safi abd55cca9a Add GitHub Sponsors badge to README 2026-04-07 10:50:59 +01:00
Safi e5e93c8180 Add GitHub Sponsors funding config 2026-04-07 10:46:36 +01:00
Safi 1a109afdce Add star history chart to README 2026-04-07 10:33:31 +01:00
Safi d7230a24c3 bump version to 0.3.2 2026-04-07 09:59:01 +01:00
Safi 9d998cc810 Add Zig and PowerShell language support 2026-04-07 09:56:53 +01:00
Safi f2423bc114 Add .graphifyignore support for excluding files and directories 2026-04-07 09:41:01 +01:00
Safi b079c6713a Add Factory Droid platform support 2026-04-07 09:34:28 +01:00
Safi 8c1d5e8114 Update SECURITY.md: supported versions, SSRF and YAML injection mitigations 2026-04-06 22:38:02 +01:00
Safi 808cd98395 Fix YAML injection in webpage title and query frontmatter 2026-04-06 22:35:19 +01:00
Safi e7bd4f38ee bump version to 0.3.1 2026-04-06 22:24:21 +01:00
Safi c529e2217f Fix 8 bugs: SSRF in tweet fetch, Cypher injection, XSS in community labels, graph_diff edge ordering, cache key collision, hook uninstall correctness, watch mode set, rebuild word count 2026-04-06 22:23:55 +01:00
Safi 4e844ea907 Update README: git hook failure behavior 2026-04-06 22:23:55 +01:00
Safi 148e247662 Fix 6 bugs: hook exit code, token budget, file node detection, duplicate function, atomic cache writes, deleted file tracking 2026-04-06 22:23:55 +01:00
Safi 9eda1558c2 feat: Lua language support 2026-04-06 21:59:38 +01:00
Safi 79b8d8d9b2 docs: add Simplified Chinese README
Add a Chinese README translation and link it from the main README for easier language discovery.
2026-04-06 21:59:38 +01:00
Safi 477465ae0d feat: Swift language support
* feat: add Swift language support

Add tree-sitter-swift extractor for classes, structs, protocols,
functions, imports, and call graph edges. Includes 8 passing tests.

* feat: full Swift AST support — enums, extensions, actors, conformance

- Enums: extract enum types, methods, and cases (case_of edges)
- Extensions: methods attach to the original type (no duplicate nodes)
- Actors: recognized via unified class_declaration node type
- Conformance/inheritance: inherits edges from : Protocol syntax
- deinit/subscript: name resolution for nameless declarations
- 12 new tests (110 total, all passing)
2026-04-06 21:59:38 +01:00
Safi 404674a24a security: SSRF private IP blocking and Neo4j Cypher injection fix
Two targeted security hardening changes:

1. SSRF: validate_url() now resolves hostnames and blocks private/reserved
   IP ranges (127.x, 10.x, 169.254.x, etc.) and cloud metadata endpoints.
   Prevents SSRF attacks in cloud environments where a URL like
   http://169.254.169.254/latest/meta-data/ could leak instance credentials.

2. Neo4j Cypher injection: Node labels (file_type) are now sanitized to
   alphanumeric + underscore before interpolation into Cypher queries.
   Previously, attacker-controlled file_type metadata could inject
   arbitrary Cypher in team/shared graph scenarios.

Both changes are zero-impact on normal UX - no new config, no new flags,
no behavioral changes for legitimate use.
2026-04-06 21:59:38 +01:00
Safi 934957cbfd update worked example READMEs for v3 multi-platform 2026-04-06 16:20:13 +01:00
Safi e11d04f8c2 explain always-on vs explicit trigger in README 2026-04-06 16:15:51 +01:00
Safi 1a54f16b80 feat: always-on hooks and README updates for all platforms 2026-04-06 16:06:31 +01:00
Safi aed4a981a1 v3: MIT license, multi-platform packaging and CI 2026-04-06 16:06:31 +01:00
Safi 3694822040 document node deduplication strategy in build.py 2026-04-06 16:06:31 +01:00
Safi 5461feb7e8 refactor extract.py: LanguageConfig + _extract_generic replaces 10 copy-pasted extractors (2527 → 1588 lines) 2026-04-06 16:06:31 +01:00
Safi 6570488658 fix build() dropping hyperedges when merging multiple extractions 2026-04-06 16:06:31 +01:00
Safi 38d967fc63 feat: multi-platform skill files and install routing (Codex, OpenCode, OpenClaw) 2026-04-06 16:06:31 +01:00
Safi 07de9d5c22 fix: use correct Python interpreter for pipx installs 2026-04-06 16:06:31 +01:00
Safi c1bf6c90dc fix graspologic optional, fall back to networkx louvain, add privacy section 2026-04-06 16:06:31 +01:00
Safi 4ba8198c7c v2.1: PyPI release and CI for v2 branch 2026-04-06 16:06:31 +01:00
Safi c46a4ebb68 README: fix CI badge to v2, update curl URL, add how it works, graphify claude install section 2026-04-06 16:06:31 +01:00
Safi 0ee77c0b6a bump version to 0.2.0 2026-04-06 16:06:31 +01:00
Safi 317d73f8f7 v2: confidence scores, hyperedges, rationale extraction, git hooks, Claude Code hooks
- confidence_score required on every edge (INFERRED: 0.4-0.9, EXTRACTED: 1.0, AMBIGUOUS: 0.1-0.3)
- semantically_similar_to edges for non-obvious cross-file conceptual links
- hyperedges for 3+ node group relationships - fixed cache and merge pipeline that was silently dropping them
- check_semantic_cache returns 4-tuple including cached_hyperedges
- extract.py: mine the "why" - module/class/function docstrings and rationale comments (# NOTE: # IMPORTANT: # HACK: # WHY: # RATIONALE: # TODO: # FIXME:) as rationale_for nodes
- skill.md: rationale_for in relation schema, doc files extract design rationale
- obsidian output opt-in (--obsidian flag) - default output is graph.html + graph.json + GRAPH_REPORT.md only
- hooks.py: post-checkout hook added alongside post-commit - graph rebuilds on branch switch
- claude install: writes .claude/settings.json PreToolUse hook on Glob/Grep - Claude checks graph before searching raw files
- README updated with all v2 features
2026-04-06 16:06:31 +01:00
Safi 3f8169c807 README: highlight multimodal capability upfront 2026-04-06 16:06:31 +01:00
Safi 3a117c93e8 v2: hypergraph support - hyperedges in graph.json, shaded regions in HTML, report section 2026-04-06 16:06:31 +01:00
Safi 6fa4c7e662 v2: semantic similarity edges, scored higher in surprising connections 2026-04-06 16:06:31 +01:00
Safi dafe6c9f03 v2: confidence scores on INFERRED edges, avg shown in report 2026-04-06 16:06:31 +01:00
Safi 7e3da961a9 v2: fast --update for code-only changes, parallel AST+semantic, graphify claude install 2026-04-06 16:06:31 +01:00
Safi 63d80200c5 README: clarify any folder works, clean up usage section 2026-04-06 16:06:31 +01:00
Safi 66f1f40de8 add git commit hook - auto-rebuilds graph after every commit 2026-04-06 16:06:31 +01:00
Safi e2fd4f944e watch: auto-rebuild graph on code changes without LLM, notify on doc/image changes 2026-04-06 16:06:31 +01:00
Safi 21e443e201 Add reproducible worked example with 7 input files and README 2026-04-06 16:06:31 +01:00
Safi d213c03adf Add --wiki export: agent-crawlable knowledge wiki from graph 2026-04-06 16:06:31 +01:00
Safi 92ab83ea38 Use graph.json for follow-up questions; bump to 0.1.6 2026-04-06 16:06:31 +01:00
Safi cb4ec5d39d fix: HTML always generated by default in Step 6, not flag-gated 2026-04-06 16:06:31 +01:00
Safi 010583674e release: 0.1.5 2026-04-06 16:06:31 +01:00
Safi d8b1e82079 fix: 5 skill gaps - graphml usage, manifest timing, graph existence checks, no-viz clarity
- Add --graphml to Usage table (was implemented but undocumented there)
- Remove early manifest save from --update merge step (Step 9 owns it; saving early meant failed pipelines left manifest ahead of graph)
- query/path/explain now check graph.json exists before running, with clear "run /graphify first" message
- --no-viz: clarify it skips both Obsidian vault and HTML (was contradictory)
2026-04-06 16:06:31 +01:00
Safi ef8c2fef50 perf: larger chunks + code-only fast path + timing estimates
- Semantic extraction chunks: 12-15 → 20-25 files (fewer subagent round trips)
- Code-only corpora skip semantic dispatch entirely (AST covers it)
- Print estimated time before extraction so the wait feels intentional
2026-04-06 16:06:31 +01:00
Safi 0f4de8e47f test: add end-to-end pipeline integration test
Covers detect → extract → build → cluster → analyze → report → export
using existing fixtures. AST-only (no LLM calls), catches regressions
in how modules connect, not just individual module behaviour.
2026-04-06 16:06:31 +01:00
Safi 5efcf114ee fix critical install bug, add --graphml to pipeline, update changelog 2026-04-06 16:06:31 +01:00
Safi d4b24d8609 feat: vis.js HTML graph, token reduction benchmark, repo cleanup
- Replace pyvis with custom vis.js renderer: node size by degree,
  click-to-inspect panel with clickable neighbors, search box,
  community filter, physics clustering by community
- HTML graph generated by default on every run (no --html flag needed)
- Token reduction benchmark auto-runs after every /graphify on corpora >5k words
- Fix 292 edge warnings: silently skip stdlib/external edges in build.py
- Fix build() to merge extractions before building (cross-extraction edges were dropped)
- Add 5 HTML renderer tests (223 total)
- Remove unnecessary files: lib/, tests/eval_attention.py, misplaced eval reports
- Add graphify-out/ and .graphify_*.json to .gitignore
- Bump version to 0.1.4, remove pyvis dependency
- README: token reduction as top-level selling point, vis.js in tech stack,
  graph.html in output listing, correct test count and install command
2026-04-06 16:06:31 +01:00
Safi 5db8f7ce39 docs: update surprising connections description, test count
style: replace all em dashes with hyphens

fix: explain hidden .graphify/ folder in skill output and README

fix: rename .graphify/ to graphify-out/ so output is visible by default
2026-04-06 16:06:31 +01:00
Safi 693d2ba991 feat: composite surprise score — cross-type, cross-repo, community distance, peripheral→hub 2026-04-06 16:06:31 +01:00
Safi 7e82212304 feat: GraphML export (--graphml flag) for Gephi and yEd 2026-04-06 16:06:31 +01:00
Safi 64e07abd98 docs: CI, architecture guide, worked examples, README fixes
- Add GitHub Actions CI workflow (Python 3.10 and 3.12)
- Add CI badge to README
- Add ARCHITECTURE.md: pipeline overview, module table, schema, how to
  add a language extractor, security summary
- Move eval reports from tests/ to worked/httpx/ and worked/mixed-corpus/
- Fix README: test count 163→212, language table (13 languages via
  tree-sitter), extract.py description, worked examples links

benchmark: 8.8x token reduction on nanoGPT + minGPT + micrograd

- Run AST extraction on 29 Python files across 3 Karpathy repos
- 177 nodes, 246 edges, 17 communities (Leiden)
- 8.8x avg token reduction vs naive full-corpus context stuffing
- Notable: micrograd cleanly splits into engine/nn communities;
  nanoGPT model vs training loop correctly separated
- Honest: stdlib import noise flagged, config isolates documented

benchmark: 71.5x token reduction on mixed corpus (code+papers+images)

Full run: nanoGPT+minGPT+micrograd + 5 research papers + 4 images
285 nodes, 340 edges, 53 communities
Average BFS query: 1,726 tokens vs 123,488 naive (71.5x)
Code-only (AST) sub-benchmark: 8.8x on 13k-word corpus
2026-04-06 16:06:31 +01:00
43 changed files with 8260 additions and 2155 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
github: safishamsi
+2 -2
View File
@@ -2,9 +2,9 @@ name: CI
on:
push:
branches: ["v1", "main"]
branches: ["v1", "v2", "v3", "main"]
pull_request:
branches: ["v1", "main"]
branches: ["v1", "v2", "v3", "main"]
jobs:
test:
+4
View File
@@ -15,3 +15,7 @@ build/
.graphify/
graphify-out/
.graphify_*.json
.graphify_python
.claude/
skills/
docs/superpowers/
+23
View File
@@ -1,5 +1,28 @@
# Changelog
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
## 0.3.0 (2026-04-06)
- Add: multi-platform support — Codex (`skill-codex.md`), OpenCode (`skill-opencode.md`), OpenClaw (`skill-claw.md`)
- Add: `graphify install --platform <codex|opencode|claw>` routes skill to correct config directory
- Add: `graphify codex install` / `opencode install` / `claw install` — writes AGENTS.md for always-on graph-first behaviour
- Add: `graphify claude uninstall` / `codex uninstall` / `opencode uninstall` / `claw uninstall`
- Add: MIT license
- Fix: `build()` was silently dropping hyperedges when merging multiple extractions
- Refactor: `extract.py` 2527 → 1588 lines — replaced 12 copy-pasted language extractors with `LanguageConfig` dataclass + `_extract_generic()`
- Docs: clustering is graph-topology-based (no embeddings) — explained in README
- Docs: all missing flags documented (`--cluster-only`, `--no-viz`, `--neo4j-push`, `query --dfs`, `query --budget`, `add --author`, `add --contributor`)
## 0.2.2 (2026-04-06)
- Add: `graphify claude install` — writes graphify section to local CLAUDE.md + PreToolUse hook in `.claude/settings.json`
- Add: `graphify claude uninstall` — removes section and hook
- Add: `graphify hook install` — installs post-commit and post-checkout git hooks (platform-agnostic)
- Add: `graphify hook uninstall` / `hook status`
- Add: `graphify benchmark` CLI command
- Fix: node deduplication documented at all three layers
## 0.1.8 (2026-04-05)
- Fix: follow-up questions now check for wiki first (graphify-out/wiki/index.md) before falling back to graph.json
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Safi Shamsi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+110 -18
View File
@@ -1,8 +1,12 @@
# graphify
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v1)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[English](README.md) | [简体中文](README.zh-CN.md)
**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.
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
[![Sponsor](https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors)](https://github.com/sponsors/safishamsi)
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, OpenClaw, or Factory Droid - 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.
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.
@@ -15,16 +19,34 @@ 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
```
Add a `.graphifyignore` file to exclude folders you don't want in the graph:
```
# .graphifyignore
vendor/
node_modules/
dist/
*.generated.py
```
Same syntax as `.gitignore`. Patterns match against file paths relative to the folder you run graphify on.
## 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.
**Clustering is graph-topology-based — no embeddings.** Leiden finds communities by edge density. The semantic similarity edges that Claude extracts (`semantically_similar_to`, marked INFERRED) are already in the graph, so they influence community detection directly. The graph structure is the similarity signal — no separate embedding step or vector database needed.
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+
**Requires:** Python 3.10+ and one of: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [OpenClaw](https://openclaw.ai), or [Factory Droid](https://factory.ai)
```bash
pip install graphifyy && graphify install
@@ -32,21 +54,57 @@ 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.
### Platform support
Then open Claude Code in any directory and type:
| Platform | Install command |
|----------|----------------|
| Claude Code (Linux/Mac) | `graphify install` |
| Claude Code (Windows) | `graphify install` (auto-detected) or `graphify install --platform windows` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| OpenClaw | `graphify install --platform claw` |
| Factory Droid | `graphify install --platform droid` |
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw uses sequential extraction (parallel agent support is still early on that platform).
Then open your AI coding assistant and type:
```
/graphify .
```
### Make your assistant always use the graph (recommended)
After building a graph, run this once in your project:
| Platform | Command |
|----------|---------|
| Claude Code | `graphify claude install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| OpenClaw | `graphify claw install` |
| Factory Droid | `graphify droid install` |
**Claude Code** does two things: writes a `CLAUDE.md` section telling Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs a **PreToolUse hook** (`settings.json`) that fires 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."_ — so Claude navigates via the graph instead of grepping through every file.
**Codex, OpenCode, OpenClaw, Factory Droid** write the same rules to `AGENTS.md` in your project root. These platforms don't support PreToolUse hooks, so AGENTS.md is the always-on mechanism.
Uninstall with the matching uninstall command (e.g. `graphify claude uninstall`).
**Always-on vs explicit trigger — what's the difference?**
The always-on hook surfaces `GRAPH_REPORT.md` — a one-page summary of god nodes, communities, and surprising connections. Your assistant reads this before searching files, so it navigates by structure instead of keyword matching. That covers most everyday questions.
`/graphify query`, `/graphify path`, and `/graphify explain` go deeper: they traverse the raw `graph.json` hop by hop, trace exact paths between nodes, and surface edge-level detail (relation type, confidence score, source location). Use them when you want a specific question answered from the graph rather than a general orientation.
Think of it this way: the always-on hook gives your assistant a map. The `/graphify` commands let it navigate the map precisely.
<details>
<summary>Manual install (curl)</summary>
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v1/skills/graphify/skill.md \
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
```
@@ -66,11 +124,18 @@ 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 --cluster-only # rerun clustering on existing graph, no re-extraction
/graphify ./raw --no-viz # skip HTML, just produce report + JSON
/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
/graphify add https://... --author "Name" # tag the original author
/graphify add https://... --contributor "Name" # tag who added it to the corpus
/graphify query "what connects attention to the optimizer?"
/graphify query "what connects attention to the optimizer?" --dfs # trace a specific path
/graphify query "what connects attention to the optimizer?" --budget 1500 # cap at N tokens
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
@@ -79,17 +144,30 @@ When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"`
/graphify ./raw --svg # export graph.svg
/graphify ./raw --graphml # export graph.graphml (Gephi, yEd)
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
/graphify ./raw --neo4j-push bolt://localhost:7687 # push directly to a running Neo4j instance
/graphify ./raw --mcp # start MCP stdio server
graphify hook install # post-commit git hook - rebuilds graph on every commit automatically
# git hooks - platform-agnostic, rebuild graph on commit and branch switch
graphify hook install
graphify hook uninstall
graphify hook status
# always-on assistant instructions - platform-specific
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
graphify claude uninstall
graphify codex install # AGENTS.md (Codex)
graphify opencode install # AGENTS.md (OpenCode)
graphify claw install # AGENTS.md (OpenClaw)
graphify droid install # AGENTS.md (Factory Droid)
```
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 pass |
| Docs | `.md .txt .rst` | Concepts + relationships via Claude |
| Code | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1` | AST via tree-sitter + call-graph + docstring/comment rationale |
| Docs | `.md .txt .rst` | Concepts + relationships + design rationale via Claude |
| Office | `.docx .xlsx` | Converted to markdown then extracted via Claude (requires `pip install graphifyy[office]`) |
| Papers | `.pdf` | Citation mining + concept extraction |
| Images | `.png .jpg .webp .gif` | Claude vision - screenshots, diagrams, any language |
@@ -101,16 +179,22 @@ Works with any mix of file types:
**Suggested questions** - 4-5 questions the graph is uniquely positioned to answer
**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.
**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.
**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.
**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.
**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.
**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. The first run extracts and builds the graph (this costs tokens). Every subsequent query reads the compact graph instead of raw files — that's where the savings compound. The SHA256 cache means re-runs only re-process changed 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.
**Git hooks** (`graphify hook install`) - installs post-commit and post-checkout hooks. Graph rebuilds automatically after every commit and every branch switch. If a rebuild fails, the hook exits with a non-zero code so git surfaces the error instead of silently continuing. No background process needed.
**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 |
@@ -121,9 +205,17 @@ Every edge is tagged `EXTRACTED`, `INFERRED`, or `AMBIGUOUS` - you always know w
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 your AI coding assistant's underlying model API for semantic extraction of docs, papers, and images — Anthropic (Claude Code), OpenAI (Codex), or whichever provider your platform uses. 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 your platform's model API during extraction, using your own API key.
## Tech stack
NetworkX + Leiden (graspologic) + tree-sitter + Claude + vis.js. No Neo4j required, no server, runs entirely locally.
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantic extraction via Claude (Claude Code), GPT-4 (Codex), or whichever model your platform runs. No Neo4j required, no server, runs entirely locally.
## Star history
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
<details>
<summary>Contributing</summary>
+211
View File
@@ -0,0 +1,211 @@
# graphify
[English](README.md) | [简体中文](README.zh-CN.md)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
**一个面向 AI 编码助手的技能。** 在 Claude Code、Codex、OpenCode 或 OpenClaw 中输入 `/graphify`,它会读取你的文件、构建知识图谱,并把原本不明显的结构关系还给你。更快理解代码库,找到架构决策背后的“为什么”。
完全多模态。你可以直接丢进去代码、PDF、Markdown、截图、流程图、白板照片,甚至其他语言的图片 —— graphify 会用 Claude vision 从这些内容中提取概念和关系,并把它们连接到同一张图里。
> Andrej Karpathy 会维护一个 `/raw` 文件夹,把论文、推文、截图和笔记都丢进去。graphify 就是在解决这类问题 —— 相比直接读取原始文件,每次查询的 token 消耗可降低 **71.5 倍**,结果还能跨会话持久保存,并且会明确区分哪些内容是实际发现的,哪些只是合理推断。
```
/graphify . # 可用于任意目录:代码库、笔记、论文都可以
```
```
graphify-out/
├── graph.html 可交互图谱:可点节点、搜索、按社区过滤
├── GRAPH_REPORT.md God nodes、意外连接、建议提问
├── graph.json 持久化图谱:数周后仍可查询,无需重新读原始文件
└── cache/ SHA256 缓存:重复运行时只处理变更过的文件
```
## 工作原理
graphify 分两轮执行。第一轮是确定性的 AST 提取,对代码文件做结构分析(类、函数、导入、调用图、docstring、解释性注释),这一轮不需要 LLM。第二轮会并行调用 Claude 子代理处理文档、论文和图片,从中提取概念、关系和设计动机。最后把两边结果合并到一个 NetworkX 图里,用 Leiden 社区发现算法做聚类,并导出成可交互 HTML、可查询 JSON,以及一份人类可读的审计报告。
**聚类是基于图拓扑完成的,不依赖 embeddings。** Leiden 按边密度发现社区。Claude 抽取出的语义相似边(`semantically_similar_to`,标记为 `INFERRED`)本来就存在于图中,所以会直接影响社区划分。图结构本身就是相似性信号,不需要额外的 embedding 步骤,也不需要向量数据库。
每条关系都会被标记为 `EXTRACTED`(直接在源材料中找到)、`INFERRED`(合理推断,并附带置信度分数)或 `AMBIGUOUS`(有歧义,需要复核)。所以你始终知道哪些是实际发现的,哪些是模型猜出来的。
## 安装
**要求:** Python 3.10+,并且使用以下平台之一:[Claude Code](https://claude.ai/code)、[Codex](https://openai.com/codex)、[OpenCode](https://opencode.ai) 或 [OpenClaw](https://openclaw.ai)
```bash
pip install graphifyy && graphify install
```
> PyPI 包当前暂时叫 `graphifyy`,因为 `graphify` 这个名字还在回收中。CLI 命令和 skill 命令仍然都是 `graphify`。
### 平台支持
| 平台 | 安装命令 |
|------|----------|
| Claude Code | `graphify install` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| OpenClaw | `graphify install --platform claw` |
Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `multi_agent = true`,这样才能并行提取。OpenClaw 目前的并行 agent 支持还比较早期,所以使用顺序提取。
然后打开你的 AI 编码助手,输入:
```
/graphify .
```
### 让助手始终优先使用图谱(推荐)
图构建完成后,在项目里运行一次:
| 平台 | 命令 |
|------|------|
| Claude Code | `graphify claude install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| OpenClaw | `graphify claw install` |
**Claude Code** 会做两件事:
1. 在 `CLAUDE.md` 中写入一段规则,告诉 Claude 在回答架构问题前先读 `graphify-out/GRAPH_REPORT.md`
2. 安装一个 **PreToolUse hook**(写入 `settings.json`),在每次 `Glob` 和 `Grep` 前触发
如果知识图谱存在,Claude 会先看到:_"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ —— 这样 Claude 会优先按图谱导航,而不是一上来就 grep 整个项目。
**Codex、OpenCode、OpenClaw** 会把同样的规则写进项目根目录的 `AGENTS.md`。这些平台没有 PreToolUse hook,所以 `AGENTS.md` 是它们的常驻机制。
卸载时使用对应平台的 uninstall 命令即可(例如 `graphify claude uninstall`)。
**常驻模式和显式触发有什么区别?**
常驻 hook 会优先暴露 `GRAPH_REPORT.md` —— 这是一页式总结,包含 god nodes、社区结构和意外连接。你的助手在搜索文件前会先读它,因此会按结构导航,而不是按关键字乱搜。这已经能覆盖大部分日常问题。
`/graphify query`、`/graphify path` 和 `/graphify explain` 会更深入:它们会逐跳遍历底层 `graph.json`,追踪节点之间的精确路径,并展示边级别细节(关系类型、置信度、源位置)。当你想从图谱里精确回答某个问题,而不仅仅是获得整体感知时,就该用这些命令。
可以这样理解:常驻 hook 是先给助手一张地图,`/graphify` 这几个命令则是让它沿着地图精确导航。
<details>
<summary>手动安装(curl)</summary>
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
```
把下面内容加到 `~/.claude/CLAUDE.md`:
```
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
```
</details>
## 用法
```
/graphify # 对当前目录运行
/graphify ./raw # 对指定目录运行
/graphify ./raw --mode deep # 更激进地抽取 INFERRED 边
/graphify ./raw --update # 只重新提取变更文件,并合并到已有图谱
/graphify ./raw --cluster-only # 只重新聚类已有图谱,不重新提取
/graphify ./raw --no-viz # 跳过 HTML,只生成 report + JSON
/graphify ./raw --obsidian # 额外生成 Obsidian vault(可选)
/graphify add https://arxiv.org/abs/1706.03762 # 拉取论文、保存并更新图谱
/graphify add https://x.com/karpathy/status/... # 拉取推文
/graphify add https://... --author "Name" # 标记原作者
/graphify add https://... --contributor "Name" # 标记是谁把它加入语料库的
/graphify query "what connects attention to the optimizer?"
/graphify query "what connects attention to the optimizer?" --dfs # 追踪一条具体路径
/graphify query "what connects attention to the optimizer?" --budget 1500 # 把预算限制在 N tokens
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
/graphify ./raw --watch # 文件变更时自动同步图谱(代码:立即更新;文档:提醒你)
/graphify ./raw --wiki # 构建可供 agent 抓取的 wiki(index.md + 每个 community 一篇文章)
/graphify ./raw --svg # 导出 graph.svg
/graphify ./raw --graphml # 导出 graph.graphml(Gephi、yEd)
/graphify ./raw --neo4j # 生成给 Neo4j 用的 cypher.txt
/graphify ./raw --neo4j-push bolt://localhost:7687 # 直接推送到运行中的 Neo4j
/graphify ./raw --mcp # 启动 MCP stdio server
# git hooks - 跨平台,在 commit 和切分支后重建图谱
graphify hook install
graphify hook uninstall
graphify hook status
# 常驻助手规则 - 按平台区分
graphify claude install # CLAUDE.md + PreToolUse hook(Claude Code)
graphify claude uninstall
graphify codex install # AGENTS.md(Codex)
graphify opencode install # AGENTS.md(OpenCode)
graphify claw install # AGENTS.md(OpenClaw)
```
支持混合文件类型:
| 类型 | 扩展名 | 提取方式 |
|------|--------|----------|
| 代码 | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php` | tree-sitter AST + 调用图 + docstring / 注释中的 rationale |
| 文档 | `.md .txt .rst` | 通过 Claude 提取概念、关系和设计动机 |
| 论文 | `.pdf` | 引文挖掘 + 概念提取 |
| 图片 | `.png .jpg .webp .gif` | Claude vision —— 截图、图表、任意语言都可以 |
## 你会得到什么
**God nodes** —— 度最高的概念节点(整个系统最容易汇聚到的地方)
**意外连接** —— 按综合得分排序。代码-论文之间的边会比代码-代码边权重更高。每条结果都会附带一段人话解释。
**建议提问** —— 图谱特别擅长回答的 4 到 5 个问题。
**“为什么”** —— docstring、行内注释(`# NOTE:`、`# IMPORTANT:`、`# HACK:`、`# WHY:`)以及文档里的设计动机都会被抽取成 `rationale_for` 节点。不只是知道代码“做了什么”,还能知道“为什么要这么写”。
**置信度分数** —— 每条 `INFERRED` 边都有 `confidence_score`(0.0-1.0)。你不只知道哪些是猜出来的,还知道模型对这个猜测有多有把握。`EXTRACTED` 边恒为 1.0。
**语义相似边** —— 跨文件的概念连接,即使结构上没有直接依赖也能建立关联。比如两个函数做的是同一类问题但彼此没有调用,或者某个代码类和某篇论文里的算法概念本质相同。
**超边(Hyperedges)** —— 用来表达 3 个以上节点的群组关系,这是普通两两边表达不出来的。比如:一组类共同实现一个协议、认证链路里的一组函数、同一篇论文某一节里的多个概念共同组成一个想法。
**Token 基准** —— 每次运行后都会自动打印。对混合语料(Karpathy 的仓库 + 论文 + 图片),每次查询的 token 消耗可以比直接读原文件少 **71.5 倍**。第一次运行需要先提取并建图,这一步会花 token;后续查询直接读取压缩后的图谱,节省会越来越明显。SHA256 缓存保证重复运行时只重新处理变更文件。
**自动同步**(`--watch`)—— 在后台终端里跑着,代码库一变化,图谱就会跟着更新。代码文件保存会立刻触发重建(只走 AST,不用 LLM);文档/图片变更则会提醒你跑 `--update` 进行 LLM 再提取。
**Git hooks**(`graphify hook install`)—— 安装 `post-commit` 和 `post-checkout` hook。每次 commit 后、每次切分支后都会自动重建图谱,不需要额外开一个后台进程。
**Wiki**(`--wiki`)—— 为每个 community 和 god node 生成类似维基百科的 Markdown 文章,并提供 `index.md` 作为入口。任何 agent 只要读 `index.md`,就能通过普通文件导航整个知识库,而不必直接解析 JSON。
## Worked examples
| 语料 | 文件数 | 压缩比 | 输出 |
|------|--------|--------|------|
| Karpathy 的仓库 + 5 篇论文 + 4 张图片 | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
| graphify 源码 + Transformer 论文 | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
| httpx(合成 Python 库) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
Token 压缩效果会随着语料规模增大而更明显。6 个文件本来就塞得进上下文窗口,所以 graphify 在这种场景里的价值更多是结构清晰度,而不是 token 压缩。到了 52 个文件(代码 + 论文 + 图片)这种规模,就能做到 71x+。每个 `worked/` 目录里都带了原始输入和真实输出(`GRAPH_REPORT.md`、`graph.json`),你可以自己跑一遍核对数字。
## 隐私
graphify 会把文档、论文和图片的内容发送给你所用 AI 编码助手背后的模型 API 来做语义提取 —— 可能是 Anthropic(Claude Code)、OpenAI(Codex),或者你当前平台使用的其他提供方。代码文件则完全在本地通过 tree-sitter AST 处理,不会把代码内容发出去。项目本身没有任何遥测、使用跟踪或分析。唯一的网络请求就是语义提取阶段调用你平台自己的模型 API,使用的也是你自己的 API key。
## 技术栈
NetworkX + Leiden(graspologic)+ tree-sitter + vis.js。语义提取由 Claude(Claude Code)、GPT-4(Codex)或你当前平台所运行的模型完成。不需要 Neo4j,不需要 server,整体是纯本地运行。
<details>
<summary>贡献</summary>
**Worked examples** 是最能建立信任的贡献方式。对一个真实语料跑 `/graphify`,把输出保存到 `worked/{slug}/`,再写一份诚实的 `review.md`,评价图谱哪些地方做得对、哪些地方做得不对,然后提交 PR。
**提取 bug** —— 提 issue 时请附上输入文件、对应的缓存项(`graphify-out/cache/`)以及它漏提取或瞎编了什么。
模块职责和新增语言的方法见 [ARCHITECTURE.md](ARCHITECTURE.md)。
</details>
+4 -4
View File
@@ -4,8 +4,8 @@
| Version | Supported |
|---------|-----------|
| 0.1.x | Yes |
| < 0.1 | No |
| 0.3.x | Yes |
| < 0.3 | No |
## Reporting a Vulnerability
@@ -28,13 +28,13 @@ graphify is a **local development tool**. It runs as a Claude Code skill and opt
| Vector | Mitigation |
|--------|-----------|
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes. Redirect targets are re-validated by `_NoFileRedirectHandler` - a redirect to `file://` is blocked. |
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes, blocks private/loopback/link-local IPs, and blocks cloud metadata endpoints. Redirect targets are re-validated. All fetch paths including tweet oEmbed go through `safe_fetch()`. |
| Oversized downloads | `safe_fetch()` streams responses and aborts at 50 MB. `safe_fetch_text()` aborts at 10 MB. |
| Non-2xx HTTP responses | `safe_fetch()` raises `HTTPError` on non-2xx status codes - error pages are not silently treated as content. |
| Path traversal in MCP server | `security.validate_graph_path()` resolves paths and requires them to be inside `graphify-out/`. Also requires the `graphify-out/` directory to exist. |
| XSS in graph HTML output | `security.sanitize_label()` strips control characters, caps at 256 chars, and HTML-escapes all node labels and edge titles before pyvis embeds them. |
| Prompt injection via node labels | `sanitize_label()` also applied to MCP text output - node labels from user-controlled source files cannot break the text format returned to agents. |
| YAML frontmatter injection | Newlines stripped from user-provided strings before embedding in YAML frontmatter (e.g. in `save_query_result()`). |
| YAML frontmatter injection | `_yaml_str()` escapes backslashes, double quotes, and newlines before embedding user-controlled strings (webpage titles, query questions) in YAML frontmatter. |
| Encoding crashes on source files | All tree-sitter byte slices decoded with `errors="replace"` - non-UTF-8 source files degrade gracefully instead of crashing extraction. |
| Symlink traversal | `os.walk(..., followlinks=False)` is explicit throughout `detect.py`. |
| Corrupted graph.json | `_load_graph()` in `serve.py` wraps `json.JSONDecodeError` and prints a clear recovery message instead of crashing. |
+227 -74
View File
@@ -1,11 +1,26 @@
"""graphify CLI - `graphify install` sets up the Claude Code skill."""
from __future__ import annotations
import json
import platform
import re
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`) "
@@ -15,39 +30,76 @@ _SKILL_REGISTRATION = (
)
def _bundled_skill() -> Path:
"""Path to the skill.md bundled with this package."""
return Path(__file__).parent / "skill.md"
_PLATFORM_CONFIG: dict[str, dict] = {
"claude": {
"skill_file": "skill.md",
"skill_dst": Path(".claude") / "skills" / "graphify" / "SKILL.md",
"claude_md": True,
},
"codex": {
"skill_file": "skill-codex.md",
"skill_dst": Path(".agents") / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"opencode": {
"skill_file": "skill-opencode.md",
"skill_dst": Path(".config") / "opencode" / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"claw": {
"skill_file": "skill-claw.md",
"skill_dst": Path(".claw") / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"droid": {
"skill_file": "skill-droid.md",
"skill_dst": Path(".factory") / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"windows": {
"skill_file": "skill-windows.md",
"skill_dst": Path(".claude") / "skills" / "graphify" / "SKILL.md",
"claude_md": True,
},
}
def install() -> None:
skill_src = _bundled_skill()
if not skill_src.exists():
print("error: skill.md not found in package - reinstall graphify", file=sys.stderr)
def install(platform: str = "claude") -> None:
if platform not in _PLATFORM_CONFIG:
print(
f"error: unknown platform '{platform}'. Choose from: {', '.join(_PLATFORM_CONFIG)}",
file=sys.stderr,
)
sys.exit(1)
# Copy skill to ~/.claude/skills/graphify/SKILL.md
skill_dst = Path.home() / ".claude" / "skills" / "graphify" / "SKILL.md"
cfg = _PLATFORM_CONFIG[platform]
skill_src = Path(__file__).parent / cfg["skill_file"]
if not skill_src.exists():
print(f"error: {cfg['skill_file']} not found in package - reinstall graphify", file=sys.stderr)
sys.exit(1)
skill_dst = Path.home() / cfg["skill_dst"]
skill_dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(skill_src, skill_dst)
print(f" skill installed → {skill_dst}")
# Register in ~/.claude/CLAUDE.md
claude_md = Path.home() / ".claude" / "CLAUDE.md"
if claude_md.exists():
content = claude_md.read_text()
if "graphify" in content:
print(f" CLAUDE.md → already registered (no change)")
if cfg["claude_md"]:
# Register in ~/.claude/CLAUDE.md (Claude Code only)
claude_md = Path.home() / ".claude" / "CLAUDE.md"
if claude_md.exists():
content = claude_md.read_text(encoding="utf-8")
if "graphify" in content:
print(f" CLAUDE.md → already registered (no change)")
else:
claude_md.write_text(content.rstrip() + _SKILL_REGISTRATION, encoding="utf-8")
print(f" CLAUDE.md → skill registered in {claude_md}")
else:
claude_md.write_text(content.rstrip() + _SKILL_REGISTRATION)
print(f" CLAUDE.md → skill registered in {claude_md}")
else:
claude_md.parent.mkdir(parents=True, exist_ok=True)
claude_md.write_text(_SKILL_REGISTRATION.lstrip())
print(f" CLAUDE.md → created at {claude_md}")
claude_md.parent.mkdir(parents=True, exist_ok=True)
claude_md.write_text(_SKILL_REGISTRATION.lstrip(), encoding="utf-8")
print(f" CLAUDE.md → created at {claude_md}")
print()
print("Done. Open Claude Code in any directory and type:")
print("Done. Open your AI coding assistant and type:")
print()
print(" /graphify .")
print()
@@ -66,13 +118,78 @@ Rules:
_CLAUDE_MD_MARKER = "## graphify"
# AGENTS.md section for Codex, OpenCode, and OpenClaw.
# All three platforms read AGENTS.md in the project root for persistent instructions.
_AGENTS_MD_SECTION = """\
## graphify
This project has a graphify knowledge graph at graphify-out/.
Rules:
- 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 in this session, run `python3 -c "from graphify.watch import _rebuild_code; from pathlib import Path; _rebuild_code(Path('.'))"` to keep the graph current
"""
_AGENTS_MD_MARKER = "## graphify"
def _agents_install(project_dir: Path, platform: str) -> None:
"""Write the graphify section to the local AGENTS.md (Codex/OpenCode/OpenClaw)."""
target = (project_dir or Path(".")) / "AGENTS.md"
if target.exists():
content = target.read_text(encoding="utf-8")
if _AGENTS_MD_MARKER in content:
print(f"graphify already configured in AGENTS.md")
return
new_content = content.rstrip() + "\n\n" + _AGENTS_MD_SECTION
else:
new_content = _AGENTS_MD_SECTION
target.write_text(new_content, encoding="utf-8")
print(f"graphify section written to {target.resolve()}")
print()
print(f"{platform.capitalize()} will now check the knowledge graph before answering")
print("codebase questions and rebuild it after code changes.")
print()
print("Note: unlike Claude Code, there is no PreToolUse hook equivalent for")
print(f"{platform.capitalize()} — the AGENTS.md rules are the always-on mechanism.")
def _agents_uninstall(project_dir: Path) -> None:
"""Remove the graphify section from the local AGENTS.md."""
target = (project_dir or Path(".")) / "AGENTS.md"
if not target.exists():
print("No AGENTS.md found in current directory - nothing to do")
return
content = target.read_text(encoding="utf-8")
if _AGENTS_MD_MARKER not in content:
print("graphify section not found in AGENTS.md - nothing to do")
return
cleaned = re.sub(
r"\n*## graphify\n.*?(?=\n## |\Z)",
"",
content,
flags=re.DOTALL,
).rstrip()
if cleaned:
target.write_text(cleaned + "\n", encoding="utf-8")
print(f"graphify section removed from {target.resolve()}")
else:
target.unlink()
print(f"AGENTS.md was empty after removal - deleted {target.resolve()}")
def claude_install(project_dir: Path | None = None) -> None:
"""Write the graphify section to the local CLAUDE.md."""
target = (project_dir or Path(".")) / "CLAUDE.md"
if target.exists():
content = target.read_text()
content = target.read_text(encoding="utf-8")
if _CLAUDE_MD_MARKER in content:
print("graphify already configured in CLAUDE.md")
return
@@ -80,46 +197,59 @@ def claude_install(project_dir: Path | None = None) -> None:
else:
new_content = _CLAUDE_MD_SECTION
target.write_text(new_content)
target.write_text(new_content, encoding="utf-8")
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.")
_COPILOT_INSTRUCTIONS = """\
## graphify knowledge graph
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)
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)
if settings_path.exists():
try:
settings = json.loads(settings_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
settings = {}
else:
target.write_text(_COPILOT_INSTRUCTIONS)
settings = {}
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.")
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), encoding="utf-8")
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(encoding="utf-8"))
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), encoding="utf-8")
print(f" .claude/settings.json → PreToolUse hook removed")
def claude_uninstall(project_dir: Path | None = None) -> None:
@@ -130,7 +260,7 @@ def claude_uninstall(project_dir: Path | None = None) -> None:
print("No CLAUDE.md found in current directory - nothing to do")
return
content = target.read_text()
content = target.read_text(encoding="utf-8")
if _CLAUDE_MD_MARKER not in content:
print("graphify section not found in CLAUDE.md - nothing to do")
return
@@ -143,13 +273,13 @@ def claude_uninstall(project_dir: Path | None = None) -> None:
flags=re.DOTALL,
).rstrip()
if cleaned:
target.write_text(cleaned + "\n")
target.write_text(cleaned + "\n", encoding="utf-8")
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("."))
def main() -> None:
@@ -157,27 +287,41 @@ def main() -> None:
print("Usage: graphify <command>")
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(" install [--platform P] copy skill to platform config dir (claude|windows|codex|opencode|claw|droid)")
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")
print(" hook status check if hook is installed")
print(" claude install write graphify section to local CLAUDE.md")
print(" claude uninstall remove graphify section from local CLAUDE.md")
print(" hook install install post-commit/post-checkout git hooks (all platforms)")
print(" hook uninstall remove git hooks")
print(" hook status check if git hooks are installed")
print(" claude install write graphify section to CLAUDE.md + PreToolUse hook (Claude Code)")
print(" claude uninstall remove graphify section from CLAUDE.md + PreToolUse hook")
print(" codex install write graphify section to AGENTS.md (Codex)")
print(" codex uninstall remove graphify section from AGENTS.md")
print(" opencode install write graphify section to AGENTS.md (OpenCode)")
print(" opencode uninstall remove graphify section from AGENTS.md")
print(" claw install write graphify section to AGENTS.md (OpenClaw)")
print(" claw uninstall remove graphify section from AGENTS.md")
print(" droid install write graphify section to AGENTS.md (Factory Droid)")
print(" droid uninstall remove graphify section from AGENTS.md")
print()
return
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)
# Default to windows platform on Windows, claude elsewhere
default_platform = "windows" if platform.system() == "Windows" else "claude"
chosen_platform = default_platform
args = sys.argv[2:]
i = 0
while i < len(args):
if args[i].startswith("--platform="):
chosen_platform = args[i].split("=", 1)[1]
i += 1
elif args[i] == "--platform" and i + 1 < len(args):
chosen_platform = args[i + 1]
i += 2
else:
i += 1
install(platform=chosen_platform)
elif cmd == "claude":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
@@ -187,6 +331,15 @@ def main() -> None:
else:
print("Usage: graphify claude [install|uninstall]", file=sys.stderr)
sys.exit(1)
elif cmd in ("codex", "opencode", "claw", "droid"):
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
_agents_install(Path("."), cmd)
elif subcmd == "uninstall":
_agents_uninstall(Path("."))
else:
print(f"Usage: graphify {cmd} [install|uninstall]", file=sys.stderr)
sys.exit(1)
elif cmd == "hook":
from graphify.hooks import install as hook_install, uninstall as hook_uninstall, status as hook_status
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
@@ -207,7 +360,7 @@ def main() -> None:
detect_path = Path(".graphify_detect.json")
if detect_path.exists():
try:
detect_data = json.loads(detect_path.read_text())
detect_data = json.loads(detect_path.read_text(encoding="utf-8"))
corpus_words = detect_data.get("total_words")
except Exception:
pass
+9 -5
View File
@@ -16,12 +16,16 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
These are synthetic nodes created by the AST extractor and should be excluded
from god nodes, surprising connections, and knowledge gap reporting.
"""
label = G.nodes[node_id].get("label", "")
attrs = G.nodes[node_id]
label = attrs.get("label", "")
if not label:
return False
# File-level hub: label is a filename with a code extension
if label.split(".")[-1] in ("py", "ts", "js", "go", "rs", "java", "rb", "cpp", "c", "h"):
return True
# File-level hub: label matches the actual source filename (not just any label ending in .py)
source_file = attrs.get("source_file", "")
if source_file:
from pathlib import Path as _Path
if label == _Path(source_file).name:
return True
# Method stub: AST extractor labels methods as '.method_name()'
if label.startswith(".") and label.endswith("()"):
return True
@@ -468,7 +472,7 @@ def graph_diff(G_old: nx.Graph, G_new: nx.Graph) -> dict:
]
def edge_key(G: nx.Graph, u: str, v: str, data: dict) -> tuple:
return (u, v, data.get("relation", ""))
return (min(u, v), max(u, v), data.get("relation", ""))
old_edge_keys = {
edge_key(G_old, u, v, d)
+30 -11
View File
@@ -1,4 +1,25 @@
# assemble node+edge dicts into a NetworkX graph, preserving edge direction
#
# Node deduplication — three layers:
#
# 1. Within a file (AST): each extractor tracks a `seen_ids` set. A node ID is
# emitted at most once per file, so duplicate class/function definitions in
# the same source file are collapsed to the first occurrence.
#
# 2. Between files (build): NetworkX G.add_node() is idempotent — calling it
# twice with the same ID overwrites the attributes with the second call's
# values. Nodes are added in extraction order (AST first, then semantic),
# so if the same entity is extracted by both passes the semantic node
# silently overwrites the AST node. This is intentional: semantic nodes
# carry richer labels and cross-file context, while AST nodes have precise
# source_location. If you need to change the priority, reorder extractions
# passed to build().
#
# 3. Semantic merge (skill): before calling build(), the skill merges cached
# and new semantic results using an explicit `seen` set keyed on node["id"],
# so duplicates across cache hits and new extractions are resolved there
# before any graph construction happens.
#
from __future__ import annotations
import sys
import networkx as nx
@@ -28,24 +49,22 @@ 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
def build(extractions: list[dict]) -> nx.Graph:
"""Merge multiple extraction results into one graph."""
combined: dict = {"nodes": [], "edges": [], "input_tokens": 0, "output_tokens": 0}
"""Merge multiple extraction results into one graph.
Extractions are merged in order. For nodes with the same ID, the last
extraction's attributes win (NetworkX add_node overwrites). Pass AST
results before semantic results so semantic labels take precedence, or
reverse the order if you prefer AST source_location precision to win.
"""
combined: dict = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0}
for ext in extractions:
combined["nodes"].extend(ext.get("nodes", []))
combined["edges"].extend(ext.get("edges", []))
combined["hyperedges"].extend(ext.get("hyperedges", []))
combined["input_tokens"] += ext.get("input_tokens", 0)
combined["output_tokens"] += ext.get("output_tokens", 0)
return build_from_json(combined)
+27 -8
View File
@@ -3,17 +3,23 @@ from __future__ import annotations
import hashlib
import json
import os
from pathlib import Path
def file_hash(path: Path) -> str:
"""SHA256 of file contents, hex digest."""
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
"""SHA256 of file contents + resolved path. Prevents cache collisions on identical content."""
p = Path(path)
h = hashlib.sha256()
h.update(p.read_bytes())
h.update(b"\x00")
h.update(str(p.resolve()).encode())
return h.hexdigest()
def cache_dir(root: Path = Path(".")) -> Path:
"""Returns graphify-out/cache/ - creates it if needed."""
d = Path(root).resolve() / "graphify-out" / "cache"
d = Path(root) / "graphify-out" / "cache"
d.mkdir(parents=True, exist_ok=True)
return d
@@ -46,7 +52,13 @@ def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
"""
h = file_hash(path)
entry = cache_dir(root) / f"{h}.json"
entry.write_text(json.dumps(result))
tmp = entry.with_suffix(".tmp")
try:
tmp.write_text(json.dumps(result))
os.replace(tmp, entry)
except Exception:
tmp.unlink(missing_ok=True)
raise
def cached_files(root: Path = Path(".")) -> set[str]:
@@ -65,14 +77,15 @@ def clear_cache(root: Path = Path(".")) -> None:
def check_semantic_cache(
files: list[str],
root: Path = Path("."),
) -> tuple[list[dict], list[dict], list[str]]:
) -> tuple[list[dict], list[dict], list[dict], list[str]]:
"""Check semantic extraction cache for a list of absolute file paths.
Returns (cached_nodes, cached_edges, uncached_files).
Returns (cached_nodes, cached_edges, cached_hyperedges, 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:
@@ -80,15 +93,17 @@ 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, uncached
return cached_nodes, cached_edges, cached_hyperedges, 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.
@@ -98,7 +113,7 @@ def save_semantic_cache(
"""
from collections import defaultdict
by_file: dict[str, dict] = defaultdict(lambda: {"nodes": [], "edges": []})
by_file: dict[str, dict] = defaultdict(lambda: {"nodes": [], "edges": [], "hyperedges": []})
for n in nodes:
src = n.get("source_file", "")
if src:
@@ -107,6 +122,10 @@ 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():
+20 -7
View File
@@ -1,8 +1,25 @@
"""Leiden community detection on NetworkX graphs. Splits oversized communities. Returns cohesion scores."""
"""Community detection on NetworkX graphs. Uses Leiden (graspologic) if available, falls back to Louvain (networkx). 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.
@@ -36,8 +53,6 @@ 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]
@@ -45,7 +60,7 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
raw: dict[int, list[str]] = {}
if connected.number_of_nodes() > 0:
partition: dict[str, int] = leiden(connected)
partition = _partition(connected)
for node, cid in partition.items():
raw.setdefault(cid, []).append(node)
@@ -76,13 +91,11 @@ 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:
from graspologic.partition import leiden
sub_partition: dict[str, int] = leiden(subgraph)
sub_partition = _partition(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:
+188 -3
View File
@@ -1,5 +1,6 @@
# file discovery, type classification, and corpus health checks
from __future__ import annotations
import fnmatch
import json
import os
import re
@@ -16,10 +17,11 @@ class FileType(str, Enum):
_MANIFEST_PATH = "graphify-out/manifest.json"
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.tsx', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php'}
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.tsx', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.toc', '.zig', '.ps1', '.ex', '.exs'}
DOC_EXTENSIONS = {'.md', '.txt', '.rst'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
OFFICE_EXTENSIONS = {'.docx', '.xlsx'}
CORPUS_WARN_THRESHOLD = 50_000 # words - below this, warn "you may not need a graph"
CORPUS_UPPER_THRESHOLD = 500_000 # words - above this, warn about token cost
@@ -85,6 +87,8 @@ def classify_file(path: Path) -> FileType | None:
if _looks_like_paper(path):
return FileType.PAPER
return FileType.DOCUMENT
if ext in OFFICE_EXTENSIONS:
return FileType.DOCUMENT
return None
@@ -103,10 +107,115 @@ def extract_pdf_text(path: Path) -> str:
return ""
def docx_to_markdown(path: Path) -> str:
"""Convert a .docx file to markdown text using python-docx."""
try:
from docx import Document
from docx.oxml.ns import qn
doc = Document(str(path))
lines = []
for para in doc.paragraphs:
style = para.style.name if para.style else ""
text = para.text.strip()
if not text:
lines.append("")
continue
if style.startswith("Heading 1"):
lines.append(f"# {text}")
elif style.startswith("Heading 2"):
lines.append(f"## {text}")
elif style.startswith("Heading 3"):
lines.append(f"### {text}")
elif style.startswith("List"):
lines.append(f"- {text}")
else:
lines.append(text)
# Tables
for table in doc.tables:
rows = [[cell.text.strip() for cell in row.cells] for row in table.rows]
if not rows:
continue
header = "| " + " | ".join(rows[0]) + " |"
sep = "| " + " | ".join("---" for _ in rows[0]) + " |"
lines.extend([header, sep])
for row in rows[1:]:
lines.append("| " + " | ".join(row) + " |")
return "\n".join(lines)
except ImportError:
return ""
except Exception:
return ""
def xlsx_to_markdown(path: Path) -> str:
"""Convert an .xlsx file to markdown text using openpyxl."""
try:
import openpyxl
wb = openpyxl.load_workbook(str(path), read_only=True, data_only=True)
sections = []
for sheet_name in wb.sheetnames:
ws = wb[sheet_name]
rows = []
for row in ws.iter_rows(values_only=True):
# Skip entirely empty rows
if all(cell is None for cell in row):
continue
rows.append([str(cell) if cell is not None else "" for cell in row])
if not rows:
continue
sections.append(f"## Sheet: {sheet_name}")
if len(rows) >= 1:
header = "| " + " | ".join(rows[0]) + " |"
sep = "| " + " | ".join("---" for _ in rows[0]) + " |"
sections.extend([header, sep])
for row in rows[1:]:
sections.append("| " + " | ".join(row) + " |")
wb.close()
return "\n".join(sections)
except ImportError:
return ""
except Exception:
return ""
def convert_office_file(path: Path, out_dir: Path) -> Path | None:
"""Convert a .docx or .xlsx to a markdown sidecar in out_dir.
Returns the path of the converted .md file, or None if conversion failed
or the required library is not installed.
"""
ext = path.suffix.lower()
if ext == ".docx":
text = docx_to_markdown(path)
elif ext == ".xlsx":
text = xlsx_to_markdown(path)
else:
return None
if not text.strip():
return None
out_dir.mkdir(parents=True, exist_ok=True)
# Use a stable name derived from the original path to avoid collisions
import hashlib
name_hash = hashlib.sha256(str(path.resolve()).encode()).hexdigest()[:8]
out_path = out_dir / f"{path.stem}_{name_hash}.md"
out_path.write_text(
f"<!-- converted from {path.name} -->\n\n{text}",
encoding="utf-8",
)
return out_path
def count_words(path: Path) -> int:
try:
if path.suffix.lower() == ".pdf":
ext = path.suffix.lower()
if ext == ".pdf":
return len(extract_pdf_text(path).split())
if ext == ".docx":
return len(docx_to_markdown(path).split())
if ext == ".xlsx":
return len(xlsx_to_markdown(path).split())
return len(path.read_text(errors="ignore").split())
except Exception:
return 0
@@ -134,6 +243,56 @@ def _is_noise_dir(part: str) -> bool:
return False
def _load_graphifyignore(root: Path) -> list[str]:
"""Read .graphifyignore from root and return a list of patterns.
Lines starting with # are comments. Blank lines are ignored.
Patterns follow gitignore semantics: glob matched against the path
relative to root. A leading slash anchors to root. A trailing slash
matches directories only (we match both dir and file for simplicity).
"""
ignore_file = root / ".graphifyignore"
if not ignore_file.exists():
return []
patterns = []
for line in ignore_file.read_text(errors="ignore").splitlines():
line = line.strip()
if line and not line.startswith("#"):
patterns.append(line)
return patterns
def _is_ignored(path: Path, root: Path, patterns: list[str]) -> bool:
"""Return True if path matches any .graphifyignore pattern."""
if not patterns:
return False
try:
rel = str(path.relative_to(root))
except ValueError:
return False
rel = rel.replace(os.sep, "/")
parts = rel.split("/")
for pattern in patterns:
# Normalize: strip leading/trailing slashes for matching purposes
p = pattern.strip("/")
if not p:
continue
# Match against full relative path
if fnmatch.fnmatch(rel, p):
return True
# Match against filename alone
if fnmatch.fnmatch(path.name, p):
return True
# Match against any path segment or prefix
# e.g. "vendor" or "vendor/" should match "vendor/lib.py"
for i, part in enumerate(parts):
if fnmatch.fnmatch(part, p):
return True
if fnmatch.fnmatch("/".join(parts[:i + 1]), p):
return True
return False
def detect(root: Path) -> dict:
files: dict[FileType, list[str]] = {
FileType.CODE: [],
@@ -144,6 +303,7 @@ def detect(root: Path) -> dict:
total_words = 0
skipped_sensitive: list[str] = []
ignore_patterns = _load_graphifyignore(root)
# Always include graphify-out/memory/ - query results filed back into the graph
memory_dir = root / "graphify-out" / "memory"
@@ -162,7 +322,9 @@ def detect(root: Path) -> dict:
# Prune noise dirs in-place so os.walk never descends into them
dirnames[:] = [
d for d in dirnames
if not d.startswith(".") and not _is_noise_dir(d)
if not d.startswith(".")
and not _is_noise_dir(d)
and not _is_ignored(dp / d, root, ignore_patterns)
]
for fname in filenames:
p = dp / fname
@@ -170,6 +332,8 @@ def detect(root: Path) -> dict:
seen.add(p)
all_files.append(p)
converted_dir = root / "graphify-out" / "converted"
for p in all_files:
# For memory dir files, skip hidden/noise filtering
in_memory = memory_dir.exists() and str(p).startswith(str(memory_dir))
@@ -178,11 +342,26 @@ def detect(root: Path) -> dict:
# but catch hidden files at the root level
if p.name.startswith("."):
continue
# Skip files inside our own converted/ dir (avoid re-processing sidecars)
if str(p).startswith(str(converted_dir)):
continue
if _is_ignored(p, root, ignore_patterns):
continue
if _is_sensitive(p):
skipped_sensitive.append(str(p))
continue
ftype = classify_file(p)
if ftype:
# Office files: convert to markdown sidecar so subagents can read them
if p.suffix.lower() in OFFICE_EXTENSIONS:
md_path = convert_office_file(p, converted_dir)
if md_path:
files[ftype].append(str(md_path))
total_words += count_words(md_path)
else:
# Conversion failed (library not installed) - skip with note
skipped_sensitive.append(str(p) + " [office conversion failed - pip install graphifyy[office]]")
continue
files[ftype].append(str(p))
total_words += count_words(p)
@@ -210,6 +389,7 @@ def detect(root: Path) -> dict:
"needs_graph": needs_graph,
"warning": warning,
"skipped_sensitive": skipped_sensitive,
"graphifyignore_patterns": len(ignore_patterns),
}
@@ -266,9 +446,14 @@ def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
else:
unchanged_files[ftype].append(f)
# Files in manifest that no longer exist - their cached nodes are now ghost nodes
current_files = {f for flist in full["files"].values() for f in flist}
deleted_files = [f for f in manifest if f not in current_files]
new_total = sum(len(v) for v in new_files.values())
full["incremental"] = True
full["new_files"] = new_files
full["unchanged_files"] = unchanged_files
full["new_total"] = new_total
full["deleted_files"] = deleted_files
return full
+22 -13
View File
@@ -8,6 +8,7 @@ from pathlib import Path
import networkx as nx
from networkx.readwrite import json_graph
from graphify.security import sanitize_label
from graphify.analyze import _node_community_map
COMMUNITY_COLORS = [
"#4E79A7", "#F28E2B", "#E15759", "#76B7B2", "#59A14F",
@@ -17,11 +18,6 @@ COMMUNITY_COLORS = [
MAX_NODES_FOR_VIZ = 5_000
def _node_community_map(communities: dict[int, list[str]]) -> dict[str, int]:
"""Invert communities dict: node_id -> community_id."""
return {n: cid for cid, nodes in communities.items() for n in nodes}
def _html_styles() -> str:
return """<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
@@ -275,18 +271,26 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) ->
json.dump(data, f, indent=2)
def _cypher_escape(s: str) -> str:
"""Escape a string for safe embedding in a Cypher single-quoted literal."""
return s.replace("\\", "\\\\").replace("'", "\\'")
def to_cypher(G: nx.Graph, output_path: str) -> None:
lines = ["// Neo4j Cypher import - generated by /graphify", ""]
for node_id, data in G.nodes(data=True):
label = data.get("label", node_id).replace("'", "\\'")
ftype = data.get("file_type", "unknown").capitalize()
lines.append(f"MERGE (n:{ftype} {{id: '{node_id}', label: '{label}'}});")
label = _cypher_escape(data.get("label", node_id))
node_id_esc = _cypher_escape(node_id)
ftype = re.sub(r"[^A-Za-z0-9_]", "", data.get("file_type", "unknown").capitalize()) or "Entity"
lines.append(f"MERGE (n:{ftype} {{id: '{node_id_esc}', label: '{label}'}});")
lines.append("")
for u, v, data in G.edges(data=True):
rel = data.get("relation", "RELATES_TO").upper().replace(" ", "_").replace("-", "_")
conf = data.get("confidence", "EXTRACTED")
rel = re.sub(r"[^A-Za-z0-9_]", "_", data.get("relation", "RELATES_TO").upper())
conf = _cypher_escape(data.get("confidence", "EXTRACTED"))
u_esc = _cypher_escape(u)
v_esc = _cypher_escape(v)
lines.append(
f"MATCH (a {{id: '{u}'}}), (b {{id: '{v}'}}) "
f"MATCH (a {{id: '{u_esc}'}}), (b {{id: '{v_esc}'}}) "
f"MERGE (a)-[:{rel} {{confidence: '{conf}'}}]->(b);"
)
with open(output_path, "w") as f:
@@ -333,7 +337,7 @@ def to_html(
"font": {"size": font_size, "color": "#ffffff"},
"title": f"{label}",
"community": cid,
"community_name": (community_labels or {}).get(cid, f"Community {cid}"),
"community_name": sanitize_label((community_labels or {}).get(cid, f"Community {cid}")),
"source_file": sanitize_label(data.get("source_file", "")),
"file_type": data.get("file_type", ""),
"degree": deg,
@@ -832,6 +836,11 @@ def push_to_neo4j(
def _safe_rel(relation: str) -> str:
return re.sub(r"[^A-Z0-9_]", "_", relation.upper().replace(" ", "_").replace("-", "_")) or "RELATED_TO"
def _safe_label(label: str) -> str:
"""Sanitize a Neo4j node label to prevent Cypher injection."""
sanitized = re.sub(r"[^A-Za-z0-9_]", "", label)
return sanitized if sanitized else "Entity"
driver = GraphDatabase.driver(uri, auth=(user, password))
nodes_pushed = 0
edges_pushed = 0
@@ -843,7 +852,7 @@ def push_to_neo4j(
cid = node_community.get(node_id)
if cid is not None:
props["community"] = cid
ftype = data.get("file_type", "Entity").capitalize()
ftype = _safe_label(data.get("file_type", "Entity").capitalize())
session.run(
f"MERGE (n:{ftype} {{id: $id}}) SET n += $props",
id=node_id,
+1430 -1645
View File
File diff suppressed because it is too large. Load diff
+98 -83
View File
@@ -1,13 +1,15 @@
# git hook integration - install/uninstall graphify post-commit hook
# git hook integration - install/uninstall graphify post-commit and post-checkout hooks
from __future__ import annotations
import subprocess
import re
from pathlib import Path
_HOOK_MARKER = "# graphify-hook"
_HOOK_MARKER = "# graphify-hook-start"
_HOOK_MARKER_END = "# graphify-hook-end"
_CHECKOUT_MARKER = "# graphify-checkout-hook-start"
_CHECKOUT_MARKER_END = "# graphify-checkout-hook-end"
_HOOK_SCRIPT = """\
#!/bin/bash
# graphify-hook
# graphify-hook-start
# Auto-rebuilds the knowledge graph after each commit (code files only, no LLM needed).
# Installed by: graphify hook install
@@ -40,8 +42,43 @@ try:
_rebuild_code(Path('.'))
except Exception as exc:
print(f'[graphify hook] Rebuild failed: {exc}')
sys.exit(0)
sys.exit(1)
"
# graphify-hook-end
"""
_CHECKOUT_SCRIPT = """\
# graphify-checkout-hook-start
# 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
import sys
try:
_rebuild_code(Path('.'))
except Exception as exc:
print(f'[graphify] Rebuild failed: {exc}')
sys.exit(1)
"
# graphify-checkout-hook-end
"""
@@ -54,104 +91,82 @@ def _git_root(path: Path) -> Path | None:
return None
def _hooks_dir(root: Path) -> Path:
"""Return the active hooks directory for this repo.
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("#!/bin/bash\n" + script)
hook_path.chmod(0o755)
return f"installed at {hook_path}"
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 _uninstall_hook(hooks_dir: Path, name: str, marker: str, marker_end: str) -> str:
"""Remove graphify section from a git hook using start/end markers."""
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."
new_content = re.sub(
rf"{re.escape(marker)}.*?{re.escape(marker_end)}\n?",
"",
content,
flags=re.DOTALL,
).strip()
if not new_content or new_content == "#!/bin/bash":
hook_path.unlink()
return f"removed {name} hook at {hook_path}"
hook_path.write_text(new_content + "\n")
return f"graphify removed from {name} at {hook_path} (other hook content preserved)"
def install(path: Path = Path(".")) -> str:
"""Install graphify post-commit hook in the nearest git repo.
Returns a message describing what was done.
"""
"""Install graphify post-commit and post-checkout hooks in the nearest git repo."""
root = _git_root(path)
if root is None:
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
hooks_dir = _hooks_dir(root)
hook_path = hooks_dir / "post-commit"
hooks_dir = root / ".git" / "hooks"
hooks_dir.mkdir(exist_ok=True)
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}"
commit_msg = _install_hook(hooks_dir, "post-commit", _HOOK_SCRIPT, _HOOK_MARKER)
checkout_msg = _install_hook(hooks_dir, "post-checkout", _CHECKOUT_SCRIPT, _CHECKOUT_MARKER)
hook_path.write_text(_HOOK_SCRIPT)
hook_path.chmod(0o755)
return f"graphify hook installed at {hook_path}"
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
def uninstall(path: Path = Path(".")) -> str:
"""Remove graphify post-commit hook."""
"""Remove graphify post-commit and post-checkout hooks."""
root = _git_root(path)
if root is None:
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
hook_path = _hooks_dir(root) / "post-commit"
if not hook_path.exists():
return "No post-commit hook found - nothing to remove."
hooks_dir = root / ".git" / "hooks"
commit_msg = _uninstall_hook(hooks_dir, "post-commit", _HOOK_MARKER, _HOOK_MARKER_END)
checkout_msg = _uninstall_hook(hooks_dir, "post-checkout", _CHECKOUT_MARKER, _CHECKOUT_MARKER_END)
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)"
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
def status(path: Path = Path(".")) -> str:
"""Check if graphify hook is installed."""
"""Check if graphify hooks are installed."""
root = _git_root(path)
if root is None:
return "Not in a git repository."
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)"
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}"
+8 -5
View File
@@ -10,6 +10,11 @@ from pathlib import Path
from graphify.security import safe_fetch, safe_fetch_text, validate_url
def _yaml_str(s: str) -> str:
"""Escape a string for embedding in a YAML double-quoted scalar."""
return s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
def _safe_filename(url: str, suffix: str) -> str:
"""Turn a URL into a safe filename."""
parsed = urllib.parse.urlparse(url)
@@ -67,9 +72,7 @@ def _fetch_tweet(url: str, author: str | None, contributor: str | None) -> tuple
oembed_url = url.replace("x.com", "twitter.com")
oembed_api = f"https://publish.twitter.com/oembed?url={urllib.parse.quote(oembed_url)}&omit_script=true"
try:
req = urllib.request.Request(oembed_api, headers={"User-Agent": "graphify/1.0"})
with urllib.request.urlopen(req, timeout=10) as resp:
data = json.loads(resp.read())
data = json.loads(safe_fetch_text(oembed_api))
tweet_text = re.sub(r"<[^>]+>", "", data.get("html", "")).strip()
tweet_author = data.get("author_name", "unknown")
except Exception:
@@ -108,7 +111,7 @@ def _fetch_webpage(url: str, author: str | None, contributor: str | None) -> tup
content = f"""---
source_url: {url}
type: webpage
title: "{title}"
title: "{_yaml_str(title)}"
captured_at: {now}
contributor: {contributor or author or 'unknown'}
---
@@ -250,7 +253,7 @@ def save_query_result(
"---",
f'type: "{query_type}"',
f'date: "{now.isoformat()}"',
f'question: "{re.sub(chr(10) + chr(13), " ", question).replace(chr(34), chr(39))}"',
f'question: "{_yaml_str(question)}"',
'contributor: "graphify"',
]
if source_nodes:
+34 -2
View File
@@ -8,20 +8,28 @@ import urllib.parse
import urllib.request
from pathlib import Path
import ipaddress
import socket
_ALLOWED_SCHEMES = {"http", "https"}
_MAX_FETCH_BYTES = 52_428_800 # 50 MB hard cap for binary downloads
_MAX_TEXT_BYTES = 10_485_760 # 10 MB hard cap for HTML / text
# AWS metadata, link-local, and common cloud metadata endpoints
_BLOCKED_HOSTS = {"metadata.google.internal", "metadata.google.com"}
# ---------------------------------------------------------------------------
# URL validation
# ---------------------------------------------------------------------------
def validate_url(url: str) -> str:
"""Raise ValueError if *url* is not http or https.
"""Raise ValueError if *url* is not http or https, or targets a private/internal IP.
Blocks file://, ftp://, data:, and any other scheme that could be used
for SSRF or local file access.
for SSRF or local file access. Also blocks requests to private/reserved
IP ranges (127.x, 10.x, 169.254.x, etc.) and cloud metadata endpoints
to prevent SSRF in cloud environments.
"""
parsed = urllib.parse.urlparse(url)
if parsed.scheme.lower() not in _ALLOWED_SCHEMES:
@@ -29,6 +37,30 @@ def validate_url(url: str) -> str:
f"Blocked URL scheme '{parsed.scheme}' - only http and https are allowed. "
f"Got: {url!r}"
)
hostname = parsed.hostname
if hostname:
# Block known cloud metadata hostnames
if hostname.lower() in _BLOCKED_HOSTS:
raise ValueError(
f"Blocked cloud metadata endpoint '{hostname}'. "
f"Got: {url!r}"
)
# Resolve hostname and block private/reserved IP ranges
try:
infos = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM)
for info in infos:
addr = info[4][0]
ip = ipaddress.ip_address(addr)
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local:
raise ValueError(
f"Blocked private/internal IP {addr} (resolved from '{hostname}'). "
f"Got: {url!r}"
)
except socket.gaierror:
pass # DNS failure will surface later during fetch
return url
+2 -2
View File
@@ -75,8 +75,8 @@ def _dfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], lis
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000) -> str:
"""Render subgraph as text, cutting at token_budget (approx 4 chars/token)."""
char_budget = token_budget * 4
"""Render subgraph as text, cutting at token_budget (approx 3 chars/token)."""
char_budget = token_budget * 3
lines = []
for nid in sorted(nodes, key=lambda n: G.degree(n), reverse=True):
d = G.nodes[nid]
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,5 @@
---
name: graphify
name: graphify-windows
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
trigger: /graphify
---
@@ -57,16 +57,20 @@ Follow these steps in order. Do not skip steps.
### Step 1 - Ensure graphify is installed
```bash
python3 -c "import graphify" 2>/dev/null || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
```powershell
# Detect Python and install graphify if needed
python -c "import graphify" 2>$null
if ($LASTEXITCODE -ne 0) { pip install graphifyy -q 2>&1 | Select-Object -Last 3 }
# Write interpreter path for all subsequent steps
python -c "import sys; open('.graphify_python', 'w').write(sys.executable)"
```
If the import succeeds, print nothing and move straight to Step 2.
### Step 2 - Detect files
```bash
python3 -c "
```powershell
python -c "
import json
from graphify.detect import detect
from pathlib import Path
@@ -105,8 +109,8 @@ 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
python3 -c "
```powershell
python -c "
import sys, json
from graphify.extract import collect_files, extract
from pathlib import Path
@@ -143,8 +147,8 @@ Before dispatching subagents, print a timing estimate:
Before dispatching any subagents, check which files already have cached extraction results:
```bash
python3 -c "
```powershell
python -c "
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
@@ -152,10 +156,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, uncached = check_semantic_cache(all_files)
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
if cached_nodes or cached_edges:
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges}))
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}))
Path('.graphify_uncached.txt').write_text('\n'.join(uncached))
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
"
@@ -195,7 +199,7 @@ 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.
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.
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.
@@ -222,15 +226,16 @@ 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 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
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
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","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|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}
```
**Step B3 - Collect, cache, and merge**
@@ -242,29 +247,30 @@ Wait for all subagents. For each result:
If more than half the chunks failed, stop and tell the user.
Save new results to cache:
```bash
python3 -c "
```powershell
python -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':[]}
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []))
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', []))
print(f'Cached {saved} files')
"
```
Merge cached + new results into `.graphify_semantic.json`:
```bash
python3 -c "
```powershell
python -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':[]}
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[]}
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':[]}
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:
@@ -275,6 +281,7 @@ 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),
}
@@ -282,12 +289,12 @@ Path('.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
"
```
Clean up temp files: `rm -f .graphify_cached.json .graphify_uncached.txt .graphify_semantic_new.json`
Clean up temp files: `Remove-Item -ErrorAction SilentlyContinue .graphify_cached.json, .graphify_uncached.txt, .graphify_semantic_new.json`
#### Part C - Merge AST + semantic into final extraction
```bash
python3 -c "
```powershell
python -c "
import sys, json
from pathlib import Path
@@ -303,9 +310,11 @@ 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),
}
@@ -318,9 +327,9 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
```bash
mkdir -p graphify-out
python3 -c "
```powershell
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
python -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
@@ -372,8 +381,8 @@ 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
python3 -c "
```powershell
python -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import score_all
@@ -406,12 +415,14 @@ 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 (default) + optional HTML
### Step 6 - Generate Obsidian vault (opt-in) + HTML
**Always generate the Obsidian vault and HTML** - they are the primary visualizations. Skip both if `--no-viz` (report + JSON only).
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
```bash
python3 -c "
If `--obsidian` was given:
```powershell
python -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_obsidian, to_canvas
@@ -439,10 +450,10 @@ print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries
"
```
Also generate the HTML graph (always, unless `--no-viz`):
Generate the HTML graph (always, unless `--no-viz`):
```bash
python3 -c "
```powershell
python -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_html
@@ -468,8 +479,8 @@ else:
**If `--neo4j`** - generate a Cypher file for manual import:
```bash
python3 -c "
```powershell
python -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_cypher
@@ -483,8 +494,8 @@ 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
python3 -c "
```powershell
python -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster
@@ -505,8 +516,8 @@ Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default
### Step 7b - SVG export (only if --svg flag)
```bash
python3 -c "
```powershell
python -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_svg
@@ -527,8 +538,8 @@ print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
### Step 7c - GraphML export (only if --graphml flag)
```bash
python3 -c "
```powershell
python -c "
import json
from graphify.build import build_from_json
from graphify.export import to_graphml
@@ -547,8 +558,8 @@ print('graph.graphml written - open in Gephi, yEd, or any GraphML tool')
### Step 7d - MCP server (only if --mcp flag)
```bash
python3 -m graphify.serve graphify-out/graph.json
```powershell
python -m graphify.serve graphify-out/graph.json
```
This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live.
@@ -558,7 +569,7 @@ To configure in Claude Desktop, add to `claude_desktop_config.json`:
{
"mcpServers": {
"graphify": {
"command": "python3",
"command": "python",
"args": ["-m", "graphify.serve", "/absolute/path/to/graphify-out/graph.json"]
}
}
@@ -569,8 +580,8 @@ 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
python3 -c "
```powershell
python -c "
import json
from graphify.benchmark import run_benchmark, print_benchmark
from pathlib import Path
@@ -587,8 +598,8 @@ 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
python3 -c "
```powershell
python -c "
import json
from pathlib import Path
from datetime import datetime, timezone
@@ -622,26 +633,18 @@ 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
rm -f graphify-out/.needs_update 2>/dev/null || true
Remove-Item -ErrorAction SilentlyContinue .graphify_detect.json, .graphify_extract.json, .graphify_ast.json, .graphify_semantic.json, .graphify_analysis.json, .graphify_labels.json, .graphify_python
Remove-Item -ErrorAction SilentlyContinue graphify-out/.needs_update
```
Tell the user:
Tell the user (omit the obsidian line unless --obsidian was given):
```
Graph complete. Outputs are in a hidden folder called graphify-out/ inside the directory you ran this on.
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
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/
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)
```
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
@@ -667,8 +670,8 @@ 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
python3 -c "
```powershell
python -c "
import sys, json
from graphify.detect import detect_incremental, save_manifest
from pathlib import Path
@@ -686,13 +689,13 @@ 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
python3 -c "
```powershell
python -c "
import json
from pathlib import Path
result = json.loads(open('.graphify_incremental.json').read()) if Path('.graphify_incremental.json').exists() else {}
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts'}
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc'}
new_files = result.get('new_files', {})
all_changed = [f for files in new_files.values() for f in files]
code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
@@ -706,8 +709,8 @@ If `code_only` is False (any changed file is a doc/paper/image): run the full St
Then:
```bash
python3 -c "
```powershell
python -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_json
@@ -733,8 +736,8 @@ Then run Steps 4–8 on the merged graph as normal.
After Step 4, show the graph diff:
```bash
python3 -c "
```powershell
python -c "
import json
from graphify.analyze import graph_diff
from graphify.build import build_from_json
@@ -758,8 +761,8 @@ if old_data:
"
```
Before the merge step, save the old graph: `cp graphify-out/graph.json .graphify_old.json`
Clean up after: `rm -f .graphify_old.json`
Before the merge step, save the old graph: `Copy-Item graphify-out/graph.json .graphify_old.json`
Clean up after: `Remove-Item -ErrorAction SilentlyContinue .graphify_old.json`
---
@@ -767,8 +770,8 @@ 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
python3 -c "
```powershell
python -c "
import sys, json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections
@@ -820,8 +823,8 @@ Two traversal modes - choose based on the question:
| DFS | `--dfs` | "How does X reach Y?" - trace a specific chain or dependency path |
First check the graph exists:
```bash
python3 -c "
```powershell
python -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.')
@@ -838,8 +841,8 @@ Load `graphify-out/graph.json`, then:
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
5. If the graph lacks enough information, say so - do not hallucinate edges.
```bash
python3 -c "
```powershell
python -c "
import sys, json
from networkx.readwrite import json_graph
import networkx as nx
@@ -929,8 +932,8 @@ 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
python3 -c "
```powershell
python -c "
from graphify.ingest import save_query_result
from pathlib import Path
save_query_result(
@@ -953,8 +956,8 @@ Replace `QUESTION` with the question, `ANSWER` with your full answer text, `SOUR
Find the shortest path between two named concepts in the graph.
First check the graph exists:
```bash
python3 -c "
```powershell
python -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.')
@@ -963,8 +966,8 @@ if not Path('graphify-out/graph.json').exists():
```
If it fails, stop and tell the user to run `/graphify <path>` first.
```bash
python3 -c "
```powershell
python -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
@@ -1015,8 +1018,8 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
After writing the explanation, save it back:
```bash
python3 -c "
```powershell
python -c "
from graphify.ingest import save_query_result
from pathlib import Path
save_query_result(
@@ -1037,8 +1040,8 @@ print('Path result saved to graphify-out/memory/')
Give a plain-language explanation of a single node - everything connected to it.
First check the graph exists:
```bash
python3 -c "
```powershell
python -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.')
@@ -1047,8 +1050,8 @@ if not Path('graphify-out/graph.json').exists():
```
If it fails, stop and tell the user to run `/graphify <path>` first.
```bash
python3 -c "
```powershell
python -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
@@ -1092,8 +1095,8 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
After writing the explanation, save it back:
```bash
python3 -c "
```powershell
python -c "
from graphify.ingest import save_query_result
from pathlib import Path
save_query_result(
@@ -1113,8 +1116,8 @@ print('Explanation saved to graphify-out/memory/')
Fetch a URL and add it to the corpus, then update the graph.
```bash
python3 -c "
```powershell
python -c "
import sys
from graphify.ingest import ingest
from pathlib import Path
@@ -1146,8 +1149,8 @@ Supported URL types (auto-detected):
Start a background watcher that monitors a folder and auto-updates the graph when files change.
```bash
python3 -m graphify.watch INPUT_PATH --debounce 3
```powershell
python -m graphify.watch INPUT_PATH --debounce 3
```
Replace INPUT_PATH with the folder to watch. Behavior depends on what changed:
+77 -70
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,15 +58,26 @@ Follow these steps in order. Do not skip steps.
### Step 1 - Ensure graphify is installed
```bash
python3 -c "import graphify" 2>/dev/null || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
# 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)"
```
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
python3 -c "
$(cat .graphify_python) -c "
import json
from graphify.detect import detect
from pathlib import Path
@@ -106,7 +117,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
python3 -c "
$(cat .graphify_python) -c "
import sys, json
from graphify.extract import collect_files, extract
from pathlib import Path
@@ -144,7 +155,7 @@ Before dispatching subagents, print a timing estimate:
Before dispatching any subagents, check which files already have cached extraction results:
```bash
python3 -c "
$(cat .graphify_python) -c "
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
@@ -152,10 +163,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, uncached = check_semantic_cache(all_files)
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
if cached_nodes or cached_edges:
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges}))
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}))
Path('.graphify_uncached.txt').write_text('\n'.join(uncached))
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
"
@@ -195,10 +206,7 @@ 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. 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"`.
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.
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.
@@ -225,15 +233,16 @@ 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 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
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
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","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|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}
```
**Step B3 - Collect, cache, and merge**
@@ -246,28 +255,29 @@ If more than half the chunks failed, stop and tell the user.
Save new results to cache:
```bash
python3 -c "
$(cat .graphify_python) -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':[]}
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []))
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', []))
print(f'Cached {saved} files')
"
```
Merge cached + new results into `.graphify_semantic.json`:
```bash
python3 -c "
$(cat .graphify_python) -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':[]}
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[]}
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':[]}
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:
@@ -278,6 +288,7 @@ 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),
}
@@ -290,7 +301,7 @@ Clean up temp files: `rm -f .graphify_cached.json .graphify_uncached.txt .graphi
#### Part C - Merge AST + semantic into final extraction
```bash
python3 -c "
$(cat .graphify_python) -c "
import sys, json
from pathlib import Path
@@ -306,9 +317,11 @@ 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),
}
@@ -323,7 +336,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
```bash
mkdir -p graphify-out
python3 -c "
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
@@ -376,7 +389,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
python3 -c "
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import score_all
@@ -409,12 +422,14 @@ 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 (default) + optional HTML
### Step 6 - Generate Obsidian vault (opt-in) + HTML
**Always generate the Obsidian vault and HTML** - they are the primary visualizations. Skip both if `--no-viz` (report + JSON only).
**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:
```bash
python3 -c "
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_obsidian, to_canvas
@@ -442,10 +457,10 @@ print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries
"
```
Also generate the HTML graph (always, unless `--no-viz`):
Generate the HTML graph (always, unless `--no-viz`):
```bash
python3 -c "
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_html
@@ -472,7 +487,7 @@ else:
**If `--neo4j`** - generate a Cypher file for manual import:
```bash
python3 -c "
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_cypher
@@ -487,7 +502,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
python3 -c "
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster
@@ -509,7 +524,7 @@ Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default
### Step 7b - SVG export (only if --svg flag)
```bash
python3 -c "
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_svg
@@ -531,7 +546,7 @@ print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
### Step 7c - GraphML export (only if --graphml flag)
```bash
python3 -c "
$(cat .graphify_python) -c "
import json
from graphify.build import build_from_json
from graphify.export import to_graphml
@@ -573,7 +588,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
python3 -c "
$(cat .graphify_python) -c "
import json
from graphify.benchmark import run_benchmark, print_benchmark
from pathlib import Path
@@ -591,7 +606,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
python3 -c "
$(cat .graphify_python) -c "
import json
from pathlib import Path
from datetime import datetime, timezone
@@ -625,26 +640,18 @@ 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
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-out/.needs_update 2>/dev/null || true
```
Tell the user:
Tell the user (omit the obsidian line unless --obsidian was given):
```
Graph complete. Outputs are in a hidden folder called graphify-out/ inside the directory you ran this on.
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
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/
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)
```
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
@@ -671,7 +678,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
python3 -c "
$(cat .graphify_python) -c "
import sys, json
from graphify.detect import detect_incremental, save_manifest
from pathlib import Path
@@ -690,12 +697,12 @@ 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
python3 -c "
$(cat .graphify_python) -c "
import json
from pathlib import Path
result = json.loads(open('.graphify_incremental.json').read()) if Path('.graphify_incremental.json').exists() else {}
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts'}
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc'}
new_files = result.get('new_files', {})
all_changed = [f for files in new_files.values() for f in files]
code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
@@ -710,7 +717,7 @@ If `code_only` is False (any changed file is a doc/paper/image): run the full St
Then:
```bash
python3 -c "
$(cat .graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_json
@@ -737,7 +744,7 @@ Then run Steps 4–8 on the merged graph as normal.
After Step 4, show the graph diff:
```bash
python3 -c "
$(cat .graphify_python) -c "
import json
from graphify.analyze import graph_diff
from graphify.build import build_from_json
@@ -771,7 +778,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
python3 -c "
$(cat .graphify_python) -c "
import sys, json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections
@@ -824,7 +831,7 @@ Two traversal modes - choose based on the question:
First check the graph exists:
```bash
python3 -c "
$(cat .graphify_python) -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.')
@@ -842,7 +849,7 @@ Load `graphify-out/graph.json`, then:
5. If the graph lacks enough information, say so - do not hallucinate edges.
```bash
python3 -c "
$(cat .graphify_python) -c "
import sys, json
from networkx.readwrite import json_graph
import networkx as nx
@@ -933,7 +940,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
python3 -c "
$(cat .graphify_python) -c "
from graphify.ingest import save_query_result
from pathlib import Path
save_query_result(
@@ -957,7 +964,7 @@ Find the shortest path between two named concepts in the graph.
First check the graph exists:
```bash
python3 -c "
$(cat .graphify_python) -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.')
@@ -967,7 +974,7 @@ if not Path('graphify-out/graph.json').exists():
If it fails, stop and tell the user to run `/graphify <path>` first.
```bash
python3 -c "
$(cat .graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
@@ -1019,7 +1026,7 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
After writing the explanation, save it back:
```bash
python3 -c "
$(cat .graphify_python) -c "
from graphify.ingest import save_query_result
from pathlib import Path
save_query_result(
@@ -1041,7 +1048,7 @@ Give a plain-language explanation of a single node - everything connected to it.
First check the graph exists:
```bash
python3 -c "
$(cat .graphify_python) -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.')
@@ -1051,7 +1058,7 @@ if not Path('graphify-out/graph.json').exists():
If it fails, stop and tell the user to run `/graphify <path>` first.
```bash
python3 -c "
$(cat .graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
@@ -1096,7 +1103,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
python3 -c "
$(cat .graphify_python) -c "
from graphify.ingest import save_query_result
from pathlib import Path
save_query_result(
@@ -1117,7 +1124,7 @@ print('Explanation saved to graphify-out/memory/')
Fetch a URL and add it to the corpus, then update the graph.
```bash
python3 -c "
$(cat .graphify_python) -c "
import sys
from graphify.ingest import ingest
from pathlib import Path
+3 -5
View File
@@ -23,7 +23,6 @@ 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
@@ -51,7 +50,7 @@ def _rebuild_code(watch_path: Path) -> bool:
detection = {
"files": {"code": [str(f) for f in code_files], "document": [], "paper": [], "image": []},
"total_files": len(code_files),
"total_words": sum(len(f.read_text(errors="ignore").split()) for f in code_files),
"total_words": 0, # not needed during watch rebuild
}
G = build_from_json(result)
@@ -119,7 +118,7 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
last_trigger: float = 0.0
pending: bool = False
changed: list[Path] = []
changed: set[Path] = set()
class Handler(FileSystemEventHandler):
def on_any_event(self, event):
@@ -135,8 +134,7 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
return
last_trigger = time.monotonic()
pending = True
if path not in changed:
changed.append(path)
changed.add(path)
handler = Handler()
observer = Observer()
+13 -7
View File
@@ -4,15 +4,14 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.1.14"
description = "Claude Code skill - turn any folder of code, docs, papers, images, or tweets into a queryable knowledge graph"
version = "0.3.6"
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, OpenClaw) - turn any folder of code, docs, papers, or images into a queryable knowledge graph"
readme = "README.md"
license = { text = "MIT" }
keywords = ["claude", "claude-code", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
license = { file = "LICENSE" }
keywords = ["claude", "claude-code", "codex", "opencode", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
requires-python = ">=3.10"
dependencies = [
"networkx",
"graspologic",
"tree-sitter",
"tree-sitter-python",
"tree-sitter-javascript",
@@ -27,6 +26,11 @@ dependencies = [
"tree-sitter-kotlin",
"tree-sitter-scala",
"tree-sitter-php",
"tree-sitter-swift",
"tree-sitter-lua",
"tree-sitter-zig",
"tree-sitter-powershell",
"tree-sitter-elixir",
]
[project.urls]
@@ -39,7 +43,9 @@ mcp = ["mcp"]
neo4j = ["neo4j"]
pdf = ["pypdf", "html2text"]
watch = ["watchdog"]
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog"]
leiden = ["graspologic"]
office = ["python-docx", "openpyxl"]
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic", "python-docx", "openpyxl"]
[project.scripts]
graphify = "graphify.__main__:main"
@@ -49,4 +55,4 @@ where = ["."]
include = ["graphify*"]
[tool.setuptools.package-data]
graphify = ["skill.md"]
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-claw.md", "skill-windows.md"]
+28
View File
@@ -0,0 +1,28 @@
defmodule MyApp.Accounts.User do
@moduledoc """
Handles user accounts and authentication.
"""
alias MyApp.Repo
import Ecto.Query
defstruct [:id, :name, :email]
def create(attrs) do
%__MODULE__{}
|> validate(attrs)
|> Repo.insert()
end
def find(id) do
Repo.get(__MODULE__, id)
end
defp validate(user, attrs) do
if Map.has_key?(attrs, :email) do
user
else
{:error, :missing_email}
end
end
end
+32
View File
@@ -0,0 +1,32 @@
using namespace System.IO
using module MyModule
function Get-Data {
param(
[string]$Name,
[int]$Count = 10
)
$result = Process-Items -Name $Name -Count $Count
return $result
}
function Process-Items {
param([string]$Name, [int]$Count)
Write-Output "Processing $Count items for $Name"
}
class DataProcessor {
[string]$Source
DataProcessor([string]$source) {
$this.Source = $source
}
[string] Transform([string]$input) {
return $input.ToUpper()
}
[void] Save([string]$path) {
Set-Content -Path $path -Value $this.Source
}
}
+73
View File
@@ -0,0 +1,73 @@
import Foundation
import UIKit
protocol Processor {
func process() -> [String]
}
protocol Loggable {
func log()
}
class DataProcessor: Processor {
private var items: [String] = []
init() {}
deinit {}
func addItem(_ item: String) {
items.append(item)
}
func process() -> [String] {
return validate(items)
}
private func validate(_ data: [String]) -> [String] {
return data.filter { !$0.isEmpty }
}
}
struct Config {
let baseUrl: String
let timeout: Int
subscript(key: String) -> String? {
return nil
}
}
enum NetworkError {
case timeout
case connectionFailed
case unauthorized
func describe() -> String {
return "error"
}
}
actor CacheManager {
private var store: [String: String] = [:]
func get(_ key: String) -> String? {
return store[key]
}
}
extension DataProcessor: Loggable {
func log() {
print("logging")
}
}
extension Config {
func isValid() -> Bool {
return !baseUrl.isEmpty
}
}
func createProcessor() -> DataProcessor {
return DataProcessor()
}
+37
View File
@@ -0,0 +1,37 @@
const std = @import("std");
const mem = @import("std").mem;
const Point = struct {
x: f64,
y: f64,
pub fn distance(self: Point, other: Point) f64 {
const dx = self.x - other.x;
const dy = self.y - other.dy;
return std.math.sqrt(dx * dx + dy * dy);
}
};
const Color = enum {
red,
green,
blue,
};
const Shape = union(enum) {
circle: f64,
rect: Point,
};
pub fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn multiply(a: i32, b: i32) i32 {
return a * b;
}
pub fn main() void {
const result = add(1, 2);
_ = multiply(result, 3);
}
+39
View File
@@ -95,3 +95,42 @@ 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)
+35 -1
View File
@@ -1,5 +1,5 @@
from pathlib import Path
from graphify.detect import classify_file, count_words, detect, FileType, _looks_like_paper
from graphify.detect import classify_file, count_words, detect, FileType, _looks_like_paper, _is_ignored, _load_graphifyignore
FIXTURES = Path(__file__).parent / "fixtures"
@@ -69,3 +69,37 @@ def test_classify_attention_paper():
if paper_path.exists():
result = classify_file(paper_path)
assert result == FileType.PAPER
def test_graphifyignore_excludes_file(tmp_path):
"""Files matching .graphifyignore patterns are excluded from detect()."""
(tmp_path / ".graphifyignore").write_text("vendor/\n*.generated.py\n")
vendor = tmp_path / "vendor"
vendor.mkdir()
(vendor / "lib.py").write_text("x = 1")
(tmp_path / "main.py").write_text("print('hi')")
(tmp_path / "schema.generated.py").write_text("x = 1")
result = detect(tmp_path)
file_list = result["files"]["code"]
assert any("main.py" in f for f in file_list)
assert not any("vendor" in f for f in file_list)
assert not any("generated" in f for f in file_list)
assert result["graphifyignore_patterns"] == 2
def test_graphifyignore_missing_is_fine(tmp_path):
"""No .graphifyignore is not an error."""
(tmp_path / "main.py").write_text("x = 1")
result = detect(tmp_path)
assert result["graphifyignore_patterns"] == 0
def test_graphifyignore_comments_ignored(tmp_path):
"""Comment lines in .graphifyignore are not treated as patterns."""
(tmp_path / ".graphifyignore").write_text("# this is a comment\n\nmain.py\n")
(tmp_path / "main.py").write_text("x = 1")
(tmp_path / "other.py").write_text("x = 2")
result = detect(tmp_path)
assert not any("main.py" in f for f in result["files"]["code"])
assert any("other.py" in f for f in result["files"]["code"])
+2 -1
View File
@@ -60,7 +60,8 @@ def test_collect_files_from_dir():
files = collect_files(FIXTURES)
supported = {".py", ".js", ".ts", ".tsx", ".go", ".rs",
".java", ".c", ".cpp", ".cc", ".cxx", ".rb",
".cs", ".kt", ".kts", ".scala", ".php", ".h", ".hpp"}
".cs", ".kt", ".kts", ".scala", ".php", ".h", ".hpp",
".swift", ".lua", ".toc", ".zig", ".ps1", ".ex", ".exs"}
assert all(f.suffix in supported for f in files)
assert len(files) > 0
+34 -2
View File
@@ -2,7 +2,7 @@
import subprocess
from pathlib import Path
import pytest
from graphify.hooks import install, uninstall, status, _HOOK_MARKER
from graphify.hooks import install, uninstall, status, _HOOK_MARKER, _CHECKOUT_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
assert "removed" in result.lower()
def test_uninstall_no_hook(tmp_path):
@@ -78,3 +78,35 @@ 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
+159
View File
@@ -0,0 +1,159 @@
"""Tests for graphify install --platform routing."""
from pathlib import Path
from unittest.mock import patch
import pytest
PLATFORMS = {
"claude": (".claude/skills/graphify/SKILL.md",),
"codex": (".agents/skills/graphify/SKILL.md",),
"opencode": (".config/opencode/skills/graphify/SKILL.md",),
"claw": (".claw/skills/graphify/SKILL.md",),
}
def _install(tmp_path, platform):
from graphify.__main__ import install
with patch("graphify.__main__.Path.home", return_value=tmp_path):
install(platform=platform)
def test_install_default_claude(tmp_path):
_install(tmp_path, "claude")
assert (tmp_path / ".claude" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_codex(tmp_path):
_install(tmp_path, "codex")
assert (tmp_path / ".agents" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_opencode(tmp_path):
_install(tmp_path, "opencode")
assert (tmp_path / ".config" / "opencode" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_claw(tmp_path):
_install(tmp_path, "claw")
assert (tmp_path / ".claw" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_unknown_platform_exits(tmp_path):
with pytest.raises(SystemExit):
_install(tmp_path, "unknown")
def test_codex_skill_contains_spawn_agent():
"""Codex skill file must reference spawn_agent."""
import graphify
skill = (Path(graphify.__file__).parent / "skill-codex.md").read_text()
assert "spawn_agent" in skill
def test_opencode_skill_contains_mention():
"""OpenCode skill file must reference @mention."""
import graphify
skill = (Path(graphify.__file__).parent / "skill-opencode.md").read_text()
assert "@mention" in skill
def test_claw_skill_is_sequential():
"""OpenClaw skill file must describe sequential extraction."""
import graphify
skill = (Path(graphify.__file__).parent / "skill-claw.md").read_text()
assert "sequential" in skill.lower()
assert "spawn_agent" not in skill
assert "@mention" not in skill
def test_all_skill_files_exist_in_package():
"""All four platform skill files must be present in the installed package."""
import graphify
pkg = Path(graphify.__file__).parent
for name in ("skill.md", "skill-codex.md", "skill-opencode.md", "skill-claw.md"):
assert (pkg / name).exists(), f"Missing: {name}"
def test_claude_install_registers_claude_md(tmp_path):
"""Claude platform install writes CLAUDE.md; others do not."""
_install(tmp_path, "claude")
assert (tmp_path / ".claude" / "CLAUDE.md").exists()
def test_codex_install_does_not_write_claude_md(tmp_path):
_install(tmp_path, "codex")
assert not (tmp_path / ".claude" / "CLAUDE.md").exists()
# --- always-on AGENTS.md install/uninstall tests ---
def _agents_install(tmp_path, platform):
from graphify.__main__ import _agents_install as _install_fn
_install_fn(tmp_path, platform)
def _agents_uninstall(tmp_path):
from graphify.__main__ import _agents_uninstall as _uninstall_fn
_uninstall_fn(tmp_path)
def test_codex_agents_install_writes_agents_md(tmp_path):
_agents_install(tmp_path, "codex")
agents_md = tmp_path / "AGENTS.md"
assert agents_md.exists()
assert "graphify" in agents_md.read_text()
assert "GRAPH_REPORT.md" in agents_md.read_text()
def test_opencode_agents_install_writes_agents_md(tmp_path):
_agents_install(tmp_path, "opencode")
assert (tmp_path / "AGENTS.md").exists()
def test_claw_agents_install_writes_agents_md(tmp_path):
_agents_install(tmp_path, "claw")
assert (tmp_path / "AGENTS.md").exists()
def test_agents_install_idempotent(tmp_path):
"""Installing twice does not duplicate the section."""
_agents_install(tmp_path, "codex")
_agents_install(tmp_path, "codex")
content = (tmp_path / "AGENTS.md").read_text()
assert content.count("## graphify") == 1
def test_agents_install_appends_to_existing(tmp_path):
"""Installs into an existing AGENTS.md without overwriting other content."""
agents_md = tmp_path / "AGENTS.md"
agents_md.write_text("# Existing rules\n\nDo not break things.\n")
_agents_install(tmp_path, "codex")
content = agents_md.read_text()
assert "Do not break things." in content
assert "## graphify" in content
def test_agents_uninstall_removes_section(tmp_path):
_agents_install(tmp_path, "codex")
_agents_uninstall(tmp_path)
agents_md = tmp_path / "AGENTS.md"
# File deleted when it only contained graphify section
assert not agents_md.exists()
def test_agents_uninstall_preserves_other_content(tmp_path):
"""Uninstall keeps pre-existing content."""
agents_md = tmp_path / "AGENTS.md"
agents_md.write_text("# Existing rules\n\nDo not break things.\n")
_agents_install(tmp_path, "codex")
_agents_uninstall(tmp_path)
assert agents_md.exists()
content = agents_md.read_text()
assert "Do not break things." in content
assert "## graphify" not in content
def test_agents_uninstall_no_op_when_not_installed(tmp_path, capsys):
_agents_uninstall(tmp_path)
out = capsys.readouterr().out
assert "nothing to do" in out
+155 -1
View File
@@ -1,10 +1,11 @@
"""Tests for the 8 new language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP."""
"""Tests for language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift."""
from __future__ import annotations
from pathlib import Path
import pytest
from graphify.extract import (
extract_java, extract_c, extract_cpp, extract_ruby,
extract_csharp, extract_kotlin, extract_scala, extract_php,
extract_swift,
)
FIXTURES = Path(__file__).parent / "fixtures"
@@ -217,3 +218,156 @@ def test_php_finds_function():
def test_php_finds_imports():
r = extract_php(FIXTURES / "sample.php")
assert "imports" in _relations(r)
# ── Swift ────────────────────────────────────────────────────────────────────
def test_swift_no_error():
r = extract_swift(FIXTURES / "sample.swift")
assert "error" not in r
def test_swift_finds_class():
r = extract_swift(FIXTURES / "sample.swift")
assert any("DataProcessor" in l for l in _labels(r))
def test_swift_finds_protocol():
r = extract_swift(FIXTURES / "sample.swift")
assert any("Processor" in l for l in _labels(r))
def test_swift_finds_struct():
r = extract_swift(FIXTURES / "sample.swift")
assert any("Config" in l for l in _labels(r))
def test_swift_finds_methods():
r = extract_swift(FIXTURES / "sample.swift")
labels = _labels(r)
assert any("addItem" in l for l in labels)
assert any("process" in l for l in labels)
def test_swift_finds_function():
r = extract_swift(FIXTURES / "sample.swift")
assert any("createProcessor" in l for l in _labels(r))
def test_swift_finds_imports():
r = extract_swift(FIXTURES / "sample.swift")
assert "imports" in _relations(r)
def test_swift_no_dangling_edges():
r = extract_swift(FIXTURES / "sample.swift")
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids
def test_swift_finds_actor():
r = extract_swift(FIXTURES / "sample.swift")
assert any("CacheManager" in l for l in _labels(r))
def test_swift_finds_enum():
r = extract_swift(FIXTURES / "sample.swift")
assert any("NetworkError" in l for l in _labels(r))
def test_swift_finds_enum_methods():
r = extract_swift(FIXTURES / "sample.swift")
assert any("describe" in l for l in _labels(r))
def test_swift_finds_enum_cases():
r = extract_swift(FIXTURES / "sample.swift")
labels = _labels(r)
assert any("timeout" in l for l in labels)
assert any("connectionFailed" in l for l in labels)
def test_swift_enum_cases_have_case_of_edge():
r = extract_swift(FIXTURES / "sample.swift")
case_edges = [e for e in r["edges"] if e["relation"] == "case_of"]
assert len(case_edges) >= 2
def test_swift_finds_deinit():
r = extract_swift(FIXTURES / "sample.swift")
assert any("deinit" in l for l in _labels(r))
def test_swift_finds_subscript():
r = extract_swift(FIXTURES / "sample.swift")
assert any("subscript" in l for l in _labels(r))
def test_swift_extension_methods_attach_to_type():
r = extract_swift(FIXTURES / "sample.swift")
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
method_edges = [e for e in r["edges"] if e["relation"] == "method"]
found = False
for e in method_edges:
src_label = node_by_id.get(e["source"], "")
tgt_label = node_by_id.get(e["target"], "")
if "Config" in src_label and "isValid" in tgt_label:
found = True
break
assert found, "extension method isValid should attach to Config"
def test_swift_extension_does_not_duplicate_type_node():
r = extract_swift(FIXTURES / "sample.swift")
config_nodes = [n for n in r["nodes"] if n["label"] == "Config"]
assert len(config_nodes) == 1, f"Config should appear once, got {len(config_nodes)}"
def test_swift_conformance_edge():
r = extract_swift(FIXTURES / "sample.swift")
inherits_edges = [e for e in r["edges"] if e["relation"] == "inherits"]
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
found = False
for e in inherits_edges:
src_label = node_by_id.get(e["source"], "")
tgt_label = node_by_id.get(e["target"], "")
if "DataProcessor" in src_label and "Processor" in tgt_label:
found = True
break
assert found, "DataProcessor should have inherits edge to Processor"
def test_swift_extension_conformance_edge():
r = extract_swift(FIXTURES / "sample.swift")
inherits_edges = [e for e in r["edges"] if e["relation"] == "inherits"]
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
found = False
for e in inherits_edges:
src_label = node_by_id.get(e["source"], "")
tgt_label = node_by_id.get(e["target"], "")
if "DataProcessor" in src_label and "Loggable" in tgt_label:
found = True
break
assert found, "extension should add conformance edge DataProcessor -> Loggable"
def test_swift_emits_calls():
r = extract_swift(FIXTURES / "sample.swift")
calls = _calls(r)
assert any("process" in src and "validate" in tgt for src, tgt in calls)
# ── Elixir ────────────────────────────────────────────────────────────────────
from graphify.extract import extract_elixir
def test_elixir_finds_module():
r = extract_elixir(FIXTURES / "sample.ex")
assert "error" not in r
labels = [n["label"] for n in r["nodes"]]
assert any("MyApp.Accounts.User" in l for l in labels)
def test_elixir_finds_functions():
r = extract_elixir(FIXTURES / "sample.ex")
labels = [n["label"] for n in r["nodes"]]
assert any("create" in l for l in labels)
assert any("find" in l for l in labels)
assert any("validate" in l for l in labels)
def test_elixir_finds_imports():
r = extract_elixir(FIXTURES / "sample.ex")
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
assert len(import_edges) >= 2
def test_elixir_finds_calls():
r = extract_elixir(FIXTURES / "sample.ex")
calls = {(e["source"], e["target"]) for e in r["edges"] if e["relation"] == "calls"}
labels = {n["id"]: n["label"] for n in r["nodes"]}
assert any("create" in labels.get(src, "") and "validate" in labels.get(tgt, "") for src, tgt in calls)
def test_elixir_method_edges():
r = extract_elixir(FIXTURES / "sample.ex")
methods = [e for e in r["edges"] if e["relation"] == "method"]
assert len(methods) >= 3
+89
View File
@@ -0,0 +1,89 @@
"""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)
+24 -25
View File
@@ -1,6 +1,6 @@
# Reproducible Example
A small document pipeline (parser, validator, processor, storage, API) with architecture notes and research notes. Six files, two languages, clear call relationships between modules.
A small document pipeline — parser, validator, processor, storage, API — with architecture notes and research notes. Seven files, two languages, clear call relationships between modules.
Run graphify on it and you get a knowledge graph showing how the modules connect, which functions call which, and how the architecture notes relate to the code.
@@ -8,50 +8,49 @@ Run graphify on it and you get a knowledge graph showing how the modules connect
```
raw/
├── parser.py reads files, detects format, kicks off the pipeline
├── validator.py schema checks, calls processor for text normalization
├── processor.py keyword extraction, cross-reference detection
├── storage.py persists everything, maintains the index
├── api.py HTTP handlers that orchestrate the above four modules
├── architecture.md design decisions and module responsibilities
└── notes.md open questions and tradeoffs, written informally
├── parser.py — reads files, detects format, kicks off the pipeline
├── validator.py — schema checks, calls processor for text normalization
├── processor.py — keyword extraction, cross-reference detection
├── storage.py — persists everything, maintains the index
├── api.py — HTTP handlers that orchestrate the above four modules
├── architecture.md — design decisions and module responsibilities
└── notes.md — open questions and tradeoffs
```
## How to run it
## How to run
```bash
pip install graphifyy && graphify install
pip install graphifyy
graphify install # Claude Code
graphify install --platform codex # Codex
graphify install --platform opencode # OpenCode
graphify install --platform claw # OpenClaw
```
Then open Claude Code in this directory and type:
Then open your AI coding assistant in this directory and type:
```
/graphify ./raw
```
Takes under a minute. No PDF or image extraction, so it runs entirely on AST and markdown parsing with no token cost for semantic extraction.
No PDF or image extraction — runs entirely on AST and markdown with no token cost for semantic extraction.
## What to expect
The graph should show:
- api.py as a hub node connected to all four modules
- parser.py calling validator.py and storage.py
- validator.py calling processor.py for normalize_text
- processor.py calling storage.py for load_index and save_processed
- architecture.md and notes.md linked to the code modules they discuss
The community detection will likely cluster the four Python modules together and the two markdown files together, or split api.py into its own cluster given its high connectivity.
God nodes will be storage.py (everything reads and writes through it) and api.py (connects to everything at the top level).
- `api.py` as a hub node connected to all four modules
- `storage.py` as the highest-degree god node (everything reads and writes through it)
- `parser.py` calling `validator.py` and `storage.py`
- `architecture.md` and `notes.md` linked to the code modules they discuss
- 2 communities: the four Python modules together, the two markdown files together (or api.py in its own cluster given high connectivity)
## After it runs
Ask questions in Claude Code and it answers from the graph:
Ask questions from your AI coding assistant:
- "what calls storage directly?"
- "what is the shortest path between parser and processor?"
- "which module has the most connections?"
- "what does the architecture doc say about the storage design?"
The graph lives in graphify-out/ and persists across sessions.
The graph lives in `graphify-out/` and persists across sessions.
+21 -22
View File
@@ -1,44 +1,43 @@
# httpx Corpus Benchmark — How to Reproduce
# httpx Corpus Benchmark
A synthetic 6-file Python codebase modeled after httpx's architecture. Tests graphify
on a realistic library codebase with clean layering: exceptions → models → auth/transport → client.
A synthetic 6-file Python codebase modeled after httpx's architecture. Tests graphify on a realistic library with clean layering: exceptions → models → auth/transport → client.
## Corpus (6 files)
All input files are in `raw/`:
```
raw/
├── exceptions.py — full HTTPError hierarchy (RequestError, TransportError, HTTPStatusError, etc.)
├── models.py — URL, Headers, Cookies, Request, Response with raise_for_status
├── auth.py — BasicAuth, BearerAuth, DigestAuth (challenge-response), NetRCAuth
├── utils.py — header normalization, query param flattening, content-type parsing
├── transport.py — ConnectionPool, HTTPTransport, AsyncHTTPTransport, MockTransport, ProxyTransport
└── client.py — Timeout, Limits, BaseClient, Client (sync), AsyncClient
├── exceptions.py — HTTPError hierarchy
├── models.py — URL, Headers, Cookies, Request, Response
├── auth.py — BasicAuth, BearerAuth, DigestAuth, NetRCAuth
├── utils.py — header normalization, query params, content-type parsing
├── transport.py — ConnectionPool, HTTPTransport, AsyncHTTPTransport, MockTransport
└── client.py — Timeout, Limits, BaseClient, Client, AsyncClient
```
## How to run
```bash
pip install graphifyy && graphify install
/graphify ./raw
pip install graphifyy
graphify install # Claude Code
graphify install --platform codex # Codex
graphify install --platform opencode # OpenCode
graphify install --platform claw # OpenClaw
```
Or from the CLI directly:
Then open your AI coding assistant in this directory and type:
```bash
pip install graphifyy
graphify ./raw
```
/graphify ./raw
```
## What to expect
- 144 nodes, 330 edges, 6 communities
- God nodes: `Client`, `AsyncClient`, `Response`, `Request`, `BaseClient`, `HTTPTransport`
- Surprising connections: `DigestAuth` ↔ `Response` (auth.py reads Response to parse WWW-Authenticate)
- **~1x token reduction** — 6 files fits in a context window, so there's no compression win here
- Surprising connection: `DigestAuth` linked to `Response` — auth.py reads Response to parse WWW-Authenticate headers
- Token reduction: ~1x — 6 files fits in a context window, so there is no compression win here
The graph value on a small corpus is structural, not compressive: you can see the full dependency graph, identify god nodes, and understand architecture at a glance. For token reduction to matter you need 20+ files. At 52 files (Karpathy repos benchmark) graphify achieves 71.5x.
The graph value on a small corpus is structural, not compressive: you can see the full dependency graph, identify god nodes, and understand architecture at a glance. Token reduction scales with corpus size — at 52 files (Karpathy benchmark) graphify achieves 71.5x.
Run `graphify benchmark worked/httpx/graph.json` to verify the numbers yourself.
Actual output is already in this folder: `GRAPH_REPORT.md` (human-readable) and `graph.json` (full graph data).
Run `graphify benchmark worked/httpx/graph.json` to verify the numbers. Actual output is in this folder: `GRAPH_REPORT.md` and `graph.json`. Full eval: `review.md`.
+19 -9
View File
@@ -1,6 +1,6 @@
# Karpathy Repos Benchmark — How to Reproduce
# Karpathy Repos Benchmark
This is the corpus that produced the 71.5x token reduction benchmark.
This is the corpus that produced the **71.5x token reduction** benchmark.
## Corpus (52 files)
@@ -33,9 +33,9 @@ Put all files into a single folder called `raw/`:
```
raw/
├── nanoGPT/ (cloned repo)
├── minGPT/ (cloned repo)
├── micrograd/ (cloned repo)
├── nanoGPT/
├── minGPT/
├── micrograd/
├── attention.pdf
├── flashattention.pdf
├── flashattention2.pdf
@@ -46,10 +46,20 @@ raw/
└── moon_mlp.png
```
Then in Claude Code:
Install and set up the skill for your platform:
```bash
pip install graphifyy
graphify install # Claude Code
graphify install --platform codex # Codex
graphify install --platform opencode # OpenCode
graphify install --platform claw # OpenClaw
```
Then open your AI coding assistant in this directory and type:
```
pip install graphifyy && graphify install
/graphify ./raw
```
@@ -58,6 +68,6 @@ pip install graphifyy && graphify install
- ~285 nodes, ~340 edges, ~17 meaningful communities
- God nodes: `Value` (micrograd), `GPT` (nanoGPT), `Training Script`, `Layer`
- Surprising connections: nanoGPT Block and minGPT Block linked across repos, FlashAttention paper bridging into CausalSelfAttention in both repos
- Token reduction: 71.5x vs reading all 52 files cold
- Token reduction: 71.5x vs reading all 52 files directly
Full eval with scores and analysis: `review.md`
Actual output is in this folder: `GRAPH_REPORT.md` and `graph.json`. Full eval with scores: `review.md`.
+19 -21
View File
@@ -1,45 +1,43 @@
# Mixed Corpus Benchmark — How to Reproduce
# Mixed Corpus Benchmark
A small but realistic mixed-input corpus: Python source files, a markdown paper with
arXiv citations, and one image. Tests graphify's ability to handle different file types
in a single run.
A small mixed-input corpus: Python source files, a markdown paper with arXiv citations, and one image. Tests graphify on different file types in a single run.
## Corpus (5 files)
All input files are in `raw/`:
```
raw/
├── analyze.py — graphify's graph analysis module (god_nodes, surprising_connections, etc.)
├── build.py — graphify's graph builder (build_from_json, networkx wrapper)
├── cluster.py — graphify's Leiden community detection (cluster, score_all)
├── attention_notes.md — Transformer paper notes (Vaswani et al., 2017), with arXiv citation
├── analyze.py — graph analysis module (god_nodes, surprising_connections)
├── build.py — graph builder (build_from_json, NetworkX wrapper)
├── cluster.py — Leiden community detection (cluster, score_all)
├── attention_notes.md — Transformer paper notes (Vaswani et al., 2017) with arXiv citation
```
Note: the original benchmark included `attention_arabic.png` (an Arabic-language figure from the
Attention paper). PNG files are not stored in this repo. To reproduce with the image, save any
diagram or figure from the Attention Is All You Need paper as `raw/attention_arabic.png`.
Note: the original benchmark included `attention_arabic.png` (an Arabic-language figure from the Attention paper). PNG files are not stored in this repo. To reproduce with the image, save any diagram from the Attention Is All You Need paper as `raw/attention_arabic.png`.
## How to run
```bash
pip install graphifyy && graphify install
/graphify ./raw
pip install graphifyy
graphify install # Claude Code
graphify install --platform codex # Codex
graphify install --platform opencode # OpenCode
graphify install --platform claw # OpenClaw
```
Or from the CLI directly:
Then open your AI coding assistant in this directory and type:
```bash
pip install graphifyy
graphify ./raw
```
/graphify ./raw
```
## What to expect
- ~20 nodes, ~19 edges from AST alone (3 Python modules)
- 3 communities: Graph Analysis, Clustering & Scoring, Graph Building
- 3 communities: Graph Analysis, Clustering and Scoring, Graph Building
- God nodes: `analyze.py`, `cluster.py`, `build.py`
- `attention_notes.md` classified as `paper` (arXiv heuristic fires on `1706.03762`)
- If you include the image: 1 extra node describing the figure content via vision
- Token reduction: 5.4x
Full eval with scores and analysis: `review.md`
Actual output is in this folder: `GRAPH_REPORT.md` and `graph.json`. Full eval: `review.md`.