Compare commits

...
28 Commits
Author SHA1 Message Date
SafiandClaude Sonnet 4.6 2736e05714 Bump to 0.4.14, README: cross-file call-graph note
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-15 00:28:18 +01:00
SafiandClaude Sonnet 4.6 5c77d9cc4a Fix 9 issues: kiro package data, betweenness perf, wiki step, opencode plugin, cache root, PHP missing edges, Windows stability, cross-file calls
- #352: add skill-kiro.md to pyproject.toml package-data
- #341: guard edge_betweenness at >5000 nodes; use approximate k=100 for suggest_questions on large graphs
- #354/#229: add Step 6b in skill.md to call to_wiki() when --wiki given (before Step 9 cleanup)
- #356: call _install_opencode_plugin() from install --platform opencode path
- #350: add cache_root param to extract() so subdirectory runs keep cache at ./graphify-out/cache/
- #230: PHP class_constant_access_expression emits references_constant edges
- #232: PHP scoped_call_expression (static method calls) emits calls edges
- #287: os.replace fallback for Windows WinError 5; graphify update exits 1 on failure; templates use graphify update . instead of python3 -c
- #348: cross-file call resolution for all languages via raw_calls + global label map pass in extract()

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-15 00:26:11 +01:00
Safi 9c04b059be docs: add Verilog/SystemVerilog to language count and list 2026-04-14 09:36:57 +01:00
SafiandClaude Sonnet 4.6 79a9200f09 v0.4.13: Verilog support, HiDPI hyperedge fix, null label guards, AGENTS.md python3 fix
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 09:28:01 +01:00
SafiandClaude Sonnet 4.6 41544c7076 Update pyproject.toml description and keywords to include all platforms
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 22:49:01 +01:00
SafiandClaude Sonnet 4.6 c657eb2049 v0.4.12: add Kiro IDE/CLI support, fix cache portability across machines
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 22:46:13 +01:00
SafiandClaude Sonnet 4.6 9fd6810e4e Fix README: Codex does have PreToolUse hook support (#299)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 22:33:33 +01:00
SafiandClaude Sonnet 4.6 e441454c55 v0.4.11: fix query crash on MultiGraph, NoneType in serve.py, MCP CWD path bug, .graphifyignore subfolder patterns; v0.4.10: Dart, Hermes, 6 CLI commands, PHP improvements
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 12:48:47 +01:00
Safi 962f28c603 docs: add Hermes platform, Dart to language list, 22→23 languages 2026-04-13 08:46:20 +01:00
SafiandClaude Sonnet 4.6 7c81c1b889 release: v0.4.9 — PHP extractor improvements, Dart, diacritics, Hermes, fixes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 08:39:28 +01:00
SafiandClaude Sonnet 4.6 04e2960135 Remove Claude-specific language from platform skill files (0.4.8)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 21:18:20 +01:00
SafiandClaude Sonnet 4.6 c713cf89fd Fix watch edge key, claw path, Blade support, WSL MCP docs (0.4.7)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 20:49:24 +01:00
SafiandClaude Sonnet 4.6 6b2d38358b Add Google Antigravity platform support (0.4.6)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 19:16:49 +01:00
SafiandClaude Sonnet 4.6 2499a1c377 fix MCP ValidationError on blank stdin lines and bump to 0.4.5
Some MCP clients send blank lines between JSON messages. The stdio
transport tried to parse every line as JSONRPCMessage, crashing with
a Pydantic ValidationError. _filter_blank_stdin() installs an OS-level
pipe that relays stdin while silently dropping blank-only lines.

Closes #201

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 18:48:29 +01:00
SafiandClaude Sonnet 4.6 0a4e6915c1 fix #261, #249, #266 and bump to 0.4.4
- watch.py: preserve INFERRED/AMBIGUOUS edges (code<->doc) across rebuilds (#261)
- __main__.py: fix Codex hook - use additionalContext instead of permissionDecision:allow (#249)
- detect.py: skip common lockfiles (package-lock.json, yarn.lock, Cargo.lock etc.) (#266)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 18:37:54 +01:00
Safi efce74dada update README: 22 languages, add .vue and .svelte to file types table 2026-04-12 13:02:45 +01:00
SafiandClaude Sonnet 4.6 4205ae86cb fix bugs #256, #253, #244, #226, #254 and bump to 0.4.3
- extract.py: resolve relative JS/TS imports to full-path IDs (fixes 0 import edges on TS codebases) (#256)
- extract.py: resolve relative Python imports to full-path IDs (#256)
- watch.py: merge fresh AST with existing semantic nodes instead of overwriting (#253)
- hooks.py: add python fallback after python3 for Windows; exit 0 if neither found (#244)
- analyze.py: guard stale _src/_tgt hints with node membership check (#226)
- detect.py + extract.py: add .vue and .svelte to CODE_EXTENSIONS and _DISPATCH (#254)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 12:59:15 +01:00
Safi 013313f8d6 add LinkedIn badge to README 2026-04-11 21:15:32 +01:00
Safi b4d4ac8e9b add 0.4.2 CHANGELOG entry 2026-04-11 21:10:45 +01:00
SafiandClaude Sonnet 4.6 62aac4f868 cherry-pick PRs #212, #220, #204, #221 into 0.4.2
- build/validate: accept NetworkX <=3.1 "links" key alongside "edges" (#212)
- __main__: skip version check during install/uninstall, deduplicate paths (#220)
- all file IO: explicit encoding="utf-8" to prevent crashes on Windows CJK locales (#204)
- hooks: add newline="\n" on write to prevent CRLF shebang breakage on Windows (#204)
- export: strip trailing .md from safe_name so "CLAUDE.md" doesn't become "CLAUDE.md.md" (#221)
- report: add Community Hubs navigation block so Obsidian vault stays connected (#221)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-11 21:07:39 +01:00
SafiandClaude Sonnet 4.6 3c503400cb fix bugs #211, #216, #217, #222 and bump to 0.4.2
- extract.py: use str(path) for node IDs to prevent same-basename collision (#211)
- build.py: normalize from/to edge keys before KeyError (#216)
- export.py: guard ZeroDivisionError when graph has no edges (#217)
- hooks.py: remove stale CODE_EXTS filter, rebuild on any changed file (#222)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-11 20:53:08 +01:00
SafiandClaude Sonnet 4.6 625ca0e2f3 Bump to 0.4.1
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 18:43:18 +01:00
SafiandClaude Sonnet 4.6 271ee0aff6 Fix #188: collect_files() now respects .graphifyignore; fix #195: skill.md requires general-purpose subagent type for extraction dispatch
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 18:41:48 +01:00
SafiandClaude Sonnet 4.6 0e453083de Remove YouTube URL references from README, use generic <video-url> placeholder
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 16:24:13 +01:00
SafiandClaude Sonnet 4.6 209224d08c Add dedicated video and audio corpus section to README
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 16:22:53 +01:00
SafiandClaude Sonnet 4.6 fa388c8556 Security: fix YAML injection in ingest.py, </script> injection in export.py, bound collision loop
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 16:07:51 +01:00
SafiandClaude Sonnet 4.6 3ce9bdabf4 Add v4 to CI branch triggers
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 16:01:14 +01:00
SafiandClaude Sonnet 4.6 68bb2bd3dc Bump to 0.4.0, set v4 as working branch, update CI badge and skill URL
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 15:59:43 +01:00
38 changed files with 2871 additions and 239 deletions

No files matched your search

+2 -2
View File
@@ -2,9 +2,9 @@ name: CI
on:
push:
branches: ["v1", "v2", "v3", "main"]
branches: ["v1", "v2", "v3", "v4", "main"]
pull_request:
branches: ["v1", "v2", "v3", "main"]
branches: ["v1", "v2", "v3", "v4", "main"]
jobs:
test:
+99
View File
@@ -2,6 +2,105 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
## 0.4.13 (2026-04-14)
- Add: Verilog/SystemVerilog support — `.v` and `.sv` files extracted via tree-sitter-verilog (modules, functions, tasks, package imports, module instantiations with `instantiates` edges) (#325)
- Fix: hyperedge polygons render correctly on HiDPI/Retina displays — `afterDrawing` callback ctx is now used directly (already in network coordinate space), removing the double-applied transform and incorrect `canvas.width/2` DPR anchor (#334)
- Fix: AGENTS.md and GEMINI.md rebuild rule now uses `graphify update .` instead of hardcoded `python3 -c "..."` — correct Python is resolved through the graphify binary, no more interpreter mismatches in Nix/pipx/uv environments (#324)
- Fix: `graphify query` and `graphify explain` no longer crash with `AttributeError` when a node has `label: null` — all `.get("label", "")` calls guarded with `or ""` to handle explicit null values (#323)
## 0.4.12 (2026-04-13)
- Add: Kiro IDE/CLI support — `graphify kiro install` writes `.kiro/skills/graphify/SKILL.md` (invoked via `/graphify`) and `.kiro/steering/graphify.md` (`inclusion: always` — always-on context before every conversation) (#319, #321)
- Fix: cache `file_hash()` now uses the path relative to project root instead of the resolved absolute path — cache entries are now portable across machines, CI runners, and different checkout directories (#311)
## 0.4.11 (2026-04-13)
- Fix: `graphify query` no longer crashes with `ValueError` on MultiGraph graphs — `G.edges[u, v]` replaced with `G[u][v]` + MultiGraph guard (#305)
- Fix: `graphify query` no longer crashes with `AttributeError: 'NoneType' has no attribute 'lower'` when a node has a null `source_file` (#307)
- Fix: MCP server launched from a different directory now correctly derives the `graphify-out` base from the absolute path provided, instead of CWD (#309)
- Fix: `.graphifyignore` patterns from a parent directory now fire correctly when graphify is run on a subfolder — patterns are matched against paths relative to both the scan root and the `.graphifyignore`'s anchor directory (#303)
## 0.4.10 (2026-04-13)
- Fix: `graphify install --platform cursor` no longer crashes — passes `Path(".")` to `_cursor_install` (#281)
- Fix: `_agents_uninstall` now only removes the OpenCode plugin when uninstalling the `opencode` platform — other platforms were incorrectly having their OpenCode plugin stripped (#276)
- Fix: misleading comment in query `--graph` path handler removed (#278)
- Fix: `skill-codex.md` — `wait` → `wait_agent` (correct Codex tool name) (#273)
- Add: `svg = ["matplotlib"]` optional extra in pyproject.toml; `matplotlib` added to `[all]` extra (#288)
- Fix: `graspologic` dependency now has `python_version < '3.13'` env marker in `leiden` and `all` extras — prevents install failures on Python 3.13+ (#290)
- Add: Dart/Flutter support — `.dart` files extracted via regex (classes, mixins, functions, imports); added to `CODE_EXTENSIONS` (#292)
- Add: `norm_label` field written at build time in `to_json()` for diacritic-insensitive search; `_score_nodes` and `_find_node` in `serve.py` use `norm_label` with Unicode NFKD normalization fallback (#293)
- Add: Hermes Agent platform support — `graphify hermes install` writes skill to `~/.hermes/skills/graphify/SKILL.md` and AGENTS.md (#251)
- Add: PHP extractor now captures static property access (`Foo::$bar`) as `uses_static_prop` edges (#234)
- Add: PHP extractor now captures `config()` helper calls as `uses_config` edges pointing to the first config key segment (#236)
- Add: PHP extractor now captures service container bindings (`bind`, `singleton`, `scoped`, `instance`) as `bound_to` edges (#238)
- Add: PHP extractor now captures `$listen` / `$subscribe` event listener arrays as `listened_by` edges (#240)
- Add: `prune_dangling_edges()` utility in `export.py` — removes edges whose source/target is not in the node set (#294)
- Fix: Antigravity install injects YAML frontmatter into skill file for native tool discovery; rules now include MCP navigation hint; prints MCP config snippet (#268)
- Fix: Windows hook tests now use platform-aware assertions instead of POSIX executable bit checks (#279)
- Add: CLI commands `path`, `explain`, `add`, `watch`, `update`, `cluster-only` now work as bare terminal commands (not just AI skill invocations) — documented in `--help` output (#277)
## 0.4.8 (2026-04-12)
- Fix: platform skill files (aider, codex, opencode, claw, droid, copilot, windows) no longer contain Claude-specific language — references to "Claude" as the AI model replaced with platform-agnostic wording (#272)
## 0.4.7 (2026-04-12)
- Fix: `watch` semantic edge preservation was always empty — `graph.json` uses `links` key but code read `edges` (#269)
- Fix: `graphify claw install` now writes to `.openclaw/` (correct OpenClaw directory) instead of `.claw/` (#208)
- Add: Blade template support — `@include`, `<livewire:>` components, and `wire:click` bindings extracted from `.blade.php` files (#242)
- Docs: WSL/Linux MCP setup note — package name is `graphifyy`, use `.venv/bin/python3` in `.mcp.json` (#250)
## 0.4.6 (2026-04-12)
- Add: Google Antigravity support — `graphify antigravity install` writes `.agent/rules/graphify.md` (always-on rules) and `.agent/workflows/graphify.md` (`/graphify` slash command) (#203, #199, #53)
## 0.4.5 (2026-04-12)
- Fix: MCP server no longer crashes with `ValidationError` on blank lines sent between JSON messages by some clients (#201)
## 0.4.4 (2026-04-12)
- Fix: `watch` now preserves INFERRED/AMBIGUOUS edges (code↔doc rationale links) across rebuilds — previously all cross-type edges were dropped (#261)
- Fix: Codex hook no longer emits `permissionDecision:allow` which codex-cli 0.120.0 rejects (#249)
- Fix: Common lockfiles (`package-lock.json`, `yarn.lock`, `Cargo.lock`, etc.) are now skipped during detection, preventing token drain on large JS/Rust/Python projects (#266)
## 0.4.3 (2026-04-12)
- Fix: JS/TS relative imports now resolve to full-path node IDs — previously all `imports_from` edges were silently dropped on large TypeScript codebases (#256)
- Fix: Python relative imports (`from .foo import bar`) now resolve correctly to full-path node IDs (#256)
- Fix: `watch --rebuild_code` now merges fresh AST with existing semantic nodes from docs/papers instead of overwriting them (#253)
- Fix: Windows hooks now fall back to `python` if `python3` is not found; exits cleanly if neither has graphify installed (#244)
- Fix: `surprising_connections` / `suggest_questions` no longer crash with `KeyError` on stale `_src`/`_tgt` edge hints after node merges (#226)
- Add: `.vue` and `.svelte` files now recognized as code and included in extraction (#254)
## 0.4.2 (2026-04-11)
- Fix: same-basename files in different directories produced colliding node IDs — now uses full path (#211)
- Fix: edges using `from`/`to` keys instead of `source`/`target` were silently dropped (#216)
- Fix: empty graphs (no edges) crashed `to_html` with `ZeroDivisionError` (#217)
- Fix: post-commit hook skipped `.tsx`, `.jsx`, and other valid code extensions due to stale allowlist (#222)
- Fix: NetworkX ≤3.1 serialises edges as `links` — now accepted alongside `edges` (#212)
- Fix: version warning fired during `install`/`uninstall` and duplicated on shared paths (#220)
- Fix: all file IO now uses `encoding="utf-8"` — prevents crashes on Windows with CJK or emoji labels; hook writes use `newline="\n"` to prevent CRLF shebang breakage (#204)
- Fix: Obsidian export — node labels ending in `.md` produced `.md.md` filenames; `GRAPH_REPORT.md` now links to community hub files so vault stays in one connected component (#221)
## 0.4.1 (2026-04-10)
- Fix: `collect_files()` in `extract.py` now respects `.graphifyignore` — previously ignored patterns, causing thousands of unwanted files (e.g. `node_modules/`) to be scanned (#188)
- Fix: skill.md Step B2 now explicitly requires `subagent_type="general-purpose"` — using `Explore` type silently dropped extraction results since it is read-only and cannot write chunk files (#195)
- Fix: Step B3 now warns when chunk files are missing from disk instead of silently skipping them
## 0.4.0 (2026-04-10)
- Branch: v4 — video and audio corpus support
- Add: drop `.mp4`, `.mp3`, `.wav`, `.mov`, `.webm`, `.m4a`, `.ogg`, `.mkv`, `.avi`, `.m4v` files into any corpus and graphify transcribes them locally with faster-whisper before extraction
- Add: YouTube and URL download via yt-dlp — `/graphify add https://youtube.com/...` downloads audio-only and feeds it through the same Whisper pipeline
- Add: domain-aware Whisper prompts — the coding agent reads god nodes from the corpus and writes a one-sentence domain hint for Whisper itself, no separate API call
- Add: `graphify-out/transcripts/` cache — transcripts cached by filename; YouTube URLs cached by hash so re-runs skip already-transcribed files
- Requires: `pip install 'graphifyy[video]'` for faster-whisper and yt-dlp
## 0.3.29 (2026-04-10)
- Add: video and audio corpus support — drop `.mp4`, `.mp3`, `.wav`, `.mov`, `.webm`, `.m4a`, `.ogg`, `.mkv`, `.avi`, `.m4v` files into any corpus and graphify transcribes them with faster-whisper before extraction
+92 -14
View File
@@ -2,14 +2,15 @@
[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja-JP.md) | [한국어](README.ko-KR.md)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
[![Downloads](https://static.pepy.tech/badge/graphifyy/month)](https://pepy.tech/project/graphifyy)
[![Sponsor](https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors)](https://github.com/sponsors/safishamsi)
[![LinkedIn](https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin)](https://www.linkedin.com/in/safi-shamsi)
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, Aider, OpenClaw, Factory Droid, or Trae - 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.
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, or Google Antigravity - 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, images in other languages, or video and audio files - graphify extracts concepts and relationships from all of it and connects them into one graph. Videos are transcribed with Whisper using a domain-aware prompt derived from your corpus. 20 languages supported via tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia).
Fully multimodal. Drop in code, PDFs, markdown, screenshots, diagrams, whiteboard photos, images in other languages, or video and audio files - graphify extracts concepts and relationships from all of it and connects them into one graph. Videos are transcribed with Whisper using a domain-aware prompt derived from your corpus. 25 languages supported via tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
> Andrej Karpathy keeps a `/raw` folder where he drops papers, tweets, screenshots, and notes. graphify is the answer to that problem - 71.5x fewer tokens per query vs reading the raw files, persistent across sessions, honest about what it found vs guessed.
@@ -35,7 +36,7 @@ dist/
*.generated.py
```
Same syntax as `.gitignore`. Patterns match against file paths relative to the folder you run graphify on.
Same syntax as `.gitignore`. You can keep a single `.graphifyignore` at your repo root — patterns work correctly even when graphify is run on a subfolder.
## How it works
@@ -47,7 +48,7 @@ Every relationship is tagged `EXTRACTED` (found directly in source), `INFERRED`
## Install
**Requires:** Python 3.10+ and one of: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), or [Trae](https://trae.ai)
**Requires:** Python 3.10+ and one of: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), [Trae](https://trae.ai), [Kiro](https://kiro.dev), Hermes, or [Google Antigravity](https://antigravity.google)
```bash
pip install graphifyy && graphify install
@@ -70,9 +71,12 @@ pip install graphifyy && graphify install
| Trae | `graphify install --platform trae` |
| Trae CN | `graphify install --platform trae-cn` |
| Gemini CLI | `graphify install --platform gemini` |
| Hermes | `graphify install --platform hermes` |
| Kiro IDE/CLI | `graphify kiro install` |
| Cursor | `graphify cursor install` |
| Google Antigravity | `graphify antigravity install` |
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 and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism.
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 and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism. Codex supports PreToolUse hooks — `graphify codex install` installs one in `.codex/hooks.json` in addition to writing AGENTS.md.
Then open your AI coding assistant and type:
@@ -99,6 +103,9 @@ After building a graph, run this once in your project:
| Trae CN | `graphify trae-cn install` |
| Cursor | `graphify cursor install` |
| Gemini CLI | `graphify gemini install` |
| Hermes | `graphify hermes install` |
| Kiro IDE/CLI | `graphify kiro install` |
| Google Antigravity | `graphify antigravity 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.
@@ -110,7 +117,11 @@ After building a graph, run this once in your project:
**Gemini CLI** copies the skill to `~/.gemini/skills/graphify/SKILL.md`, writes a `GEMINI.md` section, and installs a `BeforeTool` hook in `.gemini/settings.json` that fires before file-read tool calls — same always-on mechanism as Claude Code.
**Aider and OpenClaw, Factory Droid, Trae** write the same rules to `AGENTS.md` in your project root. These platforms don't support tool hooks, so AGENTS.md is the always-on mechanism.
**Aider, OpenClaw, Factory Droid, Trae, and Hermes** write the same rules to `AGENTS.md` in your project root and copy the skill to the platform's global skill directory. These platforms don't support tool hooks, so AGENTS.md is the always-on mechanism.
**Kiro IDE/CLI** writes the skill to `.kiro/skills/graphify/SKILL.md` (invoked via `/graphify`) and a steering file to `.kiro/steering/graphify.md` with `inclusion: always` — Kiro injects this into every conversation automatically, no hook needed.
**Google Antigravity** writes `.agent/rules/graphify.md` (always-on rules) and `.agent/workflows/graphify.md` (registers `/graphify` as a slash command). No hook equivalent exists in Antigravity — rules are the always-on mechanism.
**GitHub Copilot CLI** copies the skill to `~/.copilot/skills/graphify/SKILL.md`. Run `graphify copilot install` to set it up.
@@ -160,12 +171,21 @@ python -m graphify.serve graphify-out/graph.json
That gives the assistant structured graph access for repeated queries such as
`query_graph`, `get_node`, `get_neighbors`, and `shortest_path`.
> **WSL / Linux note:** Ubuntu ships `python3`, not `python`. Install into a project venv to avoid PEP 668 conflicts, and use the full venv path in your `.mcp.json`:
> ```bash
> python3 -m venv .venv && .venv/bin/pip install "graphifyy[mcp]"
> ```
> ```json
> { "mcpServers": { "graphify": { "type": "stdio", "command": ".venv/bin/python3", "args": ["-m", "graphify.serve", "graphify-out/graph.json"] } } }
> ```
> Also note: the PyPI package is `graphifyy` (double-y) — `pip install graphify` installs an unrelated package.
<details>
<summary>Manual install (curl)</summary>
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v4/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
```
@@ -193,7 +213,7 @@ When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"`
/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://www.youtube.com/watch?v=... # download audio, transcribe, add to graph
/graphify add <video-url> # download audio, transcribe, add to graph
/graphify add https://... --author "Name" # tag the original author
/graphify add https://... --contributor "Name" # tag who added it to the corpus
@@ -219,7 +239,7 @@ 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 codex install # AGENTS.md + PreToolUse hook in .codex/hooks.json (Codex)
graphify opencode install # AGENTS.md + tool.execute.before plugin (OpenCode)
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
graphify cursor uninstall
@@ -235,19 +255,36 @@ graphify trae install # AGENTS.md (Trae)
graphify trae uninstall
graphify trae-cn install # AGENTS.md (Trae CN)
graphify trae-cn uninstall
graphify hermes install # AGENTS.md + ~/.hermes/skills/ (Hermes)
graphify hermes uninstall
graphify kiro install # .kiro/skills/ + .kiro/steering/graphify.md (Kiro IDE/CLI)
graphify kiro uninstall
graphify antigravity install # .agent/rules + .agent/workflows (Google Antigravity)
graphify antigravity uninstall
# query the graph directly from the terminal (no AI assistant needed)
# query and navigate the graph directly from the terminal (no AI assistant needed)
graphify query "what connects attention to the optimizer?"
graphify query "show the auth flow" --dfs
graphify query "what is CfgNode?" --budget 500
graphify query "..." --graph path/to/graph.json
graphify path "DigestAuth" "Response" # shortest path between two nodes
graphify explain "SwinTransformer" # plain-language explanation of a node
# add content and update the graph from the terminal
graphify add https://arxiv.org/abs/1706.03762 # fetch paper, save to ./raw, update graph
graphify add https://... --author "Name" --contributor "Name"
# incremental update and maintenance
graphify watch ./src # auto-rebuild on code changes
graphify update ./src # re-extract code files, no LLM needed
graphify cluster-only ./my-project # rerun clustering on existing graph.json
```
Works with any mix of file types:
| Type | Extensions | Extraction |
|------|-----------|------------|
| Code | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl` | AST via tree-sitter + call-graph + docstring/comment rationale |
| Code | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl .vue .svelte` | AST via tree-sitter + call-graph (cross-file for all languages) + 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 |
@@ -255,6 +292,31 @@ Works with any mix of file types:
| Video / Audio | `.mp4 .mov .mkv .webm .avi .m4v .mp3 .wav .m4a .ogg` | Transcribed locally with faster-whisper, transcript fed into Claude extraction (requires `pip install graphifyy[video]`) |
| YouTube / URLs | any video URL | Audio downloaded via yt-dlp, then same Whisper pipeline (requires `pip install graphifyy[video]`) |
## Video and audio corpus
Drop video or audio files into your corpus folder alongside your code and docs — graphify picks them up automatically:
```bash
pip install 'graphifyy[video]' # one-time setup
/graphify ./my-corpus # transcribes any video/audio files it finds
```
Add a YouTube video (or any public video URL) directly:
```bash
/graphify add <video-url>
```
yt-dlp downloads audio-only (fast, small), Whisper transcribes it locally, and the transcript is fed into the same extraction pipeline as your other docs. Transcripts are cached in `graphify-out/transcripts/` so re-runs skip already-transcribed files.
For better accuracy on technical content, use a larger model:
```bash
/graphify ./my-corpus --whisper-model medium
```
Audio never leaves your machine. All transcription runs locally.
## What you get
**God nodes** - highest-degree concepts (what everything connects through)
@@ -295,11 +357,27 @@ graphify sends file contents to your AI coding assistant's underlying model API
## Tech stack
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.
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantic extraction via Claude (Claude Code), GPT-4 (Codex), or whichever model your platform runs. Video transcription via faster-whisper + yt-dlp (optional, `pip install graphifyy[video]`). No Neo4j required, no server, runs entirely locally.
## Built on graphify — Penpax
[**Penpax**](https://safishamsi.github.io/penpax.ai) is the enterprise layer on top of graphify. Where graphify turns a folder of files into a knowledge graph, Penpax applies the same graph to your entire working life — continuously.
| | graphify | Penpax |
|---|---|---|
| Input | A folder of files | Browser history, meetings, emails, files, code — everything |
| Runs | On demand | Continuously in the background |
| Scope | A project | Your entire working life |
| Query | CLI / MCP / AI skill | Natural language, always on |
| Privacy | Local by default | Fully on-device, no cloud |
Built for lawyers, consultants, executives, doctors, researchers — anyone whose work lives across hundreds of conversations and documents they can never fully reconstruct.
**Free trial launching soon.** [Join the waitlist →](https://safishamsi.github.io/penpax.ai)
## What we are building next
graphify is the graph layer. We are building [Penpax](https://safishamsi.github.io/penpax.ai) on top of it — an on-device digital twin that connects your meetings, browser history, files, emails, and code into one continuously updating knowledge graph. No cloud, no training on your data. [Join the waitlist.](https://safishamsi.github.io/penpax.ai)
graphify is the graph layer. Penpax is the always-on layer on top of it — an on-device digital twin that connects your meetings, browser history, files, emails, and code into one continuously updating knowledge graph. No cloud, no training on your data. [Join the waitlist.](https://safishamsi.github.io/penpax.ai)
## Star history
+414 -18
View File
@@ -74,7 +74,7 @@ _PLATFORM_CONFIG: dict[str, dict] = {
},
"claw": {
"skill_file": "skill-claw.md",
"skill_dst": Path(".claw") / "skills" / "graphify" / "SKILL.md",
"skill_dst": Path(".openclaw") / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"droid": {
@@ -92,6 +92,21 @@ _PLATFORM_CONFIG: dict[str, dict] = {
"skill_dst": Path(".trae-cn") / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"hermes": {
"skill_file": "skill-claw.md",
"skill_dst": Path(".hermes") / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"kiro": {
"skill_file": "skill-kiro.md",
"skill_dst": Path(".kiro") / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"antigravity": {
"skill_file": "skill.md",
"skill_dst": Path(".agent") / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"windows": {
"skill_file": "skill-windows.md",
"skill_dst": Path(".claude") / "skills" / "graphify" / "SKILL.md",
@@ -105,7 +120,7 @@ def install(platform: str = "claude") -> None:
gemini_install()
return
if platform == "cursor":
_cursor_install()
_cursor_install(Path("."))
return
if platform not in _PLATFORM_CONFIG:
print(
@@ -141,6 +156,9 @@ def install(platform: str = "claude") -> None:
claude_md.write_text(_SKILL_REGISTRATION.lstrip(), encoding="utf-8")
print(f" CLAUDE.md -> created at {claude_md}")
if platform == "opencode":
_install_opencode_plugin(Path("."))
print()
print("Done. Open your AI coding assistant and type:")
print()
@@ -156,7 +174,7 @@ 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
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
"""
_CLAUDE_MD_MARKER = "## graphify"
@@ -171,7 +189,7 @@ 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
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
"""
_AGENTS_MD_MARKER = "## graphify"
@@ -184,7 +202,7 @@ 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
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
"""
_GEMINI_MD_MARKER = "## graphify"
@@ -298,6 +316,169 @@ def gemini_uninstall(project_dir: Path | None = None) -> None:
_uninstall_gemini_hook(project_dir or Path("."))
_ANTIGRAVITY_RULES_PATH = Path(".agent") / "rules" / "graphify.md"
_ANTIGRAVITY_WORKFLOW_PATH = Path(".agent") / "workflows" / "graphify.md"
_ANTIGRAVITY_RULES = """\
## 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
- If the graphify MCP server is active, utilize tools like `query_graph`, `get_node`, and `shortest_path` for precise architecture navigation instead of falling back to `grep`
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
"""
_ANTIGRAVITY_WORKFLOW = """\
# Workflow: graphify
**Command:** /graphify
**Description:** Turn any folder of files into a navigable knowledge graph
## Steps
Follow the graphify skill installed at ~/.agent/skills/graphify/SKILL.md to run the full pipeline.
If no path argument is given, use `.` (current directory).
"""
_KIRO_STEERING = """\
---
inclusion: always
---
graphify: A knowledge graph of this project lives in `graphify-out/`. \
If `graphify-out/GRAPH_REPORT.md` exists, read it before answering architecture questions, \
tracing dependencies, or searching files — it contains god nodes, community structure, \
and surprising connections the graph found. Navigate by graph structure instead of grepping raw files.
"""
_KIRO_STEERING_MARKER = "graphify: A knowledge graph of this project"
def _kiro_install(project_dir: Path) -> None:
"""Write graphify skill + steering file for Kiro IDE/CLI."""
project_dir = project_dir or Path(".")
# Skill file → .kiro/skills/graphify/SKILL.md
skill_src = Path(__file__).parent / "skill-kiro.md"
skill_dst = project_dir / ".kiro" / "skills" / "graphify" / "SKILL.md"
skill_dst.parent.mkdir(parents=True, exist_ok=True)
skill_dst.write_text(skill_src.read_text(encoding="utf-8"), encoding="utf-8")
print(f" {skill_dst.relative_to(project_dir)} -> /graphify skill")
# Steering file → .kiro/steering/graphify.md (always-on)
steering_dir = project_dir / ".kiro" / "steering"
steering_dir.mkdir(parents=True, exist_ok=True)
steering_dst = steering_dir / "graphify.md"
if steering_dst.exists() and _KIRO_STEERING_MARKER in steering_dst.read_text(encoding="utf-8"):
print(f" .kiro/steering/graphify.md -> already configured")
else:
steering_dst.write_text(_KIRO_STEERING, encoding="utf-8")
print(f" .kiro/steering/graphify.md -> always-on steering written")
print()
print("Kiro will now read the knowledge graph before every conversation.")
print("Use /graphify to build or update the graph.")
def _kiro_uninstall(project_dir: Path) -> None:
"""Remove graphify skill + steering file for Kiro."""
project_dir = project_dir or Path(".")
removed = []
skill_dst = project_dir / ".kiro" / "skills" / "graphify" / "SKILL.md"
if skill_dst.exists():
skill_dst.unlink()
removed.append(str(skill_dst.relative_to(project_dir)))
# Remove parent dir if empty
try:
skill_dst.parent.rmdir()
except OSError:
pass
steering_dst = project_dir / ".kiro" / "steering" / "graphify.md"
if steering_dst.exists():
steering_dst.unlink()
removed.append(str(steering_dst.relative_to(project_dir)))
print("Removed: " + (", ".join(removed) if removed else "nothing to remove"))
def _antigravity_install(project_dir: Path) -> None:
"""Install graphify for Google Antigravity: skill + .agent/rules + .agent/workflows."""
# 1. Copy skill file to ~/.agent/skills/graphify/SKILL.md
install(platform="antigravity")
# 1.5. Inject YAML frontmatter for native Antigravity tool discovery
skill_dst = Path.home() / _PLATFORM_CONFIG["antigravity"]["skill_dst"]
if skill_dst.exists():
content = skill_dst.read_text(encoding="utf-8")
if not content.startswith("---\n"):
frontmatter = "---\nname: graphify-manager\ndescription: Rebuild the code graph or perform manual CLI queries when MCP server is offline.\n---\n\n"
skill_dst.write_text(frontmatter + content, encoding="utf-8")
# 2. Write .agent/rules/graphify.md
rules_path = project_dir / _ANTIGRAVITY_RULES_PATH
rules_path.parent.mkdir(parents=True, exist_ok=True)
if rules_path.exists():
print(f"graphify rule already exists at {rules_path} (no change)")
else:
rules_path.write_text(_ANTIGRAVITY_RULES, encoding="utf-8")
print(f"graphify rule written to {rules_path.resolve()}")
# 3. Write .agent/workflows/graphify.md
wf_path = project_dir / _ANTIGRAVITY_WORKFLOW_PATH
wf_path.parent.mkdir(parents=True, exist_ok=True)
if wf_path.exists():
print(f"graphify workflow already exists at {wf_path} (no change)")
else:
wf_path.write_text(_ANTIGRAVITY_WORKFLOW, encoding="utf-8")
print(f"graphify workflow written to {wf_path.resolve()}")
print()
print("Antigravity will now check the knowledge graph before answering")
print("codebase questions. Run /graphify first to build the graph.")
print()
print("To enable full MCP architecture navigation, add this to ~/.gemini/antigravity/mcp_config.json:")
print(' "graphify": {')
print(' "command": "uv",')
print(' "args": ["run", "--with", "graphifyy", "--with", "mcp", "-m", "graphify.serve", "${workspace.path}/graphify-out/graph.json"]')
print(' }')
def _antigravity_uninstall(project_dir: Path) -> None:
"""Remove graphify Antigravity rules, workflow, and skill files."""
# Remove rules file
rules_path = project_dir / _ANTIGRAVITY_RULES_PATH
if rules_path.exists():
rules_path.unlink()
print(f"graphify rule removed from {rules_path.resolve()}")
else:
print("No graphify Antigravity rule found - nothing to do")
# Remove workflow file
wf_path = project_dir / _ANTIGRAVITY_WORKFLOW_PATH
if wf_path.exists():
wf_path.unlink()
print(f"graphify workflow removed from {wf_path.resolve()}")
# Remove skill file
skill_dst = Path.home() / _PLATFORM_CONFIG["antigravity"]["skill_dst"]
if skill_dst.exists():
skill_dst.unlink()
print(f"graphify skill removed from {skill_dst}")
version_file = skill_dst.parent / ".graphify_version"
if version_file.exists():
version_file.unlink()
for d in (skill_dst.parent, skill_dst.parent.parent, skill_dst.parent.parent.parent):
try:
d.rmdir()
except OSError:
break
_CURSOR_RULE_PATH = Path(".cursor") / "rules" / "graphify.mdc"
_CURSOR_RULE = """\
---
@@ -309,7 +490,7 @@ 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 in this session, run `python3 -c "from graphify.watch import _rebuild_code; from pathlib import Path; _rebuild_code(Path('.'))"` to keep the graph current
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
"""
@@ -428,7 +609,7 @@ _CODEX_HOOK = {
"type": "command",
"command": (
"[ -f graphify-out/graph.json ] && "
r"""echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"},"systemMessage":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}' """
r"""echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}}' """
"|| true"
),
}
@@ -504,7 +685,7 @@ def _agents_install(project_dir: Path, platform: str) -> None:
print(f"{platform.capitalize()} — the AGENTS.md rules are the always-on mechanism.")
def _agents_uninstall(project_dir: Path) -> None:
def _agents_uninstall(project_dir: Path, platform: str = "") -> None:
"""Remove the graphify section from the local AGENTS.md."""
target = (project_dir or Path(".")) / "AGENTS.md"
@@ -530,7 +711,8 @@ def _agents_uninstall(project_dir: Path) -> None:
target.unlink()
print(f"AGENTS.md was empty after removal - deleted {target.resolve()}")
_uninstall_opencode_plugin(project_dir or Path("."))
if platform == "opencode":
_uninstall_opencode_plugin(project_dir or Path("."))
def claude_install(project_dir: Path | None = None) -> None:
@@ -628,16 +810,29 @@ def claude_uninstall(project_dir: Path | None = None) -> None:
def main() -> None:
# Check all known skill install locations for a stale version stamp
for cfg in _PLATFORM_CONFIG.values():
skill_dst = Path.home() / cfg["skill_dst"]
_check_skill_version(skill_dst)
# Check all known skill install locations for a stale version stamp.
# Skip during install/uninstall (hook writes trigger a fresh check anyway).
# Deduplicate paths so platforms sharing the same install dir don't warn twice.
if not any(arg in ("install", "uninstall") for arg in sys.argv):
for skill_dst in {Path.home() / cfg["skill_dst"] for cfg in _PLATFORM_CONFIG.values()}:
_check_skill_version(skill_dst)
if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
print("Usage: graphify <command>")
print()
print("Commands:")
print(" install [--platform P] copy skill to platform config dir (claude|windows|codex|opencode|aider|claw|droid|trae|trae-cn|gemini|cursor)")
print(" install [--platform P] copy skill to platform config dir (claude|windows|codex|opencode|aider|claw|droid|trae|trae-cn|gemini|cursor|antigravity|hermes|kiro)")
print(" path \"A\" \"B\" shortest path between two nodes in graph.json")
print(" --graph <path> path to graph.json (default graphify-out/graph.json)")
print(" explain \"X\" plain-language explanation of a node and its neighbors")
print(" --graph <path> path to graph.json (default graphify-out/graph.json)")
print(" add <url> fetch a URL and save it to ./raw, then update the graph")
print(" --author \"Name\" tag the author of the content")
print(" --contributor \"Name\" tag who added it to the corpus")
print(" --dir <path> target directory (default: ./raw)")
print(" watch <path> watch a folder and rebuild the graph on code changes")
print(" update <path> re-extract code files and update the graph (no LLM needed)")
print(" cluster-only <path> rerun clustering on an existing graph.json and regenerate report")
print(" query \"<question>\" BFS traversal of graph.json for a question")
print(" --dfs use depth-first instead of breadth-first")
print(" --budget N cap output at N tokens (default 2000)")
@@ -674,6 +869,12 @@ def main() -> None:
print(" trae uninstall remove graphify section from AGENTS.md")
print(" trae-cn install write graphify section to AGENTS.md (Trae CN)")
print(" trae-cn uninstall remove graphify section from AGENTS.md")
print(" antigravity install write .agent/rules + .agent/workflows + skill (Google Antigravity)")
print(" antigravity uninstall remove .agent/rules, .agent/workflows, and skill")
print(" hermes install write skill to ~/.hermes/skills/graphify/ (Hermes)")
print(" hermes uninstall remove skill from ~/.hermes/skills/graphify/")
print(" kiro install write skill to .kiro/skills/graphify/ + steering file (Kiro IDE/CLI)")
print(" kiro uninstall remove skill + steering file")
print()
return
@@ -743,17 +944,35 @@ def main() -> None:
else:
print("Usage: graphify copilot [install|uninstall]", file=sys.stderr)
sys.exit(1)
elif cmd in ("aider", "codex", "opencode", "claw", "droid", "trae", "trae-cn"):
elif cmd == "kiro":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
_kiro_install(Path("."))
elif subcmd == "uninstall":
_kiro_uninstall(Path("."))
else:
print("Usage: graphify kiro [install|uninstall]", file=sys.stderr)
sys.exit(1)
elif cmd in ("aider", "codex", "opencode", "claw", "droid", "trae", "trae-cn", "hermes"):
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
_agents_install(Path("."), cmd)
elif subcmd == "uninstall":
_agents_uninstall(Path("."))
_agents_uninstall(Path("."), platform=cmd)
if cmd == "codex":
_uninstall_codex_hook(Path("."))
else:
print(f"Usage: graphify {cmd} [install|uninstall]", file=sys.stderr)
sys.exit(1)
elif cmd == "antigravity":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
_antigravity_install(Path("."))
elif subcmd == "uninstall":
_antigravity_uninstall(Path("."))
else:
print("Usage: graphify antigravity [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 ""
@@ -798,8 +1017,6 @@ def main() -> None:
graph_path = args[i + 1]; i += 2
else:
i += 1
# Load graph directly — validate_graph_path restricts to graphify-out/
# so for custom --graph paths we resolve and load directly after existence check
gp = Path(graph_path).resolve()
if not gp.exists():
print(f"error: graph file not found: {gp}", file=sys.stderr)
@@ -845,6 +1062,185 @@ def main() -> None:
source_nodes=opts.nodes or None,
)
print(f"Saved to {out}")
elif cmd == "path":
if len(sys.argv) < 4:
print("Usage: graphify path \"<source>\" \"<target>\" [--graph path]", file=sys.stderr)
sys.exit(1)
from graphify.serve import _score_nodes
from networkx.readwrite import json_graph
import networkx as _nx
source_label = sys.argv[2]
target_label = sys.argv[3]
graph_path = "graphify-out/graph.json"
args = sys.argv[4:]
for i, a in enumerate(args):
if a == "--graph" and i + 1 < len(args):
graph_path = args[i + 1]
gp = Path(graph_path).resolve()
if not gp.exists():
print(f"error: graph file not found: {gp}", file=sys.stderr)
sys.exit(1)
_raw = json.loads(gp.read_text(encoding="utf-8"))
try:
G = json_graph.node_link_graph(_raw, edges="links")
except TypeError:
G = json_graph.node_link_graph(_raw)
src_scored = _score_nodes(G, [t.lower() for t in source_label.split()])
tgt_scored = _score_nodes(G, [t.lower() for t in target_label.split()])
if not src_scored:
print(f"No node matching '{source_label}' found.", file=sys.stderr)
sys.exit(1)
if not tgt_scored:
print(f"No node matching '{target_label}' found.", file=sys.stderr)
sys.exit(1)
src_nid, tgt_nid = src_scored[0][1], tgt_scored[0][1]
try:
path_nodes = _nx.shortest_path(G, src_nid, tgt_nid)
except (_nx.NetworkXNoPath, _nx.NodeNotFound):
print(f"No path found between '{source_label}' and '{target_label}'.")
sys.exit(0)
hops = len(path_nodes) - 1
segments = []
for i in range(len(path_nodes) - 1):
u, v = path_nodes[i], path_nodes[i + 1]
edata = G.edges[u, v]
rel = edata.get("relation", "")
conf = edata.get("confidence", "")
conf_str = f" [{conf}]" if conf else ""
if i == 0:
segments.append(G.nodes[u].get("label", u))
segments.append(f"--{rel}{conf_str}--> {G.nodes[v].get('label', v)}")
print(f"Shortest path ({hops} hops):\n " + " ".join(segments))
elif cmd == "explain":
if len(sys.argv) < 3:
print("Usage: graphify explain \"<node>\" [--graph path]", file=sys.stderr)
sys.exit(1)
from graphify.serve import _find_node
from networkx.readwrite import json_graph
label = sys.argv[2]
graph_path = "graphify-out/graph.json"
args = sys.argv[3:]
for i, a in enumerate(args):
if a == "--graph" and i + 1 < len(args):
graph_path = args[i + 1]
gp = Path(graph_path).resolve()
if not gp.exists():
print(f"error: graph file not found: {gp}", file=sys.stderr)
sys.exit(1)
_raw = json.loads(gp.read_text(encoding="utf-8"))
try:
G = json_graph.node_link_graph(_raw, edges="links")
except TypeError:
G = json_graph.node_link_graph(_raw)
matches = _find_node(G, label)
if not matches:
print(f"No node matching '{label}' found.")
sys.exit(0)
nid = matches[0]
d = G.nodes[nid]
print(f"Node: {d.get('label', nid)}")
print(f" ID: {nid}")
print(f" Source: {d.get('source_file', '')} {d.get('source_location', '')}".rstrip())
print(f" Type: {d.get('file_type', '')}")
print(f" Community: {d.get('community', '')}")
print(f" Degree: {G.degree(nid)}")
neighbors = list(G.neighbors(nid))
if neighbors:
print(f"\nConnections ({len(neighbors)}):")
for nb in sorted(neighbors, key=lambda n: G.degree(n), reverse=True)[:20]:
edata = G.edges[nid, nb]
rel = edata.get("relation", "")
conf = edata.get("confidence", "")
print(f" --> {G.nodes[nb].get('label', nb)} [{rel}] [{conf}]")
if len(neighbors) > 20:
print(f" ... and {len(neighbors) - 20} more")
elif cmd == "add":
if len(sys.argv) < 3:
print("Usage: graphify add <url> [--author Name] [--contributor Name] [--dir ./raw]", file=sys.stderr)
sys.exit(1)
from graphify.ingest import ingest as _ingest
url = sys.argv[2]
author: str | None = None
contributor: str | None = None
target_dir = Path("raw")
args = sys.argv[3:]
i = 0
while i < len(args):
if args[i] == "--author" and i + 1 < len(args):
author = args[i + 1]; i += 2
elif args[i] == "--contributor" and i + 1 < len(args):
contributor = args[i + 1]; i += 2
elif args[i] == "--dir" and i + 1 < len(args):
target_dir = Path(args[i + 1]); i += 2
else:
i += 1
try:
saved = _ingest(url, target_dir, author=author, contributor=contributor)
print(f"Saved to {saved}")
print("Run /graphify --update in your AI assistant to update the graph.")
except Exception as exc:
print(f"error: {exc}", file=sys.stderr)
sys.exit(1)
elif cmd == "watch":
watch_path = Path(sys.argv[2]) if len(sys.argv) > 2 else Path(".")
if not watch_path.exists():
print(f"error: path not found: {watch_path}", file=sys.stderr)
sys.exit(1)
from graphify.watch import watch as _watch
try:
_watch(watch_path)
except ImportError as exc:
print(f"error: {exc}", file=sys.stderr)
sys.exit(1)
elif cmd == "cluster-only":
watch_path = Path(sys.argv[2]) if len(sys.argv) > 2 else Path(".")
graph_json = watch_path / "graphify-out" / "graph.json"
if not graph_json.exists():
print(f"error: no graph found at {graph_json} — run /graphify first", file=sys.stderr)
sys.exit(1)
from networkx.readwrite import json_graph as _jg
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
print("Loading existing graph...")
_raw = json.loads(graph_json.read_text(encoding="utf-8"))
G = build_from_json(_raw)
print(f"Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
print("Re-clustering...")
communities = cluster(G)
cohesion = score_all(G, communities)
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: f"Community {cid}" for cid in communities}
questions = suggest_questions(G, communities, labels)
tokens = {"input": 0, "output": 0}
report = generate(G, communities, cohesion, labels, gods, surprises,
{}, tokens, str(watch_path), suggested_questions=questions)
out = watch_path / "graphify-out"
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
to_json(G, communities, str(out / "graph.json"))
print(f"Done — {len(communities)} communities. GRAPH_REPORT.md and graph.json updated.")
elif cmd == "update":
watch_path = Path(sys.argv[2]) if len(sys.argv) > 2 else Path(".")
if not watch_path.exists():
print(f"error: path not found: {watch_path}", file=sys.stderr)
sys.exit(1)
from graphify.watch import _rebuild_code
print(f"Re-extracting code files in {watch_path} (no LLM needed)...")
ok = _rebuild_code(watch_path)
if ok:
print("Code graph updated. For doc/paper/image changes run /graphify --update in your AI assistant.")
else:
print("Nothing to update or rebuild failed — check output above.", file=sys.stderr)
sys.exit(1)
elif cmd == "benchmark":
from graphify.benchmark import run_benchmark, print_benchmark
graph_path = sys.argv[2] if len(sys.argv) > 2 else "graphify-out/graph.json"
+16 -1
View File
@@ -218,7 +218,11 @@ def _cross_file_surprises(G: nx.Graph, communities: dict[int, list[str]], top_n:
score, reasons = _surprise_score(G, u, v, data, node_community, u_source, v_source)
src_id = data.get("_src", u)
if src_id not in G.nodes:
src_id = u
tgt_id = data.get("_tgt", v)
if tgt_id not in G.nodes:
tgt_id = v
candidates.append({
"_score": score,
"source": G.nodes[src_id].get("label", src_id),
@@ -258,6 +262,8 @@ def _cross_community_surprises(
# No community info - use edge betweenness centrality
if G.number_of_edges() == 0:
return []
if G.number_of_nodes() > 5000:
return []
betweenness = nx.edge_betweenness_centrality(G)
top_edges = sorted(betweenness.items(), key=lambda x: x[1], reverse=True)[:top_n]
result = []
@@ -294,7 +300,11 @@ def _cross_community_surprises(
# This edge crosses community boundaries - interesting
confidence = data.get("confidence", "EXTRACTED")
src_id = data.get("_src", u)
if src_id not in G.nodes:
src_id = u
tgt_id = data.get("_tgt", v)
if tgt_id not in G.nodes:
tgt_id = v
surprises.append({
"source": G.nodes[src_id].get("label", src_id),
"target": G.nodes[tgt_id].get("label", tgt_id),
@@ -352,7 +362,8 @@ def suggest_questions(
# 2. Bridge nodes (high betweenness) → cross-cutting concern questions
if G.number_of_edges() > 0:
betweenness = nx.betweenness_centrality(G)
k = min(100, G.number_of_nodes()) if G.number_of_nodes() > 1000 else None
betweenness = nx.betweenness_centrality(G, k=k)
# Top bridge nodes that are NOT file-level hubs
bridges = sorted(
[(n, s) for n, s in betweenness.items()
@@ -392,7 +403,11 @@ def suggest_questions(
others = []
for u, v, d in inferred[:2]:
src_id = d.get("_src", u)
if src_id not in G.nodes:
src_id = u
tgt_id = d.get("_tgt", v)
if tgt_id not in G.nodes:
tgt_id = v
other_id = tgt_id if src_id == node_id else src_id
others.append(G.nodes[other_id].get("label", other_id))
questions.append({
+1 -1
View File
@@ -75,7 +75,7 @@ def run_benchmark(
Returns dict with: corpus_tokens, avg_query_tokens, reduction_ratio, per_question
"""
data = json.loads(Path(graph_path).read_text())
data = json.loads(Path(graph_path).read_text(encoding="utf-8"))
try:
G = json_graph.node_link_graph(data, edges="links")
except TypeError:
+9
View File
@@ -32,6 +32,9 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
directed=True produces a DiGraph that preserves edge direction (source→target).
directed=False (default) produces an undirected Graph for backward compatibility.
"""
# NetworkX <= 3.1 serialised edges as "links"; remap to "edges" for compatibility.
if "edges" not in extraction and "links" in extraction:
extraction = dict(extraction, edges=extraction["links"])
errors = validate_extraction(extraction)
# Dangling edges (stdlib/external imports) are expected - only warn about real schema errors.
real_errors = [e for e in errors if "does not match any node id" not in e]
@@ -42,6 +45,12 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
G.add_node(node["id"], **{k: v for k, v in node.items() if k != "id"})
node_set = set(G.nodes())
for edge in extraction.get("edges", []):
if "source" not in edge and "from" in edge:
edge["source"] = edge["from"]
if "target" not in edge and "to" in edge:
edge["target"] = edge["to"]
if "source" not in edge or "target" not in edge:
continue
src, tgt = edge["source"], edge["target"]
if src not in node_set or tgt not in node_set:
continue # skip edges to external/stdlib nodes - expected, not an error
+23 -8
View File
@@ -17,8 +17,12 @@ def _body_content(content: bytes) -> bytes:
return content
def file_hash(path: Path) -> str:
"""SHA256 of file contents + resolved path. Prevents cache collisions on identical content.
def file_hash(path: Path, root: Path = Path(".")) -> str:
"""SHA256 of file contents + path relative to root.
Using a relative path (not absolute) makes cache entries portable across
machines and checkout directories, so shared caches and CI work correctly.
Falls back to the resolved absolute path if the file is outside root.
For Markdown files (.md), only the body below the YAML frontmatter is hashed,
so metadata-only changes (e.g. reviewed, status, tags) do not invalidate the cache.
@@ -29,7 +33,11 @@ def file_hash(path: Path) -> str:
h = hashlib.sha256()
h.update(content)
h.update(b"\x00")
h.update(str(p.resolve()).encode())
try:
rel = p.resolve().relative_to(Path(root).resolve())
h.update(str(rel).encode())
except ValueError:
h.update(str(p.resolve()).encode())
return h.hexdigest()
@@ -48,14 +56,14 @@ def load_cached(path: Path, root: Path = Path(".")) -> dict | None:
Returns None if no cache entry or file has changed.
"""
try:
h = file_hash(path)
h = file_hash(path, root)
except OSError:
return None
entry = cache_dir(root) / f"{h}.json"
if not entry.exists():
return None
try:
return json.loads(entry.read_text())
return json.loads(entry.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return None
@@ -66,12 +74,19 @@ def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
Stores as graphify-out/cache/{hash}.json where hash = SHA256 of current file contents.
result should be a dict with 'nodes' and 'edges' lists.
"""
h = file_hash(path)
h = file_hash(path, root)
entry = cache_dir(root) / f"{h}.json"
tmp = entry.with_suffix(".tmp")
try:
tmp.write_text(json.dumps(result))
os.replace(tmp, entry)
tmp.write_text(json.dumps(result), encoding="utf-8")
try:
os.replace(tmp, entry)
except PermissionError:
# Windows: os.replace can fail with WinError 5 if the target is
# briefly locked. Fall back to copy-then-delete.
import shutil
shutil.copy2(tmp, entry)
tmp.unlink(missing_ok=True)
except Exception:
tmp.unlink(missing_ok=True)
raise
+54 -34
View File
@@ -18,7 +18,7 @@ class FileType(str, Enum):
_MANIFEST_PATH = "graphify-out/manifest.json"
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl'}
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.dart', '.v', '.sv'}
DOC_EXTENSIONS = {'.md', '.txt', '.rst'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
@@ -69,7 +69,7 @@ def _looks_like_paper(path: Path) -> bool:
"""Heuristic: does this text file read like an academic paper?"""
try:
# Only scan first 3000 chars for speed
text = path.read_text(errors="ignore")[:3000]
text = path.read_text(encoding="utf-8", errors="ignore")[:3000]
hits = sum(1 for pattern in _PAPER_SIGNALS if pattern.search(text))
return hits >= _PAPER_SIGNAL_THRESHOLD
except Exception:
@@ -80,6 +80,9 @@ _ASSET_DIR_MARKERS = {".imageset", ".xcassets", ".appiconset", ".colorset", ".la
def classify_file(path: Path) -> FileType | None:
# Compound extensions must be checked before simple suffix lookup
if path.name.lower().endswith(".blade.php"):
return FileType.CODE
ext = path.suffix.lower()
if ext in CODE_EXTENSIONS:
return FileType.CODE
@@ -226,7 +229,7 @@ def count_words(path: Path) -> int:
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())
return len(path.read_text(encoding="utf-8", errors="ignore").split())
except Exception:
return 0
@@ -241,6 +244,13 @@ _SKIP_DIRS = {
".tox", ".eggs", "*.egg-info",
}
# Large generated files that are never useful to extract
_SKIP_FILES = {
"package-lock.json", "yarn.lock", "pnpm-lock.yaml",
"Cargo.lock", "poetry.lock", "Gemfile.lock",
"composer.lock", "go.sum", "go.work.sum",
}
def _is_noise_dir(part: str) -> bool:
"""Return True if this directory name looks like a venv, cache, or dep dir."""
if part in _SKIP_DIRS:
@@ -253,28 +263,26 @@ def _is_noise_dir(part: str) -> bool:
return False
def _load_graphifyignore(root: Path) -> list[str]:
"""Read .graphifyignore from root **and ancestor directories**, returning patterns.
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
"""Read .graphifyignore from root **and ancestor directories**.
Walks upward from *root* towards the filesystem root, collecting patterns
from every ``.graphifyignore`` encountered (like ``.gitignore`` discovery).
The search stops at the filesystem root or at a ``.git`` directory boundary
so it doesn't leak outside the repository.
Returns a list of (anchor_dir, pattern) pairs. Each pattern is matched
against paths relative to both the scan root and the anchor_dir where
the .graphifyignore file was found — so patterns written relative to a
parent directory still work when graphify is run on a subfolder.
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).
Walks upward from *root* towards the filesystem root, stopping at a
``.git`` boundary. Lines starting with # are comments; blank lines ignored.
"""
patterns: list[str] = []
patterns: list[tuple[Path, str]] = []
current = root.resolve()
while True:
ignore_file = current / ".graphifyignore"
if ignore_file.exists():
for line in ignore_file.read_text(errors="ignore").splitlines():
for line in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
line = line.strip()
if line and not line.startswith("#"):
patterns.append(line)
patterns.append((current, line))
# Stop climbing once we've processed the git repo root
if (current / ".git").exists():
break
@@ -285,34 +293,44 @@ def _load_graphifyignore(root: Path) -> list[str]:
return patterns
def _is_ignored(path: Path, root: Path, patterns: list[str]) -> bool:
def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, 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
def _matches(rel: str, p: str) -> bool:
parts = rel.split("/")
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
for anchor, pattern in patterns:
p = pattern.strip("/")
if not p:
continue
# Try path relative to the scan root
try:
rel = str(path.relative_to(root)).replace(os.sep, "/")
if _matches(rel, p):
return True
except ValueError:
pass
# Also try relative to the anchor dir (the .graphifyignore's location),
# so patterns written at a parent level still fire when running on a subfolder
if anchor != root:
try:
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
if _matches(rel_anchor, p):
return True
except ValueError:
pass
return False
@@ -357,6 +375,8 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
and not _is_ignored(dp / d, root, ignore_patterns)
]
for fname in filenames:
if fname in _SKIP_FILES:
continue
p = dp / fname
if p not in seen:
seen.add(p)
@@ -427,7 +447,7 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict[str, float]:
"""Load the file modification time manifest from a previous run."""
try:
return json.loads(Path(manifest_path).read_text())
return json.loads(Path(manifest_path).read_text(encoding="utf-8"))
except Exception:
return {}
@@ -442,7 +462,7 @@ def save_manifest(files: dict[str, list[str]], manifest_path: str = _MANIFEST_PA
except OSError:
pass # file deleted between detect() and manifest write - skip it
Path(manifest_path).parent.mkdir(parents=True, exist_ok=True)
Path(manifest_path).write_text(json.dumps(manifest, indent=2))
Path(manifest_path).write_text(json.dumps(manifest, indent=2), encoding="utf-8")
def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
+50 -28
View File
@@ -11,6 +11,12 @@ from networkx.readwrite import json_graph
from graphify.security import sanitize_label
from graphify.analyze import _node_community_map
def _strip_diacritics(text: str) -> str:
import unicodedata
nfkd = unicodedata.normalize("NFKD", text)
return "".join(c for c in nfkd if not unicodedata.combining(c))
COMMUNITY_COLORS = [
"#4E79A7", "#F28E2B", "#E15759", "#76B7B2", "#59A14F",
"#EDC948", "#B07AA1", "#FF9DA7", "#9C755F", "#BAB0AC",
@@ -56,32 +62,24 @@ def _hyperedge_script(hyperedges_json: str) -> str:
return f"""<script>
// Render hyperedges as shaded regions
const hyperedges = {hyperedges_json};
function drawHyperedges() {{
const canvas = network.canvas.frame.canvas;
const ctx = canvas.getContext('2d');
// afterDrawing passes ctx already transformed to network coordinate space.
// Draw node positions raw — no manual pan/zoom/DPR math needed.
network.on('afterDrawing', function(ctx) {{
hyperedges.forEach(h => {{
const positions = h.nodes
.map(nid => network.getPositions([nid])[nid])
.filter(p => p !== undefined);
if (positions.length < 2) return;
// Draw convex hull as filled polygon
ctx.save();
ctx.globalAlpha = 0.12;
ctx.fillStyle = '#6366f1';
ctx.strokeStyle = '#6366f1';
ctx.lineWidth = 2;
ctx.beginPath();
const scale = network.getScale();
const offset = network.getViewPosition();
const toCanvas = (p) => ({{
x: (p.x - offset.x) * scale + canvas.width / 2,
y: (p.y - offset.y) * scale + canvas.height / 2
}});
const pts = positions.map(toCanvas);
// Expand hull slightly
const cx = pts.reduce((s, p) => s + p.x, 0) / pts.length;
const cy = pts.reduce((s, p) => s + p.y, 0) / pts.length;
const expanded = pts.map(p => ({{
// Centroid and expanded hull in network coordinates
const cx = positions.reduce((s, p) => s + p.x, 0) / positions.length;
const cy = positions.reduce((s, p) => s + p.y, 0) / positions.length;
const expanded = positions.map(p => ({{
x: cx + (p.x - cx) * 1.15,
y: cy + (p.y - cy) * 1.15
}}));
@@ -99,8 +97,7 @@ function drawHyperedges() {{
ctx.fillText(h.label, cx, cy - 5);
ctx.restore();
}});
}}
network.on('afterDrawing', drawHyperedges);
}});
</script>"""
@@ -290,15 +287,31 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) ->
data = json_graph.node_link_data(G)
for node in data["nodes"]:
node["community"] = node_community.get(node["id"])
node["norm_label"] = _strip_diacritics(node.get("label", "")).lower()
for link in data["links"]:
if "confidence_score" not in link:
conf = link.get("confidence", "EXTRACTED")
link["confidence_score"] = _CONFIDENCE_SCORE_DEFAULTS.get(conf, 1.0)
data["hyperedges"] = getattr(G, "graph", {}).get("hyperedges", [])
with open(output_path, "w") as f:
with open(output_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
def prune_dangling_edges(graph_data: dict) -> tuple[dict, int]:
"""Remove edges whose source or target node is not in the node set.
Returns the cleaned graph_data dict and the number of pruned edges.
"""
node_ids = {n["id"] for n in graph_data["nodes"]}
links_key = "links" if "links" in graph_data else "edges"
before = len(graph_data[links_key])
graph_data[links_key] = [
e for e in graph_data[links_key]
if e["source"] in node_ids and e["target"] in node_ids
]
return graph_data, before - len(graph_data[links_key])
def _cypher_escape(s: str) -> str:
"""Escape a string for safe embedding in a Cypher single-quoted literal."""
return s.replace("\\", "\\\\").replace("'", "\\'")
@@ -322,7 +335,7 @@ def to_cypher(G: nx.Graph, output_path: str) -> None:
f"MATCH (a {{id: '{u_esc}'}}), (b {{id: '{v_esc}'}}) "
f"MERGE (a)-[:{rel} {{confidence: '{conf}'}}]->(b);"
)
with open(output_path, "w") as f:
with open(output_path, "w", encoding="utf-8") as f:
f.write("\n".join(lines))
@@ -346,7 +359,7 @@ def to_html(
node_community = _node_community_map(communities)
degree = dict(G.degree())
max_deg = max(degree.values()) if degree else 1
max_deg = max(degree.values(), default=1) or 1
# Build nodes list for vis.js
vis_nodes = []
@@ -396,10 +409,14 @@ def to_html(
n = len(communities.get(cid, []))
legend_data.append({"cid": cid, "color": color, "label": lbl, "count": n})
nodes_json = json.dumps(vis_nodes)
edges_json = json.dumps(vis_edges)
legend_json = json.dumps(legend_data)
hyperedges_json = json.dumps(getattr(G, "graph", {}).get("hyperedges", []))
# Escape </script> sequences so embedded JSON cannot break out of the script tag
def _js_safe(obj) -> str:
return json.dumps(obj).replace("</", "<\\/")
nodes_json = _js_safe(vis_nodes)
edges_json = _js_safe(vis_edges)
legend_json = _js_safe(legend_data)
hyperedges_json = _js_safe(getattr(G, "graph", {}).get("hyperedges", []))
title = _html.escape(sanitize_label(str(output_path)))
stats = f"{G.number_of_nodes()} nodes &middot; {G.number_of_edges()} edges &middot; {len(communities)} communities"
@@ -463,7 +480,10 @@ def to_obsidian(
# Map node_id → safe filename so wikilinks stay consistent.
# Deduplicate: if two nodes produce the same filename, append a numeric suffix.
def safe_name(label: str) -> str:
return re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip() or "unnamed"
cleaned = re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip()
# Strip trailing .md/.mdx/.markdown so "CLAUDE.md" doesn't become "CLAUDE.md.md"
cleaned = re.sub(r"\.(md|mdx|markdown)$", "", cleaned, flags=re.IGNORECASE)
return cleaned or "unnamed"
node_filename: dict[str, str] = {}
seen_names: dict[str, int] = {}
@@ -677,7 +697,7 @@ def to_obsidian(
for cid, label in sorted((community_labels or {}).items())
]
}
(obsidian_dir / "graph.json").write_text(json.dumps(graph_config, indent=2))
(obsidian_dir / "graph.json").write_text(json.dumps(graph_config, indent=2), encoding="utf-8")
return G.number_of_nodes() + community_notes_written
@@ -699,7 +719,9 @@ def to_canvas(
CANVAS_COLORS = ["1", "2", "3", "4", "5", "6"] # red, orange, yellow, green, cyan, purple
def safe_name(label: str) -> str:
return re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip() or "unnamed"
cleaned = re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip()
cleaned = re.sub(r"\.(md|mdx|markdown)$", "", cleaned, flags=re.IGNORECASE)
return cleaned or "unnamed"
# Build node_filenames if not provided (same dedup logic as to_obsidian)
if node_filenames is None:
@@ -953,7 +975,7 @@ def to_svg(
pos = nx.spring_layout(G, seed=42, k=2.0 / (G.number_of_nodes() ** 0.5 + 1))
degree = dict(G.degree())
max_deg = max(degree.values()) if degree else 1
max_deg = max(degree.values(), default=1) or 1
node_colors = [COMMUNITY_COLORS[node_community.get(n, 0) % len(COMMUNITY_COLORS)] for n in G.nodes()]
node_sizes = [300 + 1200 * (degree.get(n, 1) / max_deg) for n in G.nodes()]
+547 -31
View File
@@ -29,6 +29,10 @@ class LanguageConfig:
function_types: frozenset = frozenset()
import_types: frozenset = frozenset()
call_types: frozenset = frozenset()
static_prop_types: frozenset = frozenset()
helper_fn_names: frozenset = frozenset()
container_bind_methods: frozenset = frozenset()
event_listener_properties: frozenset = frozenset()
# Name extraction
name_field: str = "name"
@@ -112,8 +116,18 @@ def _import_python(node, source: bytes, file_nid: str, stem: str, edges: list, s
elif t == "import_from_statement":
module_node = node.child_by_field_name("module_name")
if module_node:
raw = _read_text(module_node, source).lstrip(".")
tgt_nid = _make_id(raw)
raw = _read_text(module_node, source)
if raw.startswith("."):
# Relative import - resolve to full path so IDs match file node IDs
dots = len(raw) - len(raw.lstrip("."))
module_name = raw.lstrip(".")
base = Path(str_path).parent
for _ in range(dots - 1):
base = base.parent
rel = (module_name.replace(".", "/") + ".py") if module_name else "__init__.py"
tgt_nid = _make_id(str(base / rel))
else:
tgt_nid = _make_id(raw)
edges.append({
"source": file_nid,
"target": tgt_nid,
@@ -129,18 +143,32 @@ def _import_js(node, source: bytes, file_nid: str, stem: str, edges: list, str_p
for child in node.children:
if child.type == "string":
raw = _read_text(child, source).strip("'\"` ")
module_name = raw.lstrip("./").split("/")[-1]
if module_name:
if not raw:
break
if raw.startswith("."):
# Relative import - resolve to full path so IDs match file node IDs
resolved = Path(str_path).parent / raw
# TypeScript ESM: imports written as .js but actual file is .ts/.tsx
if resolved.suffix == ".js":
resolved = resolved.with_suffix(".ts")
elif resolved.suffix == ".jsx":
resolved = resolved.with_suffix(".tsx")
tgt_nid = _make_id(str(resolved))
else:
# Bare/scoped import (node_modules) - use last segment; dropped as external
module_name = raw.split("/")[-1]
if not module_name:
break
tgt_nid = _make_id(module_name)
edges.append({
"source": file_nid,
"target": tgt_nid,
"relation": "imports_from",
"confidence": "EXTRACTED",
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
"weight": 1.0,
})
edges.append({
"source": file_nid,
"target": tgt_nid,
"relation": "imports_from",
"confidence": "EXTRACTED",
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
"weight": 1.0,
})
break
@@ -535,7 +563,11 @@ _PHP_CONFIG = LanguageConfig(
class_types=frozenset({"class_declaration"}),
function_types=frozenset({"function_definition", "method_declaration"}),
import_types=frozenset({"namespace_use_clause"}),
call_types=frozenset({"function_call_expression", "member_call_expression"}),
call_types=frozenset({"function_call_expression", "member_call_expression", "scoped_call_expression", "class_constant_access_expression"}),
static_prop_types=frozenset({"scoped_property_access_expression"}),
helper_fn_names=frozenset({"config"}),
container_bind_methods=frozenset({"bind", "singleton", "scoped", "instance"}),
event_listener_properties=frozenset({"listen", "subscribe"}),
call_function_field="function",
call_accessor_node_types=frozenset({"member_call_expression"}),
call_accessor_field="name",
@@ -649,6 +681,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
edges: list[dict] = []
seen_ids: set[str] = set()
function_bodies: list[tuple[str, object]] = []
pending_listen_edges: list[tuple[str, str, int]] = []
def add_node(nid: str, label: str, line: int) -> None:
if nid not in seen_ids:
@@ -673,7 +706,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
"weight": weight,
})
file_nid = _make_id(stem)
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
def walk(node, parent_class_nid: str | None = None) -> None:
@@ -776,6 +809,57 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
walk(child, parent_class_nid=class_nid)
return
# Event listener property arrays: $listen = [Event::class => [Listener::class]]
if (t == "property_declaration"
and parent_class_nid
and config.event_listener_properties):
for element in node.children:
if element.type != "property_element":
continue
prop_name: str | None = None
array_node = None
for c in element.children:
if c.type == "variable_name":
for sc in c.children:
if sc.type == "name":
prop_name = _read_text(sc, source)
break
elif c.type == "array_creation_expression":
array_node = c
if (prop_name is None
or prop_name not in config.event_listener_properties
or array_node is None):
continue
for entry in array_node.children:
if entry.type != "array_element_initializer":
continue
event_cls: str | None = None
listener_arr = None
for sub in entry.children:
if sub.type == "class_constant_access_expression" and event_cls is None:
for sc in sub.children:
if sc.is_named and sc.type in ("name", "qualified_name"):
event_cls = _read_text(sc, source)
break
elif sub.type == "array_creation_expression":
listener_arr = sub
if not event_cls or listener_arr is None:
continue
for listener_entry in listener_arr.children:
if listener_entry.type != "array_element_initializer":
continue
for item in listener_entry.children:
if item.type != "class_constant_access_expression":
continue
for sc in item.children:
if sc.is_named and sc.type in ("name", "qualified_name"):
listener_cls = _read_text(sc, source)
line_no = item.start_point[0] + 1
pending_listen_edges.append((event_cls, listener_cls, line_no))
break
break
return
# Function types
if t in config.function_types:
# Swift deinit/subscript have no name field — resolve before generic fallback
@@ -849,6 +933,21 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
label_to_nid[normalised.lower()] = n["id"]
seen_call_pairs: set[tuple[str, str]] = set()
seen_static_ref_pairs: set[tuple[str, str, str]] = set()
seen_helper_ref_pairs: set[tuple[str, str, str]] = set()
seen_bind_pairs: set[tuple[str, str, str]] = set()
raw_calls: list[dict] = [] # unresolved calls for cross-file resolution in extract()
def _php_class_const_scope(n) -> str | None:
scope = n.child_by_field_name("scope")
if scope is None:
for c in n.children:
if c.is_named and c.type in ("name", "qualified_name", "identifier"):
scope = c
break
if scope is None:
return None
return _read_text(scope, source)
def walk_calls(node, caller_nid: str) -> None:
if node.type in config.function_boundary_types:
@@ -911,11 +1010,16 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
callee_name = raw
break
elif config.ts_module == "tree_sitter_php":
# PHP: distinguish function_call_expression vs member_call_expression
# PHP: distinguish call expression subtypes
if node.type == "function_call_expression":
func_node = node.child_by_field_name("function")
if func_node:
callee_name = _read_text(func_node, source)
elif node.type == "scoped_call_expression":
# Static method call: Helper::format() → callee = "Helper"
scope_node = node.child_by_field_name("scope")
if scope_node:
callee_name = _read_text(scope_node, source)
else:
name_node = node.child_by_field_name("name")
if name_node:
@@ -961,6 +1065,138 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
"source_location": f"L{line}",
"weight": 1.0,
})
elif callee_name and not tgt_nid:
# Callee not in this file — save for cross-file resolution in extract()
raw_calls.append({
"caller_nid": caller_nid,
"callee": callee_name,
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
})
# Helper function calls: config('foo.bar') → uses_config edge to "foo"
if (callee_name and callee_name in config.helper_fn_names):
args_node = node.child_by_field_name("arguments")
first_key: str | None = None
if args_node:
for arg in args_node.children:
if arg.type != "argument":
continue
for inner in arg.children:
if inner.type == "string":
for sc in inner.children:
if sc.type == "string_content":
first_key = _read_text(sc, source)
break
break
if first_key:
break
if first_key:
segment = first_key.split(".")[0]
tgt_nid = (label_to_nid.get(segment.lower())
or label_to_nid.get(f"{segment}.php".lower()))
if tgt_nid and tgt_nid != caller_nid:
relation = f"uses_{callee_name}"
pair3 = (caller_nid, tgt_nid, relation)
if pair3 not in seen_helper_ref_pairs:
seen_helper_ref_pairs.add(pair3)
line = node.start_point[0] + 1
edges.append({
"source": caller_nid,
"target": tgt_nid,
"relation": relation,
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": str_path,
"source_location": f"L{line}",
"weight": 1.0,
})
# Service container bindings: $this->app->bind(Foo::class, Bar::class)
if (node.type == "member_call_expression"
and callee_name
and callee_name in config.container_bind_methods):
args_node = node.child_by_field_name("arguments")
class_args: list[str] = []
if args_node:
for arg in args_node.children:
if arg.type != "argument":
continue
for inner in arg.children:
if inner.type == "class_constant_access_expression":
cls = _php_class_const_scope(inner)
if cls:
class_args.append(cls)
break
if len(class_args) >= 2:
break
if len(class_args) == 2:
contract_name, impl_name = class_args
contract_nid = label_to_nid.get(contract_name.lower())
impl_nid = label_to_nid.get(impl_name.lower())
if contract_nid and impl_nid and contract_nid != impl_nid:
pair3 = (contract_nid, impl_nid, "bound_to")
if pair3 not in seen_bind_pairs:
seen_bind_pairs.add(pair3)
line = node.start_point[0] + 1
edges.append({
"source": contract_nid,
"target": impl_nid,
"relation": "bound_to",
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": str_path,
"source_location": f"L{line}",
"weight": 1.0,
})
# Static property access: Foo::$bar → uses_static_prop edge
if node.type in config.static_prop_types:
scope_node = node.child_by_field_name("scope")
if scope_node is None:
for child in node.children:
if child.is_named and child.type in ("name", "qualified_name", "identifier"):
scope_node = child
break
if scope_node is not None:
class_name = _read_text(scope_node, source)
tgt_nid = label_to_nid.get(class_name.lower())
if tgt_nid and tgt_nid != caller_nid:
pair3 = (caller_nid, tgt_nid, "uses_static_prop")
if pair3 not in seen_static_ref_pairs:
seen_static_ref_pairs.add(pair3)
line = node.start_point[0] + 1
edges.append({
"source": caller_nid,
"target": tgt_nid,
"relation": "uses_static_prop",
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": str_path,
"source_location": f"L{line}",
"weight": 1.0,
})
# PHP class constant access: Foo::BAR → references_constant edge
if config.ts_module == "tree_sitter_php" and node.type == "class_constant_access_expression":
class_name = _php_class_const_scope(node)
if class_name:
tgt_nid = label_to_nid.get(class_name.lower())
if tgt_nid and tgt_nid != caller_nid:
pair3 = (caller_nid, tgt_nid, "references_constant")
if pair3 not in seen_static_ref_pairs:
seen_static_ref_pairs.add(pair3)
line = node.start_point[0] + 1
edges.append({
"source": caller_nid,
"target": tgt_nid,
"relation": "references_constant",
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": str_path,
"source_location": f"L{line}",
"weight": 1.0,
})
for child in node.children:
walk_calls(child, caller_nid)
@@ -968,6 +1204,28 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
for caller_nid, body_node in function_bodies:
walk_calls(body_node, caller_nid)
# ── Event listener pass ───────────────────────────────────────────────────
seen_listen_pairs: set[tuple[str, str]] = set()
for event_name, listener_name, line in pending_listen_edges:
event_nid = label_to_nid.get(event_name.lower())
listener_nid = label_to_nid.get(listener_name.lower())
if not event_nid or not listener_nid or event_nid == listener_nid:
continue
pair2 = (event_nid, listener_nid)
if pair2 in seen_listen_pairs:
continue
seen_listen_pairs.add(pair2)
edges.append({
"source": event_nid,
"target": listener_nid,
"relation": "listened_by",
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": str_path,
"source_location": f"L{line}",
"weight": 1.0,
})
# ── Clean edges ───────────────────────────────────────────────────────────
valid_ids = seen_ids
clean_edges = []
@@ -976,7 +1234,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
if src in valid_ids and (tgt in valid_ids or edge["relation"] in ("imports", "imports_from")):
clean_edges.append(edge)
return {"nodes": nodes, "edges": clean_edges}
return {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls}
# ── Python rationale extraction ───────────────────────────────────────────────
@@ -1004,7 +1262,7 @@ def _extract_python_rationale(path: Path, result: dict) -> None:
nodes = result["nodes"]
edges = result["edges"]
seen_ids = {n["id"] for n in nodes}
file_nid = _make_id(stem)
file_nid = _make_id(str(path))
def _get_docstring(body_node) -> tuple[str, int] | None:
if not body_node:
@@ -1141,6 +1399,210 @@ def extract_php(path: Path) -> dict:
return _extract_generic(path, _PHP_CONFIG)
def extract_blade(path: Path) -> dict:
"""Extract @include, <livewire:> components, and wire:click bindings from Blade templates."""
import re
try:
src = path.read_text(encoding="utf-8", errors="replace")
except OSError:
return {"error": f"cannot read {path}"}
file_nid = _make_id(str(path))
nodes = [{"id": file_nid, "label": path.name, "file_type": "code",
"source_file": str(path), "source_location": None}]
edges = []
# @include('path.to.partial') or @include("path.to.partial")
for m in re.finditer(r"@include\(['\"]([^'\"]+)['\"]", src):
tgt = m.group(1).replace(".", "/")
tgt_nid = _make_id(tgt)
if tgt_nid not in {n["id"] for n in nodes}:
nodes.append({"id": tgt_nid, "label": m.group(1), "file_type": "code",
"source_file": str(path), "source_location": None})
edges.append({"source": file_nid, "target": tgt_nid, "relation": "includes",
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str(path), "source_location": None, "weight": 1.0})
# <livewire:component.name /> or <livewire:component.name>
for m in re.finditer(r"<livewire:([\w.\-]+)", src):
tgt_nid = _make_id(m.group(1))
if tgt_nid not in {n["id"] for n in nodes}:
nodes.append({"id": tgt_nid, "label": m.group(1), "file_type": "code",
"source_file": str(path), "source_location": None})
edges.append({"source": file_nid, "target": tgt_nid, "relation": "uses_component",
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str(path), "source_location": None, "weight": 1.0})
# wire:click="methodName"
for m in re.finditer(r'wire:click=["\']([^"\']+)["\']', src):
tgt_nid = _make_id(m.group(1))
if tgt_nid not in {n["id"] for n in nodes}:
nodes.append({"id": tgt_nid, "label": m.group(1), "file_type": "code",
"source_file": str(path), "source_location": None})
edges.append({"source": file_nid, "target": tgt_nid, "relation": "binds_method",
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str(path), "source_location": None, "weight": 1.0})
return {"nodes": nodes, "edges": edges}
def extract_dart(path: Path) -> dict:
"""Extract classes, mixins, functions, imports, and calls from a .dart file using regex."""
try:
src = path.read_text(encoding="utf-8", errors="replace")
except OSError:
return {"error": f"cannot read {path}"}
file_nid = _make_id(str(path))
nodes = [{"id": file_nid, "label": path.name, "file_type": "code",
"source_file": str(path), "source_location": None}]
edges = []
defined: set[str] = set()
# Classes and mixins
for m in re.finditer(r"^\s*(?:abstract\s+)?(?:class|mixin)\s+(\w+)", src, re.MULTILINE):
nid = _make_id(str(path), m.group(1))
if nid not in defined:
nodes.append({"id": nid, "label": m.group(1), "file_type": "code",
"source_file": str(path), "source_location": None})
edges.append({"source": file_nid, "target": nid, "relation": "defines",
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str(path), "source_location": None, "weight": 1.0})
defined.add(nid)
# Top-level and member functions/methods
for m in re.finditer(r"^\s*(?:static\s+|async\s+)?(?:\w+\s+)+(\w+)\s*\(", src, re.MULTILINE):
name = m.group(1)
if name in {"if", "for", "while", "switch", "catch", "return"}:
continue
nid = _make_id(str(path), name)
if nid not in defined:
nodes.append({"id": nid, "label": name, "file_type": "code",
"source_file": str(path), "source_location": None})
edges.append({"source": file_nid, "target": nid, "relation": "defines",
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str(path), "source_location": None, "weight": 1.0})
defined.add(nid)
# import 'package:...' or import '...'
for m in re.finditer(r"""^import\s+['"]([^'"]+)['"]""", src, re.MULTILINE):
pkg = m.group(1)
tgt_nid = _make_id(pkg)
if tgt_nid not in defined:
nodes.append({"id": tgt_nid, "label": pkg, "file_type": "code",
"source_file": str(path), "source_location": None})
defined.add(tgt_nid)
edges.append({"source": file_nid, "target": tgt_nid, "relation": "imports",
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str(path), "source_location": None, "weight": 1.0})
return {"nodes": nodes, "edges": edges}
def extract_verilog(path: Path) -> dict:
"""Extract modules, functions, tasks, package imports, and instantiations from .v/.sv files."""
try:
import tree_sitter_verilog as tsverilog
from tree_sitter import Language, Parser
except ImportError:
return {"nodes": [], "edges": [], "error": "tree_sitter_verilog not installed"}
try:
language = Language(tsverilog.language())
parser = Parser(language)
source = path.read_bytes()
tree = parser.parse(source)
root = tree.root_node
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
stem = path.stem
str_path = str(path)
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
def add_node(nid: str, label: str, line: int) -> None:
if nid not in seen_ids:
seen_ids.add(nid)
nodes.append({"id": nid, "label": label, "file_type": "code",
"source_file": str_path, "source_location": f"L{line}",
"confidence_score": 1.0})
def add_edge(src: str, tgt: str, relation: str, line: int,
confidence: str = "EXTRACTED", score: float = 1.0) -> None:
edges.append({"source": src, "target": tgt, "relation": relation,
"confidence": confidence, "confidence_score": score,
"source_file": str_path, "source_location": f"L{line}", "weight": 1.0})
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
def walk(node, module_nid: str | None = None) -> None:
t = node.type
if t == "module_declaration":
name_node = node.child_by_field_name("name")
if name_node:
mod_name = _read_text(name_node, source)
line = node.start_point[0] + 1
nid = _make_id(stem, mod_name)
add_node(nid, mod_name, line)
add_edge(file_nid, nid, "defines", line)
for child in node.children:
walk(child, nid)
return
elif t in ("function_declaration", "function_prototype"):
name_node = node.child_by_field_name("name")
if name_node:
func_name = _read_text(name_node, source)
line = node.start_point[0] + 1
parent = module_nid or file_nid
nid = _make_id(parent, func_name)
add_node(nid, f"{func_name}()", line)
add_edge(parent, nid, "contains", line)
elif t == "task_declaration":
name_node = node.child_by_field_name("name")
if name_node:
task_name = _read_text(name_node, source)
line = node.start_point[0] + 1
parent = module_nid or file_nid
nid = _make_id(parent, task_name)
add_node(nid, task_name, line)
add_edge(parent, nid, "contains", line)
elif t == "package_import_declaration":
for child in node.children:
if child.type == "package_import_item":
pkg_text = _read_text(child, source)
pkg_name = pkg_text.split("::")[0].strip()
if pkg_name:
line = node.start_point[0] + 1
tgt_nid = _make_id(pkg_name)
add_node(tgt_nid, pkg_name, line)
src = module_nid or file_nid
add_edge(src, tgt_nid, "imports_from", line)
elif t == "module_instantiation":
# module_type instantiates another module
type_node = node.child_by_field_name("module_type")
if type_node and module_nid:
inst_type = _read_text(type_node, source).strip()
if inst_type:
line = node.start_point[0] + 1
tgt_nid = _make_id(inst_type)
add_node(tgt_nid, inst_type, line)
add_edge(module_nid, tgt_nid, "instantiates", line)
for child in node.children:
walk(child, module_nid)
walk(root)
return {"nodes": nodes, "edges": edges}
def extract_lua(path: Path) -> dict:
"""Extract functions, methods, require() imports, and calls from a .lua file."""
return _extract_generic(path, _LUA_CONFIG)
@@ -1200,7 +1662,7 @@ def extract_julia(path: Path) -> dict:
"weight": weight,
})
file_nid = _make_id(stem)
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
def _func_name_from_signature(sig_node) -> str | None:
@@ -1415,7 +1877,7 @@ def extract_go(path: Path) -> dict:
"weight": weight,
})
file_nid = _make_id(stem)
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
def walk(node) -> None:
@@ -1603,7 +2065,7 @@ def extract_rust(path: Path) -> dict:
"weight": weight,
})
file_nid = _make_id(stem)
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
def walk(node, parent_impl_nid: str | None = None) -> None:
@@ -1761,7 +2223,7 @@ def extract_zig(path: Path) -> dict:
"confidence": confidence, "source_file": str_path,
"source_location": f"L{line}", "weight": weight})
file_nid = _make_id(stem)
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
def _extract_import(node) -> None:
@@ -1916,7 +2378,7 @@ def extract_powershell(path: Path) -> dict:
"confidence": confidence, "source_file": str_path,
"source_location": f"L{line}", "weight": weight})
file_nid = _make_id(stem)
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
_PS_SKIP = frozenset({
@@ -2205,7 +2667,7 @@ def extract_objc(path: Path) -> dict:
"confidence": confidence, "source_file": str_path,
"source_location": f"L{line}", "weight": weight})
file_nid = _make_id(stem)
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
def _read(node) -> str:
@@ -2403,7 +2865,7 @@ def extract_elixir(path: Path) -> dict:
"confidence": confidence, "source_file": str_path,
"source_location": f"L{line}", "weight": weight})
file_nid = _make_id(stem)
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
_IMPORT_KEYWORDS = frozenset({"alias", "import", "require", "use"})
@@ -2565,13 +3027,19 @@ def _check_tree_sitter_version() -> None:
)
def extract(paths: list[Path]) -> dict:
def extract(paths: list[Path], cache_root: Path | None = None) -> dict:
"""Extract AST nodes and edges from a list of code files.
Two-pass process:
1. Per-file structural extraction (classes, functions, imports)
2. Cross-file import resolution: turns file-level imports into
class-level INFERRED edges (DigestAuth --uses--> Response)
Args:
paths: files to extract from
cache_root: explicit root for graphify-out/cache/ (overrides the
inferred common path prefix). Pass Path('.') when running on a
subdirectory so the cache stays at ./graphify-out/cache/.
"""
_check_tree_sitter_version()
per_file: list[dict] = []
@@ -2622,6 +3090,11 @@ def extract(paths: list[Path]) -> dict:
".m": extract_objc,
".mm": extract_objc,
".jl": extract_julia,
".vue": extract_js,
".svelte": extract_js,
".dart": extract_dart,
".v": extract_verilog,
".sv": extract_verilog,
}
total = len(paths)
@@ -2629,16 +3102,20 @@ def extract(paths: list[Path]) -> dict:
for i, path in enumerate(paths):
if total >= _PROGRESS_INTERVAL and i % _PROGRESS_INTERVAL == 0 and i > 0:
print(f" AST extraction: {i}/{total} files ({i * 100 // total}%)", flush=True)
extractor = _DISPATCH.get(path.suffix)
# .blade.php must be checked before suffix lookup since Path.suffix returns .php
if path.name.endswith(".blade.php"):
extractor = extract_blade
else:
extractor = _DISPATCH.get(path.suffix)
if extractor is None:
continue
cached = load_cached(path, root)
cached = load_cached(path, cache_root or root)
if cached is not None:
per_file.append(cached)
continue
result = extractor(path)
if "error" not in result:
save_cached(path, result, root)
save_cached(path, result, cache_root or root)
per_file.append(result)
if total >= _PROGRESS_INTERVAL:
print(f" AST extraction: {total}/{total} files (100%)", flush=True)
@@ -2660,6 +3137,37 @@ def extract(paths: list[Path]) -> dict:
import logging
logging.getLogger(__name__).warning("Cross-file import resolution failed, skipping: %s", exc)
# Cross-file call resolution for all languages
# Each extractor saved unresolved calls in raw_calls. Now that we have all
# nodes from all files, resolve any callee that exists in another file.
global_label_to_nid: dict[str, str] = {}
for n in all_nodes:
raw = n.get("label", "")
normalised = raw.strip("()").lstrip(".")
if normalised:
global_label_to_nid[normalised.lower()] = n["id"]
existing_pairs = {(e["source"], e["target"]) for e in all_edges}
for result in per_file:
for rc in result.get("raw_calls", []):
callee = rc.get("callee", "")
if not callee:
continue
tgt = global_label_to_nid.get(callee.lower())
caller = rc["caller_nid"]
if tgt and tgt != caller and (caller, tgt) not in existing_pairs:
existing_pairs.add((caller, tgt))
all_edges.append({
"source": caller,
"target": tgt,
"relation": "calls",
"confidence": "INFERRED",
"confidence_score": 0.8,
"source_file": rc.get("source_file", ""),
"source_location": rc.get("source_location"),
"weight": 1.0,
})
return {
"nodes": all_nodes,
"edges": all_edges,
@@ -2668,7 +3176,7 @@ def extract(paths: list[Path]) -> dict:
}
def collect_files(target: Path, *, follow_symlinks: bool = False) -> list[Path]:
def collect_files(target: Path, *, follow_symlinks: bool = False, root: Path | None = None) -> list[Path]:
if target.is_file():
return [target]
_EXTENSIONS = {
@@ -2678,12 +3186,20 @@ def collect_files(target: Path, *, follow_symlinks: bool = False) -> list[Path]:
".lua", ".toc", ".zig", ".ps1",
".m", ".mm",
}
from graphify.detect import _load_graphifyignore, _is_ignored
ignore_root = root if root is not None else target
patterns = _load_graphifyignore(ignore_root)
def _ignored(p: Path) -> bool:
return bool(patterns and _is_ignored(p, ignore_root, patterns))
if not follow_symlinks:
results: list[Path] = []
for ext in sorted(_EXTENSIONS):
results.extend(
p for p in target.rglob(f"*{ext}")
if not any(part.startswith(".") for part in p.parts)
and not _ignored(p)
)
return sorted(results)
# Walk with symlink following + cycle detection
@@ -2701,7 +3217,7 @@ def collect_files(target: Path, *, follow_symlinks: bool = False) -> list[Path]:
continue
for fname in filenames:
p = dp / fname
if p.suffix in _EXTENSIONS and not fname.startswith("."):
if p.suffix in _EXTENSIONS and not fname.startswith(".") and not _ignored(p):
results.append(p)
return sorted(results)
+20 -18
View File
@@ -20,13 +20,21 @@ if [ -n "$GRAPHIFY_BIN" ]; then
# Allowlist: only keep characters valid in a filesystem path to prevent
# injection if the shebang contains shell metacharacters
case "$GRAPHIFY_PYTHON" in
*[!a-zA-Z0-9/_.-]*) GRAPHIFY_PYTHON="python3" ;;
*[!a-zA-Z0-9/_.-]*) GRAPHIFY_PYTHON="" ;;
esac
if ! "$GRAPHIFY_PYTHON" -c "import graphify" 2>/dev/null; then
if [ -n "$GRAPHIFY_PYTHON" ] && ! "$GRAPHIFY_PYTHON" -c "import graphify" 2>/dev/null; then
GRAPHIFY_PYTHON=""
fi
fi
# Fall back: try python3, then python (Windows has no python3 shim)
if [ -z "$GRAPHIFY_PYTHON" ]; then
if command -v python3 >/dev/null 2>&1 && python3 -c "import graphify" 2>/dev/null; then
GRAPHIFY_PYTHON="python3"
elif command -v python >/dev/null 2>&1 && python -c "import graphify" 2>/dev/null; then
GRAPHIFY_PYTHON="python"
else
exit 0
fi
else
GRAPHIFY_PYTHON="python3"
fi
"""
@@ -46,19 +54,13 @@ $GRAPHIFY_PYTHON -c "
import os, sys
from pathlib import Path
CODE_EXTS = {
'.py', '.ts', '.js', '.go', '.rs', '.java', '.cpp', '.c', '.rb', '.swift',
'.kt', '.cs', '.scala', '.php', '.cc', '.cxx', '.hpp', '.h', '.kts',
}
changed_raw = os.environ.get('GRAPHIFY_CHANGED', '')
changed = [Path(f.strip()) for f in changed_raw.strip().splitlines() if f.strip()]
code_changed = [f for f in changed if f.suffix.lower() in CODE_EXTS and f.exists()]
if not code_changed:
if not changed:
sys.exit(0)
print(f'[graphify hook] {len(code_changed)} code file(s) changed - rebuilding graph...')
print(f'[graphify hook] {len(changed)} file(s) changed - rebuilding graph...')
try:
from graphify.watch import _rebuild_code
@@ -119,12 +121,12 @@ 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()
content = hook_path.read_text(encoding="utf-8")
if marker in content:
return f"already installed at {hook_path}"
hook_path.write_text(content.rstrip() + "\n\n" + script)
hook_path.write_text(content.rstrip() + "\n\n" + script, encoding="utf-8", newline="\n")
return f"appended to existing {name} hook at {hook_path}"
hook_path.write_text("#!/bin/sh\n" + script)
hook_path.write_text("#!/bin/sh\n" + script, encoding="utf-8", newline="\n")
hook_path.chmod(0o755)
return f"installed at {hook_path}"
@@ -134,7 +136,7 @@ def _uninstall_hook(hooks_dir: Path, name: str, marker: str, marker_end: str) ->
hook_path = hooks_dir / name
if not hook_path.exists():
return f"no {name} hook found - nothing to remove."
content = hook_path.read_text()
content = hook_path.read_text(encoding="utf-8")
if marker not in content:
return f"graphify hook not found in {name} - nothing to remove."
new_content = re.sub(
@@ -146,7 +148,7 @@ def _uninstall_hook(hooks_dir: Path, name: str, marker: str, marker_end: str) ->
if not new_content or new_content in ("#!/bin/bash", "#!/bin/sh"):
hook_path.unlink()
return f"removed {name} hook at {hook_path}"
hook_path.write_text(new_content + "\n")
hook_path.write_text(new_content + "\n", encoding="utf-8", newline="\n")
return f"graphify removed from {name} at {hook_path} (other hook content preserved)"
@@ -189,7 +191,7 @@ def status(path: Path = Path(".")) -> 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)"
return "installed" if marker in p.read_text(encoding="utf-8") else "not installed (hook exists but graphify not found)"
commit = _check("post-commit", _HOOK_MARKER)
checkout = _check("post-checkout", _CHECKOUT_MARKER)
+11 -11
View File
@@ -82,11 +82,11 @@ def _fetch_tweet(url: str, author: str | None, contributor: str | None) -> tuple
now = datetime.now(timezone.utc).isoformat()
content = f"""---
source_url: {url}
source_url: "{_yaml_str(url)}"
type: tweet
author: {tweet_author}
author: "{_yaml_str(tweet_author)}"
captured_at: {now}
contributor: {contributor or author or 'unknown'}
contributor: "{_yaml_str(contributor or author or 'unknown')}"
---
# Tweet by @{tweet_author}
@@ -109,11 +109,11 @@ def _fetch_webpage(url: str, author: str | None, contributor: str | None) -> tup
markdown = _html_to_markdown(html, url)
now = datetime.now(timezone.utc).isoformat()
content = f"""---
source_url: {url}
source_url: "{_yaml_str(url)}"
type: webpage
title: "{_yaml_str(title)}"
captured_at: {now}
contributor: {contributor or author or 'unknown'}
contributor: "{_yaml_str(contributor or author or 'unknown')}"
---
# {title}
@@ -149,13 +149,13 @@ def _fetch_arxiv(url: str, author: str | None, contributor: str | None) -> tuple
now = datetime.now(timezone.utc).isoformat()
content = f"""---
source_url: {url}
arxiv_id: {arxiv_id.group(1) if arxiv_id else ''}
source_url: "{_yaml_str(url)}"
arxiv_id: "{_yaml_str(arxiv_id.group(1) if arxiv_id else '')}"
type: paper
title: "{title}"
paper_authors: "{paper_authors}"
title: "{_yaml_str(title)}"
paper_authors: "{_yaml_str(paper_authors)}"
captured_at: {now}
contributor: {contributor or author or 'unknown'}
contributor: "{_yaml_str(contributor or author or 'unknown')}"
---
# {title}
@@ -225,7 +225,7 @@ def ingest(url: str, target_dir: Path, author: str | None = None, contributor: s
out_path = target_dir / filename
# Avoid overwriting - append counter if needed
counter = 1
while out_path.exists():
while out_path.exists() and counter < 1000:
stem = Path(filename).stem
out_path = target_dir / f"{stem}_{counter}.md"
counter += 1
+20
View File
@@ -1,9 +1,17 @@
# generate GRAPH_REPORT.md - the human-readable audit trail
from __future__ import annotations
import re
from datetime import date
import networkx as nx
def _safe_community_name(label: str) -> str:
"""Mirrors export.safe_name so community hub filenames and report wikilinks always agree."""
cleaned = re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip()
cleaned = re.sub(r"\.(md|mdx|markdown)$", "", cleaned, flags=re.IGNORECASE)
return cleaned or "unnamed"
def generate(
G: nx.Graph,
communities: dict[int, list[str]],
@@ -48,6 +56,18 @@ def generate(
f"- Extraction: {ext_pct}% EXTRACTED · {inf_pct}% INFERRED · {amb_pct}% AMBIGUOUS"
+ (f" · INFERRED: {len(inf_edges)} edges (avg confidence: {inf_avg})" if inf_avg is not None else ""),
f"- Token cost: {token_cost.get('input', 0):,} input · {token_cost.get('output', 0):,} output",
]
# Community hub navigation - links to _COMMUNITY_*.md files in the Obsidian vault.
# Without these, GRAPH_REPORT.md is a dead-end and the vault splits into disconnected components.
if communities:
lines += ["", "## Community Hubs (Navigation)"]
for cid in communities:
label = community_labels.get(cid, f"Community {cid}")
safe = _safe_community_name(label)
lines.append(f"- [[_COMMUNITY_{safe}|{label}]]")
lines += [
"",
"## God Nodes (most connected - your core abstractions)",
]
+7 -1
View File
@@ -153,7 +153,13 @@ def validate_graph_path(path: str | Path, base: Path | None = None) -> Path:
FileNotFoundError - resolved path does not exist
"""
if base is None:
base = Path("graphify-out").resolve()
resolved_hint = Path(path).resolve()
for candidate in [resolved_hint, *resolved_hint.parents]:
if candidate.name == "graphify-out":
base = candidate
break
if base is None:
base = Path("graphify-out").resolve()
base = base.resolve()
if not base.exists():
+49 -9
View File
@@ -16,7 +16,7 @@ def _load_graph(graph_path: str) -> nx.Graph:
if not resolved.exists():
raise FileNotFoundError(f"Graph file not found: {resolved}")
safe = resolved
data = json.loads(safe.read_text())
data = json.loads(safe.read_text(encoding="utf-8"))
try:
return json_graph.node_link_graph(data, edges="links")
except TypeError:
@@ -39,12 +39,19 @@ def _communities_from_graph(G: nx.Graph) -> dict[int, list[str]]:
return communities
def _strip_diacritics(text: str) -> str:
import unicodedata
nfkd = unicodedata.normalize("NFKD", text)
return "".join(c for c in nfkd if not unicodedata.combining(c))
def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
scored = []
norm_terms = [_strip_diacritics(t).lower() for t in terms]
for nid, data in G.nodes(data=True):
label = data.get("label", "").lower()
source = data.get("source_file", "").lower()
score = sum(1 for t in terms if t in label) + sum(0.5 for t in terms if t in source)
norm_label = data.get("norm_label") or _strip_diacritics(data.get("label") or "").lower()
source = (data.get("source_file") or "").lower()
score = sum(1 for t in norm_terms if t in norm_label) + sum(0.5 for t in norm_terms if t in source)
if score > 0:
scored.append((score, nid))
return sorted(scored, reverse=True)
@@ -92,7 +99,8 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
lines.append(line)
for u, v in edges:
if u in nodes and v in nodes:
d = G.edges[u, v]
raw = G[u][v]
d = next(iter(raw.values()), {}) if isinstance(G, (nx.MultiGraph, nx.MultiDiGraph)) else raw
line = f"EDGE {sanitize_label(G.nodes[u].get('label', u))} --{d.get('relation', '')} [{d.get('confidence', '')}]--> {sanitize_label(G.nodes[v].get('label', v))}"
lines.append(line)
output = "\n".join(lines)
@@ -102,10 +110,41 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
def _find_node(G: nx.Graph, label: str) -> list[str]:
"""Return node IDs whose label or ID matches the search term (case-insensitive)."""
term = label.lower()
"""Return node IDs whose label or ID matches the search term (diacritic-insensitive)."""
term = _strip_diacritics(label).lower()
return [nid for nid, d in G.nodes(data=True)
if term in d.get("label", "").lower() or term == nid.lower()]
if term in (d.get("norm_label") or _strip_diacritics(d.get("label") or "").lower())
or term == nid.lower()]
def _filter_blank_stdin() -> None:
"""Filter blank lines from stdin before MCP reads it.
Some MCP clients (Claude Desktop, etc.) send blank lines between JSON
messages. The MCP stdio transport tries to parse every line as a
JSONRPCMessage, so a bare newline triggers a Pydantic ValidationError.
This installs an OS-level pipe that relays stdin while dropping blanks.
"""
import os
import threading
r_fd, w_fd = os.pipe()
saved_fd = os.dup(sys.stdin.fileno())
def _relay() -> None:
try:
with open(saved_fd, "rb") as src, open(w_fd, "wb") as dst:
for line in src:
if line.strip():
dst.write(line)
dst.flush()
except Exception:
pass
threading.Thread(target=_relay, daemon=True).start()
os.dup2(r_fd, sys.stdin.fileno())
os.close(r_fd)
sys.stdin = open(0, "r", closefd=False)
def serve(graph_path: str = "graphify-out/graph.json") -> None:
@@ -212,7 +251,7 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
def _tool_get_node(arguments: dict) -> str:
label = arguments["label"].lower()
matches = [(nid, d) for nid, d in G.nodes(data=True)
if label in d.get("label", "").lower() or label == nid.lower()]
if label in (d.get("label") or "").lower() or label == nid.lower()]
if not matches:
return f"No node matching '{label}' found."
nid, d = matches[0]
@@ -325,6 +364,7 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
async with stdio_server() as streams:
await server.run(streams[0], streams[1], server.create_initialization_options())
_filter_blank_stdin()
asyncio.run(main())
+3 -3
View File
@@ -38,7 +38,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
Three things it does that Claude alone cannot:
Three things it does that your AI assistant alone cannot:
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
@@ -157,7 +157,7 @@ After transcription:
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
@@ -1117,7 +1117,7 @@ Supported URL types (auto-detected):
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
- arXiv → abstract + metadata saved as `.md`
- PDF → downloaded as `.pdf`
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
- Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
- Any webpage → converted to markdown via html2text
---
+3 -3
View File
@@ -38,7 +38,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
Three things it does that Claude alone cannot:
Three things it does that your AI assistant alone cannot:
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
@@ -157,7 +157,7 @@ After transcription:
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
@@ -1117,7 +1117,7 @@ Supported URL types (auto-detected):
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
- arXiv → abstract + metadata saved as `.md`
- PDF → downloaded as `.pdf`
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
- Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
- Any webpage → converted to markdown via html2text
---
+9 -7
View File
@@ -38,7 +38,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
Three things it does that Claude alone cannot:
Three things it does that your AI assistant alone cannot:
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
@@ -156,7 +156,7 @@ After transcription:
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
@@ -230,7 +230,7 @@ Load files from `.graphify_uncached.txt`. Split into chunks of 20-25 files each.
**Step B2 - Dispatch ALL subagents in a single message (Codex)**
> **Codex platform:** Uses `spawn_agent` + `wait` + `close_agent` instead of the Agent tool.
> **Codex platform:** Uses `spawn_agent` + `wait_agent` + `close_agent` instead of the Agent tool.
> Requires `multi_agent = true` under `[features]` in `~/.codex/config.toml`.
> If `spawn_agent` is unavailable, tell the user to add that config and restart Codex.
@@ -242,7 +242,7 @@ spawn_agent(agent_type="worker", message="Your task is to perform the following.
After all agents are dispatched, collect results sequentially:
```
result = wait(handle); close_agent(handle) # repeat per handle
result = wait_agent(handle); close_agent(handle) # repeat per handle
```
Parse each result as JSON. Accumulate nodes/edges/hyperedges across all results and write to `.graphify_semantic_new.json`.
@@ -305,10 +305,12 @@ Output exactly this JSON (no other text):
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed, stop and tell the user.
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Save new results to cache:
```bash
@@ -1173,7 +1175,7 @@ Supported URL types (auto-detected):
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
- arXiv → abstract + metadata saved as `.md`
- PDF → downloaded as `.pdf`
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
- Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
- Any webpage → converted to markdown via html2text
---
+7 -5
View File
@@ -40,7 +40,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
Three things it does that Claude alone cannot:
Three things it does that your AI assistant alone cannot:
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
@@ -159,7 +159,7 @@ After transcription:
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
@@ -301,10 +301,12 @@ Output exactly this JSON (no other text):
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed, stop and tell the user.
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Save new results to cache:
```bash
@@ -1199,7 +1201,7 @@ Supported URL types (auto-detected):
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
- arXiv → abstract + metadata saved as `.md`
- PDF → downloaded as `.pdf`
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
- Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
- Any webpage → converted to markdown via html2text
---
+7 -5
View File
@@ -38,7 +38,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
Three things it does that Claude alone cannot:
Three things it does that your AI assistant alone cannot:
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
@@ -157,7 +157,7 @@ After transcription:
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
@@ -302,10 +302,12 @@ Output exactly this JSON (no other text):
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed, stop and tell the user.
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Save new results to cache:
```bash
@@ -1170,7 +1172,7 @@ Supported URL types (auto-detected):
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
- arXiv → abstract + metadata saved as `.md`
- PDF → downloaded as `.pdf`
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
- Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
- Any webpage → converted to markdown via html2text
---
File diff suppressed because it is too large. Load diff
+7 -5
View File
@@ -38,7 +38,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
Three things it does that Claude alone cannot:
Three things it does that your AI assistant alone cannot:
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
@@ -157,7 +157,7 @@ After transcription:
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
@@ -301,10 +301,12 @@ Output exactly this JSON (no other text):
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed, stop and tell the user.
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Save new results to cache:
```bash
@@ -1169,7 +1171,7 @@ Supported URL types (auto-detected):
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
- arXiv → abstract + metadata saved as `.md`
- PDF → downloaded as `.pdf`
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
- Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
- Any webpage → converted to markdown via html2text
---
+4 -2
View File
@@ -298,10 +298,12 @@ Accumulate nodes/edges/hyperedges across all results and write to `.graphify_sem
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed, stop and tell the user.
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Save new results to cache:
```bash
+7 -5
View File
@@ -41,7 +41,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
Three things it does that Claude alone cannot:
Three things it does that your AI assistant alone cannot:
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
@@ -149,7 +149,7 @@ After transcription:
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
@@ -291,10 +291,12 @@ Output exactly this JSON (no other text):
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed, stop and tell the user.
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Save new results to cache:
```powershell
@@ -1163,7 +1165,7 @@ Supported URL types (auto-detected):
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
- arXiv → abstract + metadata saved as `.md`
- PDF → downloaded as `.pdf`
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
- Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
- Any webpage → converted to markdown via html2text
---
+39 -5
View File
@@ -238,11 +238,13 @@ Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-2
Call the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.
**IMPORTANT - subagent type:** Always use `subagent_type="general-purpose"`. Do NOT use `Explore` - it is read-only and cannot write chunk files to disk, which silently drops extraction results. General-purpose has Write and Bash access which the subagent needs.
Concrete example for 3 chunks:
```
[Agent tool call 1: files 1-15]
[Agent tool call 2: files 16-30]
[Agent tool call 3: files 31-45]
[Agent tool call 1: files 1-15, subagent_type="general-purpose"]
[Agent tool call 2: files 16-30, subagent_type="general-purpose"]
[Agent tool call 3: files 31-45, subagent_type="general-purpose"]
```
All three in one message. Not three separate messages.
@@ -304,10 +306,12 @@ Output exactly this JSON (no other text):
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed, stop and tell the user.
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Save new results to cache:
```bash
@@ -544,6 +548,36 @@ else:
"
```
### Step 6b - Wiki (only if --wiki flag)
**Only run this step if `--wiki` was explicitly given in the original command.**
Run this before Step 9 (cleanup) so `.graphify_labels.json` is still available.
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.build import build_from_json
from graphify.wiki import to_wiki
from graphify.analyze import god_nodes
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
labels = {int(k): v for k, v in labels_raw.items()}
gods = god_nodes(G)
n = to_wiki(G, communities, 'graphify-out/wiki', community_labels=labels or None, cohesion=cohesion, god_nodes_data=gods)
print(f'Wiki: {n} articles written to graphify-out/wiki/')
print(' graphify-out/wiki/index.md -> agent entry point')
"
```
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
**If `--neo4j`** - generate a Cypher file for manual import:
+5 -4
View File
@@ -36,14 +36,15 @@ def validate_extraction(data: dict) -> list[str]:
f"'{node['file_type']}' - must be one of {sorted(VALID_FILE_TYPES)}"
)
# Edges
if "edges" not in data:
# Edges - accept "links" (NetworkX <= 3.1) as fallback for "edges"
edge_list = data.get("edges") if "edges" in data else data.get("links")
if edge_list is None:
errors.append("Missing required key 'edges'")
elif not isinstance(data["edges"], list):
elif not isinstance(edge_list, list):
errors.append("'edges' must be a list")
else:
node_ids = {n["id"] for n in data.get("nodes", []) if isinstance(n, dict) and "id" in n}
for i, edge in enumerate(data["edges"]):
for i, edge in enumerate(edge_list):
if not isinstance(edge, dict):
errors.append(f"Edge {i} must be an object")
continue
+24 -3
View File
@@ -34,6 +34,28 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
result = extract(code_files)
# Preserve semantic nodes/edges from a previous full run.
# AST-only rebuild replaces code nodes; doc/paper/image nodes are kept.
out = watch_path / "graphify-out"
existing_graph = out / "graph.json"
if existing_graph.exists():
try:
existing = json.loads(existing_graph.read_text(encoding="utf-8"))
code_ids = {n["id"] for n in existing.get("nodes", []) if n.get("file_type") == "code"}
sem_nodes = [n for n in existing.get("nodes", []) if n.get("file_type") != "code"]
sem_edges = [e for e in existing.get("links", existing.get("edges", []))
if e.get("confidence") in ("INFERRED", "AMBIGUOUS")
or (e.get("source") not in code_ids and e.get("target") not in code_ids)]
result = {
"nodes": result["nodes"] + sem_nodes,
"edges": result["edges"] + sem_edges,
"hyperedges": existing.get("hyperedges", []),
"input_tokens": 0,
"output_tokens": 0,
}
except Exception:
pass # corrupt graph.json - proceed with AST-only
detection = {
"files": {"code": [str(f) for f in code_files], "document": [], "paper": [], "image": []},
"total_files": len(code_files),
@@ -48,12 +70,11 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
labels = {cid: "Community " + str(cid) for cid in communities}
questions = suggest_questions(G, communities, labels)
out = watch_path / "graphify-out"
out.mkdir(exist_ok=True)
report = generate(G, communities, cohesion, labels, gods, surprises, detection,
{"input": 0, "output": 0}, str(watch_path), suggested_questions=questions)
(out / "GRAPH_REPORT.md").write_text(report)
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
to_json(G, communities, str(out / "graph.json"))
# clear stale needs_update flag if present
@@ -75,7 +96,7 @@ def _notify_only(watch_path: Path) -> None:
"""Write a flag file and print a notification (fallback for non-code-only corpora)."""
flag = watch_path / "graphify-out" / "needs_update"
flag.parent.mkdir(parents=True, exist_ok=True)
flag.write_text("1")
flag.write_text("1", encoding="utf-8")
print(f"\n[graphify watch] New or changed files detected in {watch_path}")
print("[graphify watch] Non-code files changed - semantic re-extraction requires LLM.")
print("[graphify watch] Run `/graphify --update` in Claude Code to update the graph.")
+8 -6
View File
@@ -4,11 +4,11 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.3.29"
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, OpenClaw, Factory Droid, Trae) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
version = "0.4.14"
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
readme = "README.md"
license = { file = "LICENSE" }
keywords = ["claude", "claude-code", "codex", "opencode", "cursor", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
keywords = ["claude", "claude-code", "codex", "opencode", "cursor", "gemini", "aider", "kiro", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
requires-python = ">=3.10"
dependencies = [
"networkx",
@@ -33,6 +33,7 @@ dependencies = [
"tree-sitter-elixir",
"tree-sitter-objc",
"tree-sitter-julia",
"tree-sitter-verilog",
]
[project.urls]
@@ -45,10 +46,11 @@ mcp = ["mcp"]
neo4j = ["neo4j"]
pdf = ["pypdf", "html2text"]
watch = ["watchdog"]
leiden = ["graspologic"]
svg = ["matplotlib"]
leiden = ["graspologic; python_version < '3.13'"]
office = ["python-docx", "openpyxl"]
video = ["faster-whisper", "yt-dlp"]
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic", "python-docx", "openpyxl", "faster-whisper", "yt-dlp"]
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper", "yt-dlp", "matplotlib"]
[project.scripts]
graphify = "graphify.__main__:main"
@@ -58,4 +60,4 @@ where = ["."]
include = ["graphify*"]
[tool.setuptools.package-data]
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-aider.md", "skill-copilot.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md"]
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-aider.md", "skill-copilot.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md", "skill-kiro.md"]
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Support;
class Throttle
{
public const int DEFAULT_PER_SECOND = 60;
public const int DEFAULT_PER_DAY = 10000;
}
class RateLimiter
{
public function perSecond(): int
{
return (int) config('throttle.api.per_second', 60);
}
public function perDay(): int
{
return (int) config('throttle.api.per_day', 10000);
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Providers;
class PaymentGateway {}
class StripeGateway {}
class CashierGateway {}
class AppServiceProvider
{
public function register(): void
{
$this->app->bind(PaymentGateway::class, StripeGateway::class);
$this->app->singleton(CashierGateway::class, StripeGateway::class);
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Providers;
class UserRegistered {}
class OrderPlaced {}
class SendWelcomeEmail {}
class NotifyAdmins {}
class ShipOrder {}
class EventServiceProvider
{
protected $listen = [
UserRegistered::class => [
SendWelcomeEmail::class,
NotifyAdmins::class,
],
OrderPlaced::class => [
ShipOrder::class,
],
];
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Theme;
class DefaultPalette
{
public static string $primary = '#3366ff';
public static string $accent = '#ff6633';
}
class ColorResolver
{
public function primary(): string
{
return DefaultPalette::$primary;
}
public function accent(): string
{
return DefaultPalette::$accent;
}
}
+2 -2
View File
@@ -62,8 +62,8 @@ def test_cached_files(tmp_path, cache_root):
save_cached(f2, {"nodes": [], "edges": []}, root=cache_root)
hashes = cached_files(cache_root)
assert file_hash(f1) in hashes
assert file_hash(f2) in hashes
assert file_hash(f1, cache_root) in hashes
assert file_hash(f2, cache_root) in hashes
def test_clear_cache(tmp_file, cache_root):
+1 -1
View File
@@ -22,7 +22,7 @@ def test_install_contains_expected_rules(tmp_path):
content = (tmp_path / "CLAUDE.md").read_text()
assert "GRAPH_REPORT.md" in content
assert "wiki/index.md" in content
assert "_rebuild_code" in content
assert "graphify update" in content
def test_install_appends_to_existing_claude_md(tmp_path):
+9 -2
View File
@@ -1,4 +1,5 @@
"""Tests for hooks.py - git hook install/uninstall."""
import os
import subprocess
from pathlib import Path
import pytest
@@ -23,7 +24,10 @@ def test_install_is_executable(tmp_path):
repo = _make_git_repo(tmp_path)
install(repo)
hook = repo / ".git" / "hooks" / "post-commit"
assert hook.stat().st_mode & 0o111 # executable bit set
if os.name == "nt":
assert hook.read_text(encoding="utf-8").startswith("#!/bin/sh\n")
else:
assert hook.stat().st_mode & 0o111 # executable bit set
def test_install_idempotent(tmp_path):
@@ -92,7 +96,10 @@ 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
if os.name == "nt":
assert hook.read_text(encoding="utf-8").startswith("#!/bin/sh\n")
else:
assert hook.stat().st_mode & 0o111
def test_uninstall_removes_post_checkout_hook(tmp_path):
+5 -5
View File
@@ -8,7 +8,7 @@ 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",),
"claw": (".openclaw/skills/graphify/SKILL.md",),
"droid": (".factory/skills/graphify/SKILL.md",),
"trae": (".trae/skills/graphify/SKILL.md",),
"trae-cn": (".trae-cn/skills/graphify/SKILL.md",),
@@ -39,7 +39,7 @@ def test_install_opencode(tmp_path):
def test_install_claw(tmp_path):
_install(tmp_path, "claw")
assert (tmp_path / ".claw" / "skills" / "graphify" / "SKILL.md").exists()
assert (tmp_path / ".openclaw" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_droid(tmp_path):
@@ -116,9 +116,9 @@ def _agents_install(tmp_path, platform):
_install_fn(tmp_path, platform)
def _agents_uninstall(tmp_path):
def _agents_uninstall(tmp_path, platform=""):
from graphify.__main__ import _agents_uninstall as _uninstall_fn
_uninstall_fn(tmp_path)
_uninstall_fn(tmp_path, platform=platform)
def test_codex_agents_install_writes_agents_md(tmp_path):
@@ -218,7 +218,7 @@ def test_opencode_agents_uninstall_removes_plugin(tmp_path):
"""opencode uninstall removes the plugin file and deregisters from opencode.json."""
import json as _json
_agents_install(tmp_path, "opencode")
_agents_uninstall(tmp_path)
_agents_uninstall(tmp_path, platform="opencode")
plugin = tmp_path / ".opencode" / "plugins" / "graphify.js"
assert not plugin.exists()
config_file = tmp_path / "opencode.json"
+52
View File
@@ -234,6 +234,58 @@ def test_php_finds_imports():
r = extract_php(FIXTURES / "sample.php")
assert "imports" in _relations(r)
def test_php_finds_static_property_access():
r = extract_php(FIXTURES / "sample_php_static_prop.php")
assert "uses_static_prop" in _relations(r)
def test_php_static_prop_target_is_holding_class():
r = extract_php(FIXTURES / "sample_php_static_prop.php")
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
uses_prop = [
(node_by_id.get(e["source"], e["source"]), node_by_id.get(e["target"], e["target"]))
for e in r["edges"] if e["relation"] == "uses_static_prop"
]
assert any("DefaultPalette" in tgt for _, tgt in uses_prop)
def test_php_finds_config_helper_call():
r = extract_php(FIXTURES / "sample_php_config.php")
assert "uses_config" in _relations(r)
def test_php_config_helper_target_matches_first_segment():
r = extract_php(FIXTURES / "sample_php_config.php")
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
uses_cfg = [
(node_by_id.get(e["source"], e["source"]), node_by_id.get(e["target"], e["target"]))
for e in r["edges"] if e["relation"] == "uses_config"
]
assert any("Throttle" in tgt for _, tgt in uses_cfg)
def test_php_finds_container_bind():
r = extract_php(FIXTURES / "sample_php_container.php")
assert "bound_to" in _relations(r)
def test_php_container_bind_links_contract_to_implementation():
r = extract_php(FIXTURES / "sample_php_container.php")
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
bound = [
(node_by_id.get(e["source"], e["source"]), node_by_id.get(e["target"], e["target"]))
for e in r["edges"] if e["relation"] == "bound_to"
]
assert any("PaymentGateway" in src and "StripeGateway" in tgt for src, tgt in bound)
def test_php_finds_event_listeners():
r = extract_php(FIXTURES / "sample_php_listen.php")
assert "listened_by" in _relations(r)
def test_php_event_listener_links_event_to_listener():
r = extract_php(FIXTURES / "sample_php_listen.php")
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
listened = [
(node_by_id.get(e["source"], e["source"]), node_by_id.get(e["target"], e["target"]))
for e in r["edges"] if e["relation"] == "listened_by"
]
assert any("UserRegistered" in src and "SendWelcomeEmail" in tgt for src, tgt in listened)
# ── Swift ────────────────────────────────────────────────────────────────────