Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c81c1b889 | ||
|
|
04e2960135 | ||
|
|
c713cf89fd | ||
|
|
6b2d38358b | ||
|
|
2499a1c377 | ||
|
|
0a4e6915c1 | ||
|
|
efce74dada | ||
|
|
4205ae86cb | ||
|
|
013313f8d6 | ||
|
|
b4d4ac8e9b | ||
|
|
62aac4f868 | ||
|
|
3c503400cb | ||
|
|
625ca0e2f3 | ||
|
|
271ee0aff6 | ||
|
|
0e453083de | ||
|
|
209224d08c | ||
|
|
fa388c8556 | ||
|
|
3ce9bdabf4 | ||
|
|
68bb2bd3dc |
No files matched your search
@@ -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:
|
||||
|
||||
@@ -2,6 +2,85 @@
|
||||
|
||||
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
|
||||
|
||||
## 0.4.9 (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)
|
||||
|
||||
## 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
|
||||
|
||||
@@ -2,14 +2,15 @@
|
||||
|
||||
[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja-JP.md) | [한국어](README.ko-KR.md)
|
||||
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://pypi.org/project/graphifyy/)
|
||||
[](https://pepy.tech/project/graphifyy)
|
||||
[](https://github.com/sponsors/safishamsi)
|
||||
[](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, 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. 22 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, Vue, Svelte).
|
||||
|
||||
> 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.
|
||||
|
||||
@@ -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), or [Google Antigravity](https://antigravity.google)
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
@@ -71,6 +72,7 @@ pip install graphifyy && graphify install
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| 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.
|
||||
|
||||
@@ -99,6 +101,7 @@ 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` |
|
||||
| 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.
|
||||
|
||||
@@ -112,6 +115,8 @@ After building a graph, run this once in your project:
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
Uninstall with the matching uninstall command (e.g. `graphify claude uninstall`).
|
||||
@@ -160,12 +165,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 +207,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
|
||||
|
||||
@@ -235,6 +249,8 @@ graphify trae install # AGENTS.md (Trae)
|
||||
graphify trae uninstall
|
||||
graphify trae-cn install # AGENTS.md (Trae CN)
|
||||
graphify trae-cn uninstall
|
||||
graphify antigravity install # .agent/rules + .agent/workflows (Google Antigravity)
|
||||
graphify antigravity uninstall
|
||||
|
||||
# query the graph directly from the terminal (no AI assistant needed)
|
||||
graphify query "what connects attention to the optimizer?"
|
||||
@@ -247,7 +263,7 @@ 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 + 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 +271,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 +336,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
|
||||
|
||||
|
||||
+136
-14
@@ -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,16 @@ _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,
|
||||
},
|
||||
"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 +115,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(
|
||||
@@ -298,6 +308,106 @@ 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 `python3 -c "from graphify.watch import _rebuild_code; from pathlib import Path; _rebuild_code(Path('.'))"` to keep the graph current
|
||||
"""
|
||||
|
||||
_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).
|
||||
"""
|
||||
|
||||
|
||||
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 = """\
|
||||
---
|
||||
@@ -428,7 +538,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 +614,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 +640,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 +739,18 @@ 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)")
|
||||
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 +787,8 @@ 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()
|
||||
return
|
||||
|
||||
@@ -743,17 +858,26 @@ 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 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 +922,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)
|
||||
|
||||
@@ -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),
|
||||
@@ -294,7 +298,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),
|
||||
@@ -392,7 +400,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({
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
+2
-2
@@ -55,7 +55,7 @@ def load_cached(path: Path, root: Path = Path(".")) -> dict | None:
|
||||
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
|
||||
|
||||
@@ -70,7 +70,7 @@ def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
|
||||
entry = cache_dir(root) / f"{h}.json"
|
||||
tmp = entry.with_suffix(".tmp")
|
||||
try:
|
||||
tmp.write_text(json.dumps(result))
|
||||
tmp.write_text(json.dumps(result), encoding="utf-8")
|
||||
os.replace(tmp, entry)
|
||||
except Exception:
|
||||
tmp.unlink(missing_ok=True)
|
||||
|
||||
+18
-6
@@ -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'}
|
||||
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:
|
||||
@@ -271,7 +281,7 @@ def _load_graphifyignore(root: Path) -> list[str]:
|
||||
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)
|
||||
@@ -357,6 +367,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 +439,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 +454,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:
|
||||
|
||||
+42
-11
@@ -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",
|
||||
@@ -290,15 +296,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 +344,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 +368,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 +418,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 · {G.number_of_edges()} edges · {len(communities)} communities"
|
||||
|
||||
@@ -463,7 +489,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 +706,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 +728,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 +984,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()]
|
||||
|
||||
+363
-25
@@ -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
|
||||
|
||||
|
||||
@@ -536,6 +564,10 @@ _PHP_CONFIG = LanguageConfig(
|
||||
function_types=frozenset({"function_definition", "method_declaration"}),
|
||||
import_types=frozenset({"namespace_use_clause"}),
|
||||
call_types=frozenset({"function_call_expression", "member_call_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,20 @@ 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()
|
||||
|
||||
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:
|
||||
@@ -962,12 +1060,137 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
"weight": 1.0,
|
||||
})
|
||||
|
||||
# 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,
|
||||
})
|
||||
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
|
||||
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 = []
|
||||
@@ -1004,7 +1227,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 +1364,106 @@ 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_lua(path: Path) -> dict:
|
||||
"""Extract functions, methods, require() imports, and calls from a .lua file."""
|
||||
return _extract_generic(path, _LUA_CONFIG)
|
||||
@@ -1200,7 +1523,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 +1738,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 +1926,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 +2084,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 +2239,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 +2528,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 +2726,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"})
|
||||
@@ -2622,6 +2945,9 @@ def extract(paths: list[Path]) -> dict:
|
||||
".m": extract_objc,
|
||||
".mm": extract_objc,
|
||||
".jl": extract_julia,
|
||||
".vue": extract_js,
|
||||
".svelte": extract_js,
|
||||
".dart": extract_dart,
|
||||
}
|
||||
|
||||
total = len(paths)
|
||||
@@ -2629,7 +2955,11 @@ 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)
|
||||
@@ -2668,7 +2998,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 +3008,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 +3039,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
@@ -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
@@ -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
|
||||
|
||||
@@ -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)",
|
||||
]
|
||||
|
||||
+45
-6
@@ -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()
|
||||
norm_label = data.get("norm_label") or _strip_diacritics(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)
|
||||
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)
|
||||
@@ -102,10 +109,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", "")).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:
|
||||
@@ -325,6 +363,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())
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
---
|
||||
|
||||
@@ -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
|
||||
|
||||
---
|
||||
|
||||
@@ -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
|
||||
|
||||
---
|
||||
|
||||
@@ -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
|
||||
|
||||
---
|
||||
|
||||
@@ -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
|
||||
|
||||
---
|
||||
|
||||
@@ -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
|
||||
|
||||
---
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
---
|
||||
|
||||
+9
-5
@@ -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
|
||||
|
||||
@@ -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
@@ -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.")
|
||||
|
||||
+4
-3
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "graphifyy"
|
||||
version = "0.3.29"
|
||||
version = "0.4.9"
|
||||
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"
|
||||
readme = "README.md"
|
||||
license = { file = "LICENSE" }
|
||||
@@ -45,10 +45,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"
|
||||
|
||||
Vendored
+22
@@ -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
@@ -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);
|
||||
}
|
||||
}
|
||||
Vendored
+22
@@ -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
@@ -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;
|
||||
}
|
||||
}
|
||||
+9
-2
@@ -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):
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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 ────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
Reference in new issue
Block a user