Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1184e7d4d5 | ||
|
|
d3c7f950d5 | ||
|
|
5f02b3dfe1 | ||
|
|
5164d972ed | ||
|
|
6dc07e5f99 | ||
|
|
ccdd465a08 | ||
|
|
90fac738e2 | ||
|
|
83c2f4245c | ||
|
|
b37f187767 | ||
|
|
6fe4c01bb8 | ||
|
|
a7fc2493f0 | ||
|
|
494f519bf4 | ||
|
|
d23ae1774d | ||
|
|
e6fefa8a2c | ||
|
|
0f11f6a32d | ||
|
|
e8b8e2039d | ||
|
|
e4bc87a284 | ||
|
|
0a31c0862b | ||
|
|
2a8b6c16ad | ||
|
|
014758f61d | ||
|
|
5617a7d285 | ||
|
|
154919bb64 | ||
|
|
3baf316044 | ||
|
|
0fee55726d | ||
|
|
c488808842 | ||
|
|
546fc0b346 | ||
|
|
5ae2be8ca7 | ||
|
|
fd2cc8d8a7 | ||
|
|
ef06d7d8d9 | ||
|
|
93b8ec3cde | ||
|
|
e98c1b6297 | ||
|
|
a4ae70892a | ||
|
|
a1be5abb24 | ||
|
|
0061b36c29 | ||
|
|
c88528dfa3 | ||
|
|
a7f8cab1a9 | ||
|
|
fa702bd69f | ||
|
|
1cd52f191e | ||
|
|
d7a54d7e14 | ||
|
|
8708333484 | ||
|
|
a7d1969f02 | ||
|
|
258eff3e9f | ||
|
|
a7f910667d | ||
|
|
cf7f42d3e7 | ||
|
|
24bcd6d448 |
No files matched your search
@@ -1 +0,0 @@
|
||||
github: safishamsi
|
||||
@@ -2,9 +2,9 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["v1", "v2", "v3", "main"]
|
||||
branches: ["v1", "v2", "main"]
|
||||
pull_request:
|
||||
branches: ["v1", "v2", "v3", "main"]
|
||||
branches: ["v1", "v2", "main"]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
|
||||
@@ -15,10 +15,3 @@ build/
|
||||
.graphify/
|
||||
graphify-out/
|
||||
.graphify_*.json
|
||||
.graphify_python
|
||||
.claude/
|
||||
skills/
|
||||
docs/superpowers/
|
||||
.vscode/
|
||||
openspec/
|
||||
uv.lock
|
||||
-177
@@ -1,182 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
|
||||
|
||||
## 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
|
||||
- Add: YouTube and URL video download — pass a YouTube link (or any video URL) to `/graphify add <url>` and yt-dlp downloads audio-only, which is then transcribed and added to the corpus automatically
|
||||
- Add: domain-aware Whisper prompts — god nodes from non-video files are used to build a one-sentence domain hint for Whisper via a cheap Haiku call, improving transcript accuracy on technical content
|
||||
- Add: `graphify-out/transcripts/` cache — transcripts are cached by filename so re-runs skip already-transcribed files; URLs cached by hash
|
||||
- Requires: `pip install 'graphifyy[video]'` for faster-whisper + yt-dlp
|
||||
|
||||
## 0.3.28 (2026-04-10)
|
||||
|
||||
- Fix: hook installers (Claude Code, Codex, Gemini CLI) now always remove and reinstall the hook on re-run — users upgrading from old versions no longer get stuck with a broken hook format (#182)
|
||||
- Fix: rationale node labels no longer contain bare `\r` characters on Windows/WSL CRLF files — breaks Obsidian export was silently producing invalid filenames (#176)
|
||||
- Fix: `skill-windows.md` now includes `--wiki`, `--obsidian-dir`, and `--directed` which were missing vs the main skill (#177)
|
||||
|
||||
## 0.3.27 (2026-04-10)
|
||||
|
||||
- Fix: graphify install --platform gemini now also copies the skill file to ~/.gemini/skills/graphify/SKILL.md so the /graphify trigger works in Gemini CLI (#174)
|
||||
|
||||
## 0.3.26 (2026-04-10)
|
||||
|
||||
- Fix: MCP server no longer uses a circular path validation when loading a graph outside cwd — now validates the path exists and ends in `.json` instead of checking containment within its own parent directory (security fix)
|
||||
|
||||
## 0.3.25 (2026-04-09)
|
||||
|
||||
- Fix: `graphify install --platform gemini` now routes to `gemini_install()` instead of erroring — `gemini` was missing from `_PLATFORM_CONFIG` (#171)
|
||||
- Fix: `graphify install --platform cursor` now routes to `_cursor_install()` the same way (#171)
|
||||
- Fix: `serve.py` `validate_graph_path` now passes `base=Path(graph_path).resolve().parent` so MCP server works when graph is outside cwd (#170)
|
||||
- Fix: MCP `call_tool()` handler now wraps dispatch in try/except — exceptions in tool handlers return graceful error strings instead of crashing the stdio loop (#163)
|
||||
- Fix: `_load_graphifyignore` now walks parent directories up to the `.git` boundary, matching `.gitignore` discovery behavior — subdirectory scans now inherit root ignore patterns (#168)
|
||||
- Add: Aider platform support — `graphify install --platform aider` copies skill to `~/.aider/graphify/SKILL.md`; `graphify aider install/uninstall` writes AGENTS.md rules (#74)
|
||||
- Add: GitHub Copilot CLI platform support — `graphify install --platform copilot` copies skill to `~/.copilot/skills/graphify/SKILL.md`; `graphify copilot install/uninstall` for skill management (#134)
|
||||
- Add: `--directed` flag — `build_from_json()` and `build()` now accept `directed=True` to produce a `DiGraph` preserving edge direction (source→target); `cluster()` converts to undirected internally for Leiden; `graph_diff` edge key handles directed graphs correctly (#125)
|
||||
- Add: Frontmatter-aware cache for Markdown files — `.md` files hash only the body below YAML frontmatter, so metadata-only changes (reviewed, status, tags) no longer invalidate the cache (#131)
|
||||
|
||||
## 0.3.24 (2026-04-09)
|
||||
|
||||
- Fix: `graphify codex install` (and opencode) no longer exits early when `AGENTS.md` already has the graphify section — partial installs with a missing `.codex/hooks.json` can now recover on re-run (#153)
|
||||
|
||||
## 0.3.23 (2026-04-09)
|
||||
|
||||
- Add: Gemini CLI support — `graphify gemini install` writes a `GEMINI.md` section and a `BeforeTool` hook in `.gemini/settings.json` that fires before file-read tool calls (#105)
|
||||
- Add: sponsor nudge at pipeline completion — all skill files now print a one-line sponsor link after a fresh build, not on `--update` runs
|
||||
|
||||
## 0.3.22 (2026-04-09)
|
||||
|
||||
- Add: Cursor support — `graphify cursor install` writes `.cursor/rules/graphify.mdc` with `alwaysApply: true` so the graph context is always included; `graphify cursor uninstall` removes it (#137)
|
||||
- Fix: `_rebuild_code()` KeyError — `detected[FileType.CODE]` corrected to `detected['files']['code']` matching `detect()`'s actual return shape; was silently breaking git hooks on every commit (#148)
|
||||
- Fix: `to_json()` crash on NetworkX 3.2.x — `node_link_data(G, edges="links")` now falls back to `node_link_data(G)` on older NetworkX, same shim already used for `node_link_graph` (#149)
|
||||
- Fix: README clarifies `graphifyy` is the only official PyPI package — other `graphify*` packages are not affiliated (#129)
|
||||
|
||||
## 0.3.21 (2026-04-09)
|
||||
|
||||
- Fix: Codex PreToolUse hook now places `systemMessage` at the top level of the output JSON instead of inside `hookSpecificOutput` — matches the strict schema enforced by codex-cli 0.118.0+ which uses `additionalProperties: false` (#138)
|
||||
- Fix: git hooks now use `#!/bin/sh` instead of `#!/bin/bash` — Git for Windows ships `sh.exe` not `bash`, so hooks were silently skipped on Windows (#140)
|
||||
|
||||
## 0.3.20 (2026-04-09)
|
||||
|
||||
- Fix: XSS in interactive HTML graph — node labels, file types, community names, source files, and edge relations now HTML-escaped before `innerHTML` injection; neighbor link `onclick` uses `JSON.stringify` instead of raw string interpolation
|
||||
- Add: OpenCode `tool.execute.before` plugin — `graphify opencode install` now writes `.opencode/plugins/graphify.js` and registers it in `opencode.json`, firing the graph reminder before bash calls (equivalent to Claude Code's PreToolUse hook) (#71)
|
||||
- Fix: AST-resolved call edges now carry `confidence=EXTRACTED, weight=1.0` instead of INFERRED/0.8 — tree-sitter call resolution is deterministic, not probabilistic (#127)
|
||||
- Fix: `tree-sitter>=0.23.0` now pinned in dependencies and `_check_tree_sitter_version()` guard added — stale environments now get a clear `RuntimeError` with upgrade instructions instead of a cryptic `TypeError` deep in the AST pipeline (#89)
|
||||
|
||||
## 0.3.19 (2026-04-09)
|
||||
|
||||
- Fix: install step now tries plain `pip install` before falling back to `--break-system-packages` — Homebrew and PEP 668 managed environments no longer risk environment corruption (#126)
|
||||
|
||||
## 0.3.18 (2026-04-09)
|
||||
|
||||
- Fix: `--watch` mode now respects `.graphifyignore` — `_rebuild_code` was calling `collect_files()` directly instead of `detect()`, bypassing ignore patterns (#120)
|
||||
- Fix: Codex PreToolUse hook now uses `systemMessage` instead of `additionalContext` — Codex does not support `additionalContext` and was returning an error (#121)
|
||||
- Fix: Trae link corrected from `trae.com` to `trae.ai` in README, README.zh-CN.md, README.ja-JP.md, README.ko-KR.md (#122)
|
||||
- Docs: Korean README added (README.ko-KR.md) (#112)
|
||||
- Refactor: `save_query_result` inline Python blocks in all 6 skill files replaced with `graphify save-result` CLI command — shorter, maintainable, less tokens for LLM (#114)
|
||||
- Add: `graphify save-result` CLI subcommand — saves Q&A results to memory dir without inline Python
|
||||
- Fix: HTML graph click detection now uses hover-tracking (`hoveredNodeId`) — more reliable than vis.js click params on small/dense nodes (#82)
|
||||
- Fix: `mkdir -p graphify-out` now runs before writing `.graphify_python` in `skill.md` — prevents write failure on first run; `.graphify_python` no longer deleted in Step 9 cleanup across all skill files so follow-up commands keep their interpreter (#93)
|
||||
- Fix: `skill-trae.md` added to `pyproject.toml` package-data — Trae users no longer hit `ModuleNotFoundError` after `pip install` (#102)
|
||||
- Fix: `analyze.py` and `watch.py` now import extension sets from `detect.py` instead of local copies — Swift, Lua, Zig, PowerShell, Elixir, JSX, Julia, Objective-C files no longer misclassified as documents (#109)
|
||||
- Refactor: dead `build_graph()` function removed from `cluster.py` (#109)
|
||||
|
||||
## 0.3.17 (2026-04-08)
|
||||
|
||||
- Add: Julia (.jl) support — modules, structs, abstract types, functions, short functions, using/import, call edges, inherits edges via tree-sitter-julia (#98)
|
||||
- Fix: Semantic extraction chunks now group files by directory so related artifacts land in the same chunk, reducing missed cross-chunk relationships (#65)
|
||||
- Fix: `tree-sitter>=0.21` now pinned in dependencies — prevents silent empty AST output when older tree-sitter is installed with newer language bindings (#52)
|
||||
- Add: Progress output every 100 files during AST extraction so large projects don't appear to hang (#52)
|
||||
|
||||
## 0.3.16 (2026-04-08)
|
||||
|
||||
- Fix: `graphify query`, `serve`, and `benchmark` now work on NetworkX < 3.4 — version-safe shim for `node_link_graph()` at all call sites (#95)
|
||||
- Fix: `.jsx` files now detected and extracted via the JS extractor — added to `CODE_EXTENSIONS` and `_DISPATCH` (#94)
|
||||
- Fix: `.graphify_python` no longer deleted in Step 9 cleanup across all 6 skill files — pipx users no longer hit `ModuleNotFoundError` on follow-up commands (#92)
|
||||
|
||||
## 0.3.15 (2026-04-08)
|
||||
|
||||
- Feat: Trae and Trae CN platform support (`graphify install --platform trae` / `trae-cn`)
|
||||
- Fix: `skill-droid.md` was missing from PyPI package data — Factory Droid users couldn't install the skill
|
||||
- Fix: XSS in HTML legend — community labels now HTML-escaped before `innerHTML` injection
|
||||
- Fix: Shebang allowlist validation in `hooks.py` and all 6 skill files — prevents metacharacter injection from malicious binaries
|
||||
- Fix: `louvain_communities()` kwargs now inspected at runtime for cross-version NetworkX compatibility
|
||||
- Fix: pipx installs now detected correctly in git hooks (reads shebang from graphify binary)
|
||||
- Fix: graspologic ANSI escape codes no longer corrupt PowerShell 5.1 scroll buffer
|
||||
- Docs: Japanese README added
|
||||
- Docs: `graph.json` + LLM workflow example added to README
|
||||
- Docs: Codex PreToolUse hook now documented in platform table
|
||||
|
||||
## 0.3.14 (2026-04-08)
|
||||
|
||||
- Fix: `graphify codex install` now also writes a PreToolUse hook to `.codex/hooks.json` so the graph reminder fires before every Bash tool call (#86)
|
||||
- Fix: `--update` now prunes ghost nodes from deleted files before merging new extraction (#51)
|
||||
|
||||
## 0.3.13 (2026-04-08)
|
||||
|
||||
- Fix: PreToolUse hook now outputs `additionalContext` JSON so Claude actually sees the graph reminder before Glob/Grep calls (#83)
|
||||
- Fix: Go AST method receivers and type declarations now use package directory scope, eliminating disconnected duplicate type nodes across files in the same package (#85)
|
||||
- Fix: PDFs inside Xcode asset catalogs (`.imageset`, `.xcassets`) are no longer misclassified as academic papers (#52)
|
||||
- Fix: `_resolve_cross_file_imports` is now guarded with `if py_paths` and wrapped in try/except so a Python parser crash can't abort extraction for non-Python files (#52)
|
||||
- Fix: Skill intermediate files (`.graphify_*.json`) now live in `graphify-out/` instead of project root, preventing git pollution (#81)
|
||||
|
||||
## 0.3.12 (2026-04-07)
|
||||
|
||||
- Fix: `sanitize_label` was double-encoding HTML entities in the interactive graph (`&lt;` instead of `<`) — removed `html.escape()` from `sanitize_label`; callers that inject directly into HTML now call `html.escape()` themselves (#66)
|
||||
- Fix: `--wiki` flag missing from `skill.md` usage table (#55)
|
||||
|
||||
## 0.3.11 (2026-04-07)
|
||||
|
||||
- Fix: Louvain fallback hangs indefinitely on large sparse graphs — added `max_level=10, threshold=1e-4` to prevent infinite loops while preserving community quality (#48)
|
||||
|
||||
## 0.3.10 (2026-04-07)
|
||||
|
||||
- Fix: Windows UnicodeEncodeError during `graphify install` — replaced arrow character with `->` in all print statements (#47)
|
||||
- Add: skill version staleness check — warns when installed skill is older than the current package, across all platforms (#46)
|
||||
|
||||
## 0.3.9 (2026-04-07)
|
||||
|
||||
- Add: `follow_symlinks` parameter to `detect()` and `collect_files()` — opt-in symlink following with circular symlink cycle detection (#33)
|
||||
- Fix: `watch.py` now uses `collect_files()` instead of manual rglob loop for consistency
|
||||
- Docs: Codex uses `$graphify .` not `/graphify .` (#36)
|
||||
- Test: 5 new symlink tests (367 total)
|
||||
|
||||
## 0.3.8 (2026-04-07)
|
||||
|
||||
- Add: C# inheritance and interface implementation extraction — `base_list` now emits `inherits` edges for both simple (`identifier`) and generic (`generic_name`) base types (#45)
|
||||
- Add: `graphify query "<question>"` CLI command — BFS/DFS traversal of `graph.json` without needing Claude Code skill (`--dfs`, `--budget N`, `--graph <path>` flags)
|
||||
- Test: 2 new C# inheritance tests (362 total)
|
||||
|
||||
## 0.3.7 (2026-04-07)
|
||||
|
||||
- Add: Objective-C support (`.m`, `.mm`) — `@interface`, `@implementation`, `@protocol`, method declarations, `#import` directives, message-expression call edges
|
||||
- Add: `--obsidian-dir <path>` flag — write Obsidian vault to a custom directory instead of `graphify-out/obsidian`
|
||||
- Fix: semantic cache was only saving 4/17 files — relative paths from subagents now resolved against corpus root before existence check
|
||||
- Fix: 75 validation warnings per run for `file_type: "rationale"` — added `"rationale"` to `VALID_FILE_TYPES`
|
||||
- Test: 6 Objective-C tests; `.m`/`.mm` added to `test_collect_files_from_dir` supported set (360 total)
|
||||
|
||||
## 0.3.0 (2026-04-06)
|
||||
|
||||
- Add: multi-platform support — Codex (`skill-codex.md`), OpenCode (`skill-opencode.md`), OpenClaw (`skill-claw.md`)
|
||||
- Add: `graphify install --platform <codex|opencode|claw>` routes skill to correct config directory
|
||||
- Add: `graphify codex install` / `opencode install` / `claw install` — writes AGENTS.md for always-on graph-first behaviour
|
||||
- Add: `graphify claude uninstall` / `codex uninstall` / `opencode uninstall` / `claw uninstall`
|
||||
- Add: MIT license
|
||||
- Fix: `build()` was silently dropping hyperedges when merging multiple extractions
|
||||
- Refactor: `extract.py` 2527 → 1588 lines — replaced 12 copy-pasted language extractors with `LanguageConfig` dataclass + `_extract_generic()`
|
||||
- Docs: clustering is graph-topology-based (no embeddings) — explained in README
|
||||
- Docs: all missing flags documented (`--cluster-only`, `--no-viz`, `--neo4j-push`, `query --dfs`, `query --budget`, `add --author`, `add --contributor`)
|
||||
|
||||
## 0.2.2 (2026-04-06)
|
||||
|
||||
- Add: `graphify claude install` — writes graphify section to local CLAUDE.md + PreToolUse hook in `.claude/settings.json`
|
||||
- Add: `graphify claude uninstall` — removes section and hook
|
||||
- Add: `graphify hook install` — installs post-commit and post-checkout git hooks (platform-agnostic)
|
||||
- Add: `graphify hook uninstall` / `hook status`
|
||||
- Add: `graphify benchmark` CLI command
|
||||
- Fix: node deduplication documented at all three layers
|
||||
|
||||
## 0.1.8 (2026-04-05)
|
||||
|
||||
- Fix: follow-up questions now check for wiki first (graphify-out/wiki/index.md) before falling back to graph.json
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Safi Shamsi
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
-238
@@ -1,238 +0,0 @@
|
||||
# graphify
|
||||
|
||||
[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://pypi.org/project/graphifyy/)
|
||||
[](https://github.com/sponsors/safishamsi)
|
||||
|
||||
**AIコーディングアシスタント向けのスキル。** Claude Code、Codex、OpenCode、OpenClaw、Factory Droid で `/graphify` と入力するだけで、ファイルを読み込んでナレッジグラフを構築し、あなたが気づいていなかった構造を返します。コードベースをより速く理解し、アーキテクチャ上の意思決定の「なぜ」を見つけ出します。
|
||||
|
||||
完全にマルチモーダル対応。コード、PDF、Markdown、スクリーンショット、図、ホワイトボード写真、他言語の画像まで――graphify は Claude Vision を使ってそれらすべてから概念と関係性を抽出し、1 つのグラフに接続します。tree-sitter AST により 19 言語をサポート(Python、JS、TS、Go、Rust、Java、C、C++、Ruby、C#、Kotlin、Scala、PHP、Swift、Lua、Zig、PowerShell、Elixir、Objective-C)。
|
||||
|
||||
> Andrej Karpathy は論文、ツイート、スクリーンショット、メモを放り込む `/raw` フォルダを持っています。graphify はまさにその問題への答えです――生ファイルを読むのに比べて1クエリあたりのトークン数が 71.5 倍少なく、セッションをまたいで永続化され、見つけたものと推測したものを正直に区別します。
|
||||
|
||||
```
|
||||
/graphify . # どのフォルダでも動作 - コードベース、メモ、論文、なんでも
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html インタラクティブなグラフ - ノードをクリック、検索、コミュニティでフィルタ
|
||||
├── GRAPH_REPORT.md ゴッドノード、意外なつながり、推奨される質問
|
||||
├── graph.json 永続化されたグラフ - 数週間後でも再読み込みなしでクエリ可能
|
||||
└── cache/ SHA256 キャッシュ - 再実行時は変更されたファイルのみ処理
|
||||
```
|
||||
|
||||
グラフに含めたくないフォルダを除外するには `.graphifyignore` ファイルを追加します:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
構文は `.gitignore` と同じです。パターンは graphify を実行したフォルダからの相対パスに対してマッチします。
|
||||
|
||||
## 仕組み
|
||||
|
||||
graphify は 2 パスで動作します。まず、決定論的な AST パスがコードファイルから構造(クラス、関数、インポート、コールグラフ、docstring、根拠コメント)を LLM なしで抽出します。次に、Claude サブエージェントがドキュメント、論文、画像に対して並列に実行され、概念、関係性、設計の根拠を抽出します。結果は NetworkX グラフにマージされ、Leiden コミュニティ検出でクラスタリングされ、インタラクティブ HTML、クエリ可能な JSON、平易な言葉の監査レポートとしてエクスポートされます。
|
||||
|
||||
**クラスタリングはグラフトポロジベース――埋め込みは使いません。** Leiden はエッジ密度によってコミュニティを見つけます。Claude が抽出する意味的類似性エッジ(`semantically_similar_to`、INFERRED とマーク)は既にグラフに含まれているため、コミュニティ検出に直接影響します。グラフ構造そのものが類似性シグナルであり――別途の埋め込みステップやベクターデータベースは不要です。
|
||||
|
||||
すべての関係は `EXTRACTED`(ソースから直接見つかった)、`INFERRED`(合理的な推論、信頼度スコア付き)、`AMBIGUOUS`(レビュー対象としてフラグ付け)のいずれかでタグ付けされます。何が見つかったもので何が推測されたものか、常に分かります。
|
||||
|
||||
## インストール
|
||||
|
||||
**必要なもの:** Python 3.10+ および以下のいずれか: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [OpenClaw](https://openclaw.ai), または [Factory Droid](https://factory.ai)
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> PyPI パッケージは `graphify` の名前が再取得されるまでの間、一時的に `graphifyy` となっています。CLI とスキルコマンドは依然として `graphify` です。
|
||||
|
||||
### プラットフォームサポート
|
||||
|
||||
| プラットフォーム | インストールコマンド |
|
||||
|----------|----------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install`(自動検出)または `graphify install --platform windows` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
|
||||
Codex ユーザーは並列抽出のために `~/.codex/config.toml` の `[features]` の下に `multi_agent = true` も必要です。Factory Droid は並列サブエージェントディスパッチに `Task` ツールを使用します。OpenClaw は逐次抽出を使用します(並列エージェントサポートはこのプラットフォームではまだ初期段階です)。
|
||||
|
||||
次に、AI コーディングアシスタントを開いて入力します:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
注意:Codex はスキル呼び出しに `/` ではなく `$` を使用するため、代わりに `$graphify .` と入力してください。
|
||||
|
||||
### アシスタントに常にグラフを使わせる(推奨)
|
||||
|
||||
グラフを構築した後、プロジェクトで一度だけ以下を実行します:
|
||||
|
||||
| プラットフォーム | コマンド |
|
||||
|----------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
| Factory Droid | `graphify droid install` |
|
||||
|
||||
**Claude Code** は 2 つのことを行います:Claude にアーキテクチャの質問に答える前に `graphify-out/GRAPH_REPORT.md` を読むように指示する `CLAUDE.md` セクションを書き込み、すべての Glob と Grep 呼び出しの前に発火する **PreToolUse フック**(`settings.json`)をインストールします。ナレッジグラフが存在する場合、Claude は次のメッセージを見ます:_"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ ――これにより Claude はすべてのファイルを grep するのではなく、グラフを介してナビゲートします。
|
||||
|
||||
**Codex、OpenCode、OpenClaw、Factory Droid** は同じルールをプロジェクトルートの `AGENTS.md` に書き込みます。これらのプラットフォームは PreToolUse フックをサポートしていないため、AGENTS.md が常時有効のメカニズムとなります。
|
||||
|
||||
アンインストールは対応するアンインストールコマンドで行います(例:`graphify claude uninstall`)。
|
||||
|
||||
**常時有効 vs 明示的トリガー――何が違うのか?**
|
||||
|
||||
常時有効のフックは `GRAPH_REPORT.md` を表面化します――これはゴッドノード、コミュニティ、意外なつながりを 1 ページにまとめた要約です。アシスタントはファイル検索の前にこれを読み、キーワードマッチではなく構造に基づいてナビゲートします。これで日常的な質問のほとんどをカバーできます。
|
||||
|
||||
`/graphify query`、`/graphify path`、`/graphify explain` はさらに深く踏み込みます:生の `graph.json` をホップごとに辿り、ノード間の正確なパスをトレースし、エッジレベルの詳細(関係タイプ、信頼度スコア、ソース位置)を表面化します。一般的なオリエンテーションではなく、特定の質問をグラフから答えさせたいときに使います。
|
||||
|
||||
こう考えてください:常時有効のフックはアシスタントに地図を与え、`/graphify` コマンドはその地図を正確にナビゲートさせます。
|
||||
|
||||
<details>
|
||||
<summary>手動インストール(curl)</summary>
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/graphify
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
|
||||
> ~/.claude/skills/graphify/SKILL.md
|
||||
```
|
||||
|
||||
`~/.claude/CLAUDE.md` に追加します:
|
||||
|
||||
```
|
||||
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## 使い方
|
||||
|
||||
```
|
||||
/graphify # カレントディレクトリで実行
|
||||
/graphify ./raw # 特定のフォルダで実行
|
||||
/graphify ./raw --mode deep # より積極的な INFERRED エッジ抽出
|
||||
/graphify ./raw --update # 変更されたファイルのみ再抽出し、既存グラフにマージ
|
||||
/graphify ./raw --cluster-only # 既存グラフのクラスタリングを再実行(再抽出なし)
|
||||
/graphify ./raw --no-viz # HTML をスキップ、レポート + JSON のみ生成
|
||||
/graphify ./raw --obsidian # Obsidian ボールトも生成(オプトイン)
|
||||
/graphify ./raw --obsidian --obsidian-dir ~/vaults/myproject # ボールトを特定のディレクトリに書き込み
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # 論文を取得、保存、グラフを更新
|
||||
/graphify add https://x.com/karpathy/status/... # ツイートを取得
|
||||
/graphify add https://... --author "Name" # 元の著者をタグ付け
|
||||
/graphify add https://... --contributor "Name" # コーパスに追加した人をタグ付け
|
||||
|
||||
/graphify query "アテンションとオプティマイザを結ぶものは?"
|
||||
/graphify query "アテンションとオプティマイザを結ぶものは?" --dfs # 特定のパスをトレース
|
||||
/graphify query "アテンションとオプティマイザを結ぶものは?" --budget 1500 # N トークンで上限設定
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
/graphify ./raw --watch # ファイル変更時にグラフを自動同期(コード:即時、ドキュメント:通知)
|
||||
/graphify ./raw --wiki # エージェントがクロール可能な wiki を構築(index.md + コミュニティごとの記事)
|
||||
/graphify ./raw --svg # graph.svg をエクスポート
|
||||
/graphify ./raw --graphml # graph.graphml をエクスポート(Gephi、yEd)
|
||||
/graphify ./raw --neo4j # Neo4j 用の cypher.txt を生成
|
||||
/graphify ./raw --neo4j-push bolt://localhost:7687 # 実行中の Neo4j インスタンスに直接プッシュ
|
||||
/graphify ./raw --mcp # MCP stdio サーバーを起動
|
||||
|
||||
# git フック - プラットフォーム非依存、コミット時とブランチ切り替え時にグラフを再構築
|
||||
graphify hook install
|
||||
graphify hook uninstall
|
||||
graphify hook status
|
||||
|
||||
# 常時有効のアシスタント指示 - プラットフォーム固有
|
||||
graphify claude install # CLAUDE.md + PreToolUse フック(Claude Code)
|
||||
graphify claude uninstall
|
||||
graphify codex install # AGENTS.md(Codex)
|
||||
graphify opencode install # AGENTS.md(OpenCode)
|
||||
graphify claw install # AGENTS.md(OpenClaw)
|
||||
graphify droid install # AGENTS.md(Factory Droid)
|
||||
|
||||
# ターミナルから直接グラフをクエリ(AI アシスタント不要)
|
||||
graphify query "アテンションとオプティマイザを結ぶものは?"
|
||||
graphify query "認証フローを表示" --dfs
|
||||
graphify query "CfgNode とは?" --budget 500
|
||||
graphify query "..." --graph path/to/graph.json
|
||||
```
|
||||
|
||||
あらゆるファイルタイプの組み合わせで動作します:
|
||||
|
||||
| タイプ | 拡張子 | 抽出方法 |
|
||||
|------|-----------|------------|
|
||||
| コード | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm` | tree-sitter による AST + コールグラフ + docstring/コメントの根拠 |
|
||||
| ドキュメント | `.md .txt .rst` | Claude による概念 + 関係性 + 設計根拠 |
|
||||
| Office | `.docx .xlsx` | Markdown に変換した後 Claude で抽出(`pip install graphifyy[office]` が必要) |
|
||||
| 論文 | `.pdf` | 引用マイニング + 概念抽出 |
|
||||
| 画像 | `.png .jpg .webp .gif` | Claude Vision - スクリーンショット、図、任意の言語 |
|
||||
|
||||
## 得られるもの
|
||||
|
||||
**ゴッドノード** - 最高次数の概念(すべてが接続するもの)
|
||||
|
||||
**意外なつながり** - 複合スコアでランク付け。コード-論文のエッジはコード-コードよりも高くランクされます。各結果には平易な英語の理由が含まれます。
|
||||
|
||||
**推奨される質問** - グラフがユニークに答えられる 4〜5 の質問
|
||||
|
||||
**「なぜ」** - docstring、インラインコメント(`# NOTE:`、`# IMPORTANT:`、`# HACK:`、`# WHY:`)、ドキュメントからの設計根拠が `rationale_for` ノードとして抽出されます。コードが何をするかだけでなく――なぜそのように書かれたか。
|
||||
|
||||
**信頼度スコア** - すべての INFERRED エッジには `confidence_score`(0.0〜1.0)があります。何が推測されたかだけでなく、モデルがどれだけ確信していたかもわかります。EXTRACTED エッジは常に 1.0 です。
|
||||
|
||||
**意味的類似性エッジ** - 構造的接続のないクロスファイル概念リンク。互いを呼び出さずに同じ問題を解いている 2 つの関数、同じアルゴリズムを記述しているコード内のクラスと論文内の概念など。
|
||||
|
||||
**ハイパーエッジ** - ペアワイズエッジでは表現できない 3+ ノードを接続するグループ関係。共有プロトコルを実装するすべてのクラス、認証フロー内のすべての関数、論文セクションから 1 つのアイデアを形成するすべての概念など。
|
||||
|
||||
**トークンベンチマーク** - 実行ごとに自動的に出力されます。混合コーパス(Karpathy リポジトリ + 論文 + 画像)で、生ファイルを読むのに比べて 1 クエリあたり **71.5 倍** 少ないトークン。最初の実行で抽出とグラフ構築を行います(これにはトークンがかかります)。以降のクエリはすべて生ファイルではなくコンパクトなグラフを読みます――ここで節約が複利的に効いてきます。SHA256 キャッシュにより、再実行時は変更されたファイルのみ再処理されます。
|
||||
|
||||
**自動同期** (`--watch`) - バックグラウンドターミナルで実行し、コードベースが変更されるとグラフが自動的に更新されます。コードファイルの保存は即座の再構築をトリガーします(AST のみ、LLM なし)。ドキュメント/画像の変更は、LLM の再パスのために `--update` を実行するよう通知します。
|
||||
|
||||
**Git フック** (`graphify hook install`) - post-commit と post-checkout フックをインストールします。コミットごと、ブランチ切り替えごとにグラフが自動的に再構築されます。再構築が失敗した場合、フックは非ゼロコードで終了するため、git がエラーを表面化し、静かに続行することはありません。バックグラウンドプロセスは不要です。
|
||||
|
||||
**Wiki** (`--wiki`) - コミュニティごとおよびゴッドノードごとの Wikipedia スタイルの Markdown 記事と、`index.md` エントリポイント。任意のエージェントを `index.md` に向ければ、JSON をパースする代わりにファイルを読むことでナレッジベースをナビゲートできます。
|
||||
|
||||
## 実例
|
||||
|
||||
| コーパス | ファイル数 | 削減率 | 出力 |
|
||||
|--------|-------|-----------|--------|
|
||||
| Karpathy リポジトリ + 論文5本 + 画像4枚 | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
|
||||
| graphify ソース + Transformer 論文 | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
|
||||
| httpx(合成 Python ライブラリ) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
|
||||
|
||||
トークン削減はコーパスサイズに応じてスケールします。6 ファイルはいずれにせよコンテキストウィンドウに収まるため、そこでのグラフの価値は圧縮ではなく構造的明瞭さです。52 ファイル(コード + 論文 + 画像)では 71 倍以上が得られます。各 `worked/` フォルダには生の入力ファイルと実際の出力(`GRAPH_REPORT.md`、`graph.json`)があり、自分で実行して数字を検証できます。
|
||||
|
||||
## プライバシー
|
||||
|
||||
graphify はドキュメント、論文、画像の意味的抽出のために、ファイル内容を AI コーディングアシスタントの基盤モデル API に送信します――Anthropic(Claude Code)、OpenAI(Codex)、またはプラットフォームが使用するプロバイダーです。コードファイルは tree-sitter AST を介してローカルで処理されます――コードに関してはファイル内容がマシンから出ることはありません。テレメトリ、利用追跡、分析は一切ありません。ネットワーク呼び出しは抽出中のプラットフォームのモデル API への呼び出しのみで、あなた自身の API キーを使用します。
|
||||
|
||||
## 技術スタック
|
||||
|
||||
NetworkX + Leiden(graspologic) + tree-sitter + vis.js。意味的抽出は Claude(Claude Code)、GPT-4(Codex)、またはプラットフォームが実行するモデルを介して行われます。Neo4j は不要、サーバーも不要、完全にローカルで実行されます。
|
||||
|
||||
## スター履歴
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
|
||||
<details>
|
||||
<summary>コントリビューション</summary>
|
||||
|
||||
**実例** は最も信頼を築くコントリビューションです。実際のコーパスで `/graphify` を実行し、出力を `worked/{slug}/` に保存し、グラフが正しく捉えたもの・間違えたものを評価する正直な `review.md` を書き、PR を提出してください。
|
||||
|
||||
**抽出バグ** - 入力ファイル、キャッシュエントリ(`graphify-out/cache/`)、何が見逃された/捏造されたかを添えて issue を開いてください。
|
||||
|
||||
モジュールの責任と言語の追加方法については [ARCHITECTURE.md](ARCHITECTURE.md) を参照してください。
|
||||
|
||||
</details>
|
||||
-282
@@ -1,282 +0,0 @@
|
||||
# graphify
|
||||
|
||||
[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://pypi.org/project/graphifyy/)
|
||||
[](https://github.com/sponsors/safishamsi)
|
||||
|
||||
**AI 코딩 어시스턴트를 위한 스킬.** Claude Code, Codex, OpenCode, OpenClaw, Factory Droid, 또는 Trae에서 `/graphify`를 입력하면 파일을 읽고 지식 그래프를 구축하여, 미처 몰랐던 구조를 보여줍니다. 코드베이스를 더 빠르게 이해하고, 아키텍처 결정의 "이유"를 찾아보세요.
|
||||
|
||||
완전한 멀티모달 지원. 코드, PDF, 마크다운, 스크린샷, 다이어그램, 화이트보드 사진, 심지어 다른 언어로 된 이미지까지 — graphify는 Claude Vision을 사용하여 이 모든 것에서 개념과 관계를 추출하고 하나의 그래프로 연결합니다. tree-sitter AST를 통해 20개 언어를 지원합니다(Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia).
|
||||
|
||||
> Andrej Karpathy는 논문, 트윗, 스크린샷, 메모를 모아두는 `/raw` 폴더를 관리합니다. graphify는 바로 그 문제에 대한 답입니다 — 원본 파일을 직접 읽는 것 대비 쿼리당 토큰 소비가 71.5배 적고, 세션 간에 영속적이며, 발견한 것과 추측한 것을 정직하게 구분합니다.
|
||||
|
||||
```
|
||||
/graphify . # 어떤 폴더든 동작 - 코드베이스, 노트, 논문, 무엇이든
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html 인터랙티브 그래프 - 노드 클릭, 검색, 커뮤니티별 필터
|
||||
├── GRAPH_REPORT.md 갓 노드, 의외의 연결, 추천 질문
|
||||
├── graph.json 영속 그래프 - 몇 주 후에도 재읽기 없이 쿼리 가능
|
||||
└── cache/ SHA256 캐시 - 재실행 시 변경된 파일만 처리
|
||||
```
|
||||
|
||||
그래프에 포함하지 않을 폴더를 제외하려면 `.graphifyignore` 파일을 추가하세요:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
`.gitignore`와 동일한 문법입니다. 패턴은 graphify를 실행한 폴더 기준의 상대 경로에 대해 매칭됩니다.
|
||||
|
||||
## 동작 원리
|
||||
|
||||
graphify는 두 번의 패스로 실행됩니다. 첫 번째는 결정론적 AST 패스로, 코드 파일에서 구조(클래스, 함수, 임포트, 콜 그래프, docstring, 근거 주석)를 LLM 없이 추출합니다. 두 번째는 Claude 서브에이전트가 문서, 논문, 이미지에 대해 병렬로 실행되어 개념, 관계, 설계 근거를 추출합니다. 결과는 NetworkX 그래프로 병합되고, Leiden 커뮤니티 탐지로 클러스터링되며, 인터랙티브 HTML, 쿼리 가능한 JSON, 그리고 일반 언어 감사 보고서로 내보내집니다.
|
||||
|
||||
**클러스터링은 그래프 토폴로지 기반 — 임베딩을 사용하지 않습니다.** Leiden은 엣지 밀도를 기반으로 커뮤니티를 찾습니다. Claude가 추출하는 의미적 유사성 엣지(`semantically_similar_to`, INFERRED로 표시)는 이미 그래프에 포함되어 있으므로 커뮤니티 탐지에 직접 영향을 줍니다. 그래프 구조 자체가 유사성 신호이며 — 별도의 임베딩 단계나 벡터 데이터베이스가 필요하지 않습니다.
|
||||
|
||||
모든 관계는 `EXTRACTED`(소스에서 직접 발견), `INFERRED`(합리적 추론, 신뢰도 점수 포함), `AMBIGUOUS`(리뷰 필요 표시) 중 하나로 태깅됩니다. 무엇이 발견된 것이고 무엇이 추측된 것인지 항상 알 수 있습니다.
|
||||
|
||||
## 설치
|
||||
|
||||
**필수 요구사항:** Python 3.10+ 및 다음 중 하나: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), 또는 [Trae](https://trae.ai)
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> PyPI 패키지는 `graphify` 이름을 되찾는 동안 임시로 `graphifyy`로 명명되어 있습니다. CLI와 스킬 명령은 여전히 `graphify`입니다.
|
||||
|
||||
### 플랫폼 지원
|
||||
|
||||
| 플랫폼 | 설치 명령 |
|
||||
|--------|-----------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (자동 감지) 또는 `graphify install --platform windows` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
|
||||
Codex 사용자는 병렬 추출을 위해 `~/.codex/config.toml`의 `[features]` 아래에 `multi_agent = true`도 필요합니다. Factory Droid는 병렬 서브에이전트 디스패치에 `Task` 도구를 사용합니다. OpenClaw는 순차 추출을 사용합니다(해당 플랫폼의 병렬 에이전트 지원은 아직 초기 단계입니다). Trae는 병렬 서브에이전트 디스패치에 Agent 도구를 사용하며 PreToolUse 훅을 **지원하지 않습니다** — AGENTS.md가 상시 작동 메커니즘입니다.
|
||||
|
||||
그런 다음 AI 코딩 어시스턴트를 열고 입력하세요:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
참고: Codex는 스킬 호출에 `/` 대신 `$`를 사용하므로 `$graphify .`라고 입력하세요.
|
||||
|
||||
### 어시스턴트가 항상 그래프를 사용하도록 설정 (권장)
|
||||
|
||||
그래프를 빌드한 후, 프로젝트에서 한 번만 실행하세요:
|
||||
|
||||
| 플랫폼 | 명령 |
|
||||
|--------|------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
| Factory Droid | `graphify droid install` |
|
||||
| Trae | `graphify trae install` |
|
||||
| Trae CN | `graphify trae-cn install` |
|
||||
|
||||
**Claude Code**는 두 가지를 수행합니다: 아키텍처 질문에 답하기 전에 `graphify-out/GRAPH_REPORT.md`를 읽도록 Claude에게 지시하는 `CLAUDE.md` 섹션을 작성하고, 모든 Glob 및 Grep 호출 전에 실행되는 **PreToolUse 훅**(`settings.json`)을 설치합니다. 지식 그래프가 존재하면 Claude는 다음 메시지를 보게 됩니다: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ — 이를 통해 Claude는 모든 파일을 grep하는 대신 그래프를 통해 탐색합니다.
|
||||
|
||||
**Codex**는 `AGENTS.md`에 작성하고 Bash 도구 호출 전에 실행되는 **PreToolUse 훅**을 `.codex/hooks.json`에 설치합니다 — Claude Code와 동일한 상시 작동 메커니즘입니다.
|
||||
|
||||
**OpenCode, OpenClaw, Factory Droid, Trae**는 프로젝트 루트의 `AGENTS.md`에 동일한 규칙을 작성합니다. 이 플랫폼들은 PreToolUse 훅을 지원하지 않으므로 AGENTS.md가 상시 작동 메커니즘입니다.
|
||||
|
||||
제거는 대응하는 uninstall 명령으로 수행합니다(예: `graphify claude uninstall`).
|
||||
|
||||
**상시 작동 vs 명시적 트리거 — 차이점은?**
|
||||
|
||||
상시 작동 훅은 `GRAPH_REPORT.md`를 노출합니다 — 갓 노드, 커뮤니티, 의외의 연결을 한 페이지로 요약한 것입니다. 어시스턴트는 파일 검색 전에 이것을 읽으므로 키워드 매칭이 아닌 구조 기반으로 탐색합니다. 이것만으로 대부분의 일상적인 질문을 처리할 수 있습니다.
|
||||
|
||||
`/graphify query`, `/graphify path`, `/graphify explain`은 더 깊이 들어갑니다: 원시 `graph.json`을 홉 단위로 순회하고, 노드 간의 정확한 경로를 추적하며, 엣지 수준의 세부 정보(관계 유형, 신뢰도 점수, 소스 위치)를 보여줍니다. 일반적인 오리엔테이션이 아닌 그래프에서 특정 질문에 답하고 싶을 때 사용하세요.
|
||||
|
||||
이렇게 생각하면 됩니다: 상시 작동 훅은 어시스턴트에게 지도를 주고, `/graphify` 명령은 그 지도를 정확하게 탐색하게 합니다.
|
||||
|
||||
## `graph.json`을 LLM과 함께 사용하기
|
||||
|
||||
`graph.json`은 프롬프트에 한 번에 전부 붙여넣기 위한 것이 아닙니다. 유용한 워크플로우는 다음과 같습니다:
|
||||
|
||||
1. `graphify-out/GRAPH_REPORT.md`로 높은 수준의 개요를 파악합니다.
|
||||
2. `graphify query`를 사용하여 답하려는 특정 질문에 대한 더 작은 서브그래프를 가져옵니다.
|
||||
3. 전체 원시 코퍼스 대신 그 집중된 결과를 어시스턴트에게 제공합니다.
|
||||
|
||||
예를 들어, 프로젝트에서 graphify를 실행한 후:
|
||||
|
||||
```bash
|
||||
graphify query "show the auth flow" --graph graphify-out/graph.json
|
||||
graphify query "what connects DigestAuth to Response?" --graph graphify-out/graph.json
|
||||
```
|
||||
|
||||
출력에는 노드 레이블, 엣지 유형, 신뢰도 태그, 소스 파일, 소스 위치가 포함됩니다. 이는 LLM을 위한 좋은 중간 컨텍스트 블록이 됩니다:
|
||||
|
||||
```text
|
||||
이 그래프 쿼리 결과를 사용하여 질문에 답하세요. 추측보다 그래프 구조를 우선하고,
|
||||
가능한 경우 소스 파일을 인용하세요.
|
||||
```
|
||||
|
||||
어시스턴트가 도구 호출이나 MCP를 지원하는 경우, 텍스트를 붙여넣는 대신 그래프를 직접 사용하세요. graphify는 `graph.json`을 MCP 서버로 노출할 수 있습니다:
|
||||
|
||||
```bash
|
||||
python -m graphify.serve graphify-out/graph.json
|
||||
```
|
||||
|
||||
이를 통해 어시스턴트가 `query_graph`, `get_node`, `get_neighbors`, `shortest_path` 같은 반복 쿼리에 구조화된 그래프 접근을 할 수 있습니다.
|
||||
|
||||
<details>
|
||||
<summary>수동 설치 (curl)</summary>
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/graphify
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
|
||||
> ~/.claude/skills/graphify/SKILL.md
|
||||
```
|
||||
|
||||
`~/.claude/CLAUDE.md`에 추가:
|
||||
|
||||
```
|
||||
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## 사용법
|
||||
|
||||
```
|
||||
/graphify # 현재 디렉토리에서 실행
|
||||
/graphify ./raw # 특정 폴더에서 실행
|
||||
/graphify ./raw --mode deep # 더 적극적인 INFERRED 엣지 추출
|
||||
/graphify ./raw --update # 변경된 파일만 재추출하여 기존 그래프에 병합
|
||||
/graphify ./raw --cluster-only # 기존 그래프의 클러스터링만 재실행, 재추출 없음
|
||||
/graphify ./raw --no-viz # HTML 건너뛰기, 보고서 + JSON만 생성
|
||||
/graphify ./raw --obsidian # Obsidian 볼트도 생성 (옵트인)
|
||||
/graphify ./raw --obsidian --obsidian-dir ~/vaults/myproject # 볼트를 특정 디렉토리에 생성
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # 논문 가져오기, 저장, 그래프 업데이트
|
||||
/graphify add https://x.com/karpathy/status/... # 트윗 가져오기
|
||||
/graphify add https://... --author "Name" # 원저자 태그
|
||||
/graphify add https://... --contributor "Name" # 코퍼스에 추가한 사람 태그
|
||||
|
||||
/graphify query "어텐션과 옵티마이저를 연결하는 것은?"
|
||||
/graphify query "어텐션과 옵티마이저를 연결하는 것은?" --dfs # 특정 경로 추적
|
||||
/graphify query "어텐션과 옵티마이저를 연결하는 것은?" --budget 1500 # N 토큰으로 제한
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
/graphify ./raw --watch # 파일 변경 시 그래프 자동 동기화 (코드: 즉시, 문서: 알림)
|
||||
/graphify ./raw --wiki # 에이전트가 크롤 가능한 위키 빌드 (index.md + 커뮤니티별 문서)
|
||||
/graphify ./raw --svg # graph.svg 내보내기
|
||||
/graphify ./raw --graphml # graph.graphml 내보내기 (Gephi, yEd)
|
||||
/graphify ./raw --neo4j # Neo4j용 cypher.txt 생성
|
||||
/graphify ./raw --neo4j-push bolt://localhost:7687 # 실행 중인 Neo4j 인스턴스에 직접 푸시
|
||||
/graphify ./raw --mcp # MCP stdio 서버 시작
|
||||
|
||||
# git 훅 - 플랫폼 무관, 커밋 및 브랜치 전환 시 그래프 재빌드
|
||||
graphify hook install
|
||||
graphify hook uninstall
|
||||
graphify hook status
|
||||
|
||||
# 상시 작동 어시스턴트 지시 - 플랫폼별
|
||||
graphify claude install # CLAUDE.md + PreToolUse 훅 (Claude Code)
|
||||
graphify claude uninstall
|
||||
graphify codex install # AGENTS.md (Codex)
|
||||
graphify opencode install # AGENTS.md (OpenCode)
|
||||
graphify claw install # AGENTS.md (OpenClaw)
|
||||
graphify droid install # AGENTS.md (Factory Droid)
|
||||
graphify trae install # AGENTS.md (Trae)
|
||||
graphify trae uninstall
|
||||
graphify trae-cn install # AGENTS.md (Trae CN)
|
||||
graphify trae-cn uninstall
|
||||
|
||||
# 터미널에서 직접 그래프 쿼리 (AI 어시스턴트 불필요)
|
||||
graphify query "어텐션과 옵티마이저를 연결하는 것은?"
|
||||
graphify query "인증 흐름 보기" --dfs
|
||||
graphify query "CfgNode이 뭐지?" --budget 500
|
||||
graphify query "..." --graph path/to/graph.json
|
||||
```
|
||||
|
||||
다양한 파일 유형의 조합과 함께 동작합니다:
|
||||
|
||||
| 유형 | 확장자 | 추출 방식 |
|
||||
|------|--------|-----------|
|
||||
| 코드 | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl` | tree-sitter AST + 콜 그래프 + docstring/주석 근거 |
|
||||
| 문서 | `.md .txt .rst` | Claude를 통한 개념 + 관계 + 설계 근거 |
|
||||
| 오피스 | `.docx .xlsx` | 마크다운으로 변환 후 Claude를 통해 추출 (`pip install graphifyy[office]` 필요) |
|
||||
| 논문 | `.pdf` | 인용 마이닝 + 개념 추출 |
|
||||
| 이미지 | `.png .jpg .webp .gif` | Claude Vision - 스크린샷, 다이어그램, 모든 언어 |
|
||||
|
||||
## 결과물
|
||||
|
||||
**갓 노드** - 최고 차수의 개념 (모든 것이 연결되는 허브)
|
||||
|
||||
**의외의 연결** - 복합 점수로 순위 지정. 코드-논문 엣지는 코드-코드보다 높게 순위됩니다. 각 결과에는 쉬운 설명이 포함됩니다.
|
||||
|
||||
**추천 질문** - 그래프가 고유하게 답할 수 있는 4~5개의 질문
|
||||
|
||||
**"이유"** - docstring, 인라인 주석(`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), 문서의 설계 근거가 `rationale_for` 노드로 추출됩니다. 코드가 무엇을 하는지뿐만 아니라 — 왜 그렇게 작성되었는지.
|
||||
|
||||
**신뢰도 점수** - 모든 INFERRED 엣지에는 `confidence_score`(0.0~1.0)가 있습니다. 무엇이 추측되었는지뿐 아니라 모델이 얼마나 확신했는지도 알 수 있습니다. EXTRACTED 엣지는 항상 1.0입니다.
|
||||
|
||||
**의미적 유사성 엣지** - 구조적 연결 없는 파일 간 개념 링크. 서로를 호출하지 않으면서 같은 문제를 해결하는 두 함수, 코드의 클래스와 같은 알고리즘을 설명하는 논문의 개념 등.
|
||||
|
||||
**하이퍼엣지** - 쌍별 엣지로는 표현할 수 없는 3개 이상 노드의 그룹 관계. 공유 프로토콜을 구현하는 모든 클래스, 인증 흐름의 모든 함수, 논문 섹션에서 하나의 아이디어를 구성하는 모든 개념 등.
|
||||
|
||||
**토큰 벤치마크** - 매 실행 후 자동으로 출력됩니다. 혼합 코퍼스(Karpathy 리포지토리 + 논문 + 이미지)에서: 원본 파일 대비 쿼리당 **71.5배** 적은 토큰. 첫 실행은 추출과 그래프 빌드를 수행합니다(토큰이 소비됩니다). 이후 모든 쿼리는 원본 파일 대신 압축된 그래프를 읽습니다 — 여기서 절약이 복리로 누적됩니다. SHA256 캐시로 재실행 시 변경된 파일만 재처리합니다.
|
||||
|
||||
**자동 동기화** (`--watch`) - 백그라운드 터미널에서 실행하면 코드베이스가 변경될 때 그래프가 자동으로 업데이트됩니다. 코드 파일 저장 시 즉시 재빌드가 트리거됩니다(AST만, LLM 없음). 문서/이미지 변경 시에는 LLM 재처리를 위해 `--update` 실행을 알려줍니다.
|
||||
|
||||
**Git 훅** (`graphify hook install`) - post-commit 및 post-checkout 훅을 설치합니다. 모든 커밋과 브랜치 전환 후 그래프가 자동으로 재빌드됩니다. 재빌드가 실패하면 훅이 0이 아닌 코드로 종료하여 git이 에러를 표시하고 조용히 계속 진행하지 않습니다. 백그라운드 프로세스가 필요 없습니다.
|
||||
|
||||
**위키** (`--wiki`) - 커뮤니티 및 갓 노드별 위키피디아 스타일 마크다운 문서와 `index.md` 진입점. 어떤 에이전트든 `index.md`를 가리키면 JSON을 파싱하는 대신 파일을 읽어서 지식 베이스를 탐색할 수 있습니다.
|
||||
|
||||
## 실전 예제
|
||||
|
||||
| 코퍼스 | 파일 수 | 축소율 | 결과 |
|
||||
|--------|---------|--------|------|
|
||||
| Karpathy 리포지토리 + 논문 5편 + 이미지 4장 | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
|
||||
| graphify 소스 + Transformer 논문 | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
|
||||
| httpx (합성 Python 라이브러리) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
|
||||
|
||||
토큰 축소는 코퍼스 크기에 비례하여 확장됩니다. 6개 파일은 어차피 컨텍스트 윈도우에 들어가므로, 그래프의 가치는 압축이 아닌 구조적 명확성에 있습니다. 52개 파일(코드 + 논문 + 이미지)에서는 71배 이상을 달성합니다. 각 `worked/` 폴더에는 원본 입력 파일과 실제 출력(`GRAPH_REPORT.md`, `graph.json`)이 있어 직접 실행하여 수치를 검증할 수 있습니다.
|
||||
|
||||
## 개인정보 보호
|
||||
|
||||
graphify는 문서, 논문, 이미지의 의미적 추출을 위해 파일 내용을 AI 코딩 어시스턴트의 기반 모델 API로 전송합니다 — Anthropic(Claude Code), OpenAI(Codex), 또는 사용 중인 플랫폼의 제공자. 코드 파일은 tree-sitter AST를 통해 로컬에서 처리됩니다 — 코드의 경우 파일 내용이 사용자의 머신을 벗어나지 않습니다. 어떠한 텔레메트리, 사용 추적, 분석도 없습니다. 유일한 네트워크 호출은 추출 중 플랫폼 모델 API에 대한 것이며, 사용자 본인의 API 키를 사용합니다.
|
||||
|
||||
## 기술 스택
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. 의미적 추출은 Claude(Claude Code), GPT-4(Codex), 또는 플랫폼이 실행하는 모델을 통해 수행됩니다. Neo4j 불필요, 서버 불필요, 완전히 로컬에서 실행됩니다.
|
||||
|
||||
## 다음 계획
|
||||
|
||||
graphify는 그래프 레이어입니다. 그 위에 [Penpax](https://safishamsi.github.io/penpax.ai)를 개발하고 있습니다 — 회의, 브라우저 기록, 파일, 이메일, 코드를 하나의 지속적으로 업데이트되는 지식 그래프로 연결하는 온디바이스 디지털 트윈입니다. 클라우드 없음, 데이터 학습 없음. [대기 목록에 등록하세요.](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## 스타 히스토리
|
||||
|
||||
[](https://starchart.cc/safishamsi/graphify)
|
||||
|
||||
<details>
|
||||
<summary>기여하기</summary>
|
||||
|
||||
**실전 예제**는 가장 신뢰를 쌓는 기여 방식입니다. 실제 코퍼스에서 `/graphify`를 실행하고, 결과를 `worked/{slug}/`에 저장하고, 그래프가 맞게 파악한 것과 틀린 것을 평가하는 솔직한 `review.md`를 작성하여 PR을 제출하세요.
|
||||
|
||||
**추출 버그** - 입력 파일, 캐시 엔트리(`graphify-out/cache/`), 그리고 누락되거나 날조된 내용과 함께 이슈를 열어주세요.
|
||||
|
||||
모듈 책임과 언어 추가 방법은 [ARCHITECTURE.md](ARCHITECTURE.md)를 참조하세요.
|
||||
|
||||
</details>
|
||||
@@ -1,15 +1,11 @@
|
||||
# graphify
|
||||
|
||||
[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)
|
||||
|
||||
**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.
|
||||
**A Claude Code skill.** Type `/graphify` in Claude Code - it reads your files, builds a knowledge graph, and gives you back structure you didn't know was there. Understand a codebase faster. Find the "why" behind architectural decisions.
|
||||
|
||||
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, even images in other languages - graphify uses Claude vision to extract concepts and relationships from all of it and connects them into one graph.
|
||||
|
||||
> 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.
|
||||
|
||||
@@ -25,147 +21,52 @@ graphify-out/
|
||||
└── cache/ SHA256 cache - re-runs only process changed files
|
||||
```
|
||||
|
||||
Add a `.graphifyignore` file to exclude folders you don't want in the graph:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
Same syntax as `.gitignore`. Patterns match against file paths relative to the folder you run graphify on.
|
||||
|
||||
## How it works
|
||||
|
||||
graphify runs in three passes. First, a deterministic AST pass extracts structure from code files (classes, functions, imports, call graphs, docstrings, rationale comments) with no LLM needed. Second, video and audio files are transcribed locally with faster-whisper using a domain-aware prompt derived from corpus god nodes — transcripts are cached so re-runs are instant. Third, Claude subagents run in parallel over docs, papers, images, and transcripts to extract concepts, relationships, and design rationale. The results are merged into a NetworkX graph, clustered with Leiden community detection, and exported as interactive HTML, queryable JSON, and a plain-language audit report.
|
||||
|
||||
**Clustering is graph-topology-based — no embeddings.** Leiden finds communities by edge density. The semantic similarity edges that Claude extracts (`semantically_similar_to`, marked INFERRED) are already in the graph, so they influence community detection directly. The graph structure is the similarity signal — no separate embedding step or vector database needed.
|
||||
graphify runs in two passes. First, a deterministic AST pass extracts structure from code files (classes, functions, imports, call graphs, docstrings, rationale comments) with no LLM needed. Second, Claude subagents run in parallel over docs, papers, and images to extract concepts, relationships, and design rationale. The results are merged into a NetworkX graph, clustered with Leiden community detection, and exported as interactive HTML, queryable JSON, and a plain-language audit report.
|
||||
|
||||
Every relationship is tagged `EXTRACTED` (found directly in source), `INFERRED` (reasonable inference, with a confidence score), or `AMBIGUOUS` (flagged for review). You always know what was found vs guessed.
|
||||
|
||||
## Install
|
||||
|
||||
**Requires:** 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:** [Claude Code](https://claude.ai/code) and Python 3.10+
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Official package:** The PyPI package is named `graphifyy` (install with `pip install graphifyy`). Other packages named `graphify*` on PyPI are not affiliated with this project. The only official repository is [safishamsi/graphify](https://github.com/safishamsi/graphify). The CLI and skill command are still `graphify`.
|
||||
> The PyPI package is temporarily named `graphifyy` while the `graphify` name is being reclaimed. The CLI and skill command are still `graphify`.
|
||||
|
||||
### Platform support
|
||||
|
||||
| Platform | Install command |
|
||||
|----------|----------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (auto-detected) or `graphify install --platform windows` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| GitHub Copilot CLI | `graphify install --platform copilot` |
|
||||
| Aider | `graphify install --platform aider` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| Cursor | `graphify cursor 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.
|
||||
|
||||
Then open your AI coding assistant and type:
|
||||
Then open Claude Code in any directory and type:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
Note: Codex uses `$` instead of `/` for skill calling, so type `$graphify .` instead.
|
||||
|
||||
### Make your assistant always use the graph (recommended)
|
||||
### Make Claude always use the graph (recommended)
|
||||
|
||||
After building a graph, run this once in your project:
|
||||
|
||||
| Platform | Command |
|
||||
|----------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| GitHub Copilot CLI | `graphify copilot install` |
|
||||
| Aider | `graphify aider install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
| Factory Droid | `graphify droid install` |
|
||||
| Trae | `graphify trae install` |
|
||||
| Trae CN | `graphify trae-cn install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
|
||||
**Claude Code** does two things: writes a `CLAUDE.md` section telling Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs a **PreToolUse hook** (`settings.json`) that fires before every Glob and Grep call. If a knowledge graph exists, Claude sees: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ — so Claude navigates via the graph instead of grepping through every file.
|
||||
|
||||
**Codex** writes to `AGENTS.md` and also installs a **PreToolUse hook** in `.codex/hooks.json` that fires before every Bash tool call — same always-on mechanism as Claude Code.
|
||||
|
||||
**OpenCode** writes to `AGENTS.md` and also installs a **`tool.execute.before` plugin** (`.opencode/plugins/graphify.js` + `opencode.json` registration) that fires before bash tool calls and injects the graph reminder into tool output when the graph exists.
|
||||
|
||||
**Cursor** writes `.cursor/rules/graphify.mdc` with `alwaysApply: true` — Cursor includes it in every conversation automatically, no hook needed.
|
||||
|
||||
**Gemini CLI** copies the skill to `~/.gemini/skills/graphify/SKILL.md`, writes a `GEMINI.md` section, and installs a `BeforeTool` hook in `.gemini/settings.json` that fires before file-read tool calls — same always-on mechanism as Claude Code.
|
||||
|
||||
**Aider and OpenClaw, Factory Droid, Trae** write the same rules to `AGENTS.md` in your project root. These platforms don't support tool hooks, so AGENTS.md is the always-on mechanism.
|
||||
|
||||
**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`).
|
||||
|
||||
**Always-on vs explicit trigger — what's the difference?**
|
||||
|
||||
The always-on hook surfaces `GRAPH_REPORT.md` — a one-page summary of god nodes, communities, and surprising connections. Your assistant reads this before searching files, so it navigates by structure instead of keyword matching. That covers most everyday questions.
|
||||
|
||||
`/graphify query`, `/graphify path`, and `/graphify explain` go deeper: they traverse the raw `graph.json` hop by hop, trace exact paths between nodes, and surface edge-level detail (relation type, confidence score, source location). Use them when you want a specific question answered from the graph rather than a general orientation.
|
||||
|
||||
Think of it this way: the always-on hook gives your assistant a map. The `/graphify` commands let it navigate the map precisely.
|
||||
|
||||
## Using `graph.json` with an LLM
|
||||
|
||||
`graph.json` is not meant to be pasted into a prompt all at once. The useful
|
||||
workflow is:
|
||||
|
||||
1. Start with `graphify-out/GRAPH_REPORT.md` for the high-level overview.
|
||||
2. Use `graphify query` to pull a smaller subgraph for the specific question
|
||||
you want to answer.
|
||||
3. Give that focused output to your assistant instead of dumping the full raw
|
||||
corpus.
|
||||
|
||||
For example, after running graphify on a project:
|
||||
|
||||
```bash
|
||||
graphify query "show the auth flow" --graph graphify-out/graph.json
|
||||
graphify query "what connects DigestAuth to Response?" --graph graphify-out/graph.json
|
||||
graphify claude install
|
||||
```
|
||||
|
||||
The output includes node labels, edge types, confidence tags, source files, and
|
||||
source locations. That makes it a good intermediate context block for an LLM:
|
||||
This does two things:
|
||||
|
||||
```text
|
||||
Use this graph query output to answer the question. Prefer the graph structure
|
||||
over guessing, and cite the source files when possible.
|
||||
```
|
||||
1. **CLAUDE.md rules** - tells Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and to rebuild the graph after editing code files.
|
||||
|
||||
If your assistant supports tool calling or MCP, use the graph directly instead
|
||||
of pasting text. graphify can expose `graph.json` as an MCP server:
|
||||
2. **PreToolUse hook** (`settings.json`) - fires automatically before every Glob and Grep call. If a knowledge graph exists, Claude sees: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ This means Claude navigates via the graph instead of grepping through every file - faster answers, fewer wasted tool calls, and responses grounded in the actual structure of your codebase rather than keyword matches.
|
||||
|
||||
```bash
|
||||
python -m graphify.serve graphify-out/graph.json
|
||||
```
|
||||
Without this, Claude will grep raw files by default even when a graph exists. With it, the graph becomes the first thing Claude reaches for.
|
||||
|
||||
That gives the assistant structured graph access for repeated queries such as
|
||||
`query_graph`, `get_node`, `get_neighbors`, and `shortest_path`.
|
||||
Uninstall with `graphify claude uninstall`.
|
||||
|
||||
<details>
|
||||
<summary>Manual install (curl)</summary>
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/graphify
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v2/graphify/skill.md \
|
||||
> ~/.claude/skills/graphify/SKILL.md
|
||||
```
|
||||
|
||||
@@ -185,21 +86,12 @@ When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"`
|
||||
/graphify ./raw # run on a specific folder
|
||||
/graphify ./raw --mode deep # more aggressive INFERRED edge extraction
|
||||
/graphify ./raw --update # re-extract only changed files, merge into existing graph
|
||||
/graphify ./raw --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify ./raw --cluster-only # rerun clustering on existing graph, no re-extraction
|
||||
/graphify ./raw --no-viz # skip HTML, just produce report + JSON
|
||||
/graphify ./raw --obsidian # also generate Obsidian vault (opt-in)
|
||||
/graphify ./raw --obsidian --obsidian-dir ~/vaults/myproject # write vault to a specific directory
|
||||
/graphify ./raw --obsidian # also generate Obsidian vault (opt-in)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper, save, update graph
|
||||
/graphify add https://x.com/karpathy/status/... # fetch a tweet
|
||||
/graphify add https://www.youtube.com/watch?v=... # 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
|
||||
|
||||
/graphify query "what connects attention to the optimizer?"
|
||||
/graphify query "what connects attention to the optimizer?" --dfs # trace a specific path
|
||||
/graphify query "what connects attention to the optimizer?" --budget 1500 # cap at N tokens
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
@@ -208,52 +100,20 @@ When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"`
|
||||
/graphify ./raw --svg # export graph.svg
|
||||
/graphify ./raw --graphml # export graph.graphml (Gephi, yEd)
|
||||
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
|
||||
/graphify ./raw --neo4j-push bolt://localhost:7687 # push directly to a running Neo4j instance
|
||||
/graphify ./raw --mcp # start MCP stdio server
|
||||
|
||||
# git hooks - platform-agnostic, rebuild graph on commit and branch switch
|
||||
graphify hook install
|
||||
graphify hook uninstall
|
||||
graphify hook status
|
||||
|
||||
# always-on assistant instructions - platform-specific
|
||||
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
|
||||
graphify claude uninstall
|
||||
graphify codex install # AGENTS.md (Codex)
|
||||
graphify opencode install # AGENTS.md + tool.execute.before plugin (OpenCode)
|
||||
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
|
||||
graphify cursor uninstall
|
||||
graphify gemini install # GEMINI.md + BeforeTool hook (Gemini CLI)
|
||||
graphify gemini uninstall
|
||||
graphify copilot install # skill file (GitHub Copilot CLI)
|
||||
graphify copilot uninstall
|
||||
graphify aider install # AGENTS.md (Aider)
|
||||
graphify aider uninstall
|
||||
graphify claw install # AGENTS.md (OpenClaw)
|
||||
graphify droid install # AGENTS.md (Factory Droid)
|
||||
graphify trae install # AGENTS.md (Trae)
|
||||
graphify trae uninstall
|
||||
graphify trae-cn install # AGENTS.md (Trae CN)
|
||||
graphify trae-cn uninstall
|
||||
|
||||
# query the graph directly from the terminal (no AI assistant needed)
|
||||
graphify query "what connects attention to the optimizer?"
|
||||
graphify query "show the auth flow" --dfs
|
||||
graphify query "what is CfgNode?" --budget 500
|
||||
graphify query "..." --graph path/to/graph.json
|
||||
graphify hook install # git hooks - rebuilds graph on commit and branch switch
|
||||
graphify claude install # always-on: CLAUDE.md + PreToolUse hook for this project
|
||||
```
|
||||
|
||||
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 .go .rs .java .c .cpp .rb .cs .kt .scala .php` | AST via tree-sitter + call-graph + docstring/comment rationale |
|
||||
| Docs | `.md .txt .rst` | Concepts + relationships + design rationale via Claude |
|
||||
| Office | `.docx .xlsx` | Converted to markdown then extracted via Claude (requires `pip install graphifyy[office]`) |
|
||||
| Papers | `.pdf` | Citation mining + concept extraction |
|
||||
| Images | `.png .jpg .webp .gif` | Claude vision - screenshots, diagrams, any language |
|
||||
| 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]`) |
|
||||
|
||||
## What you get
|
||||
|
||||
@@ -271,11 +131,11 @@ Works with any mix of file types:
|
||||
|
||||
**Hyperedges** - group relationships connecting 3+ nodes that pairwise edges can't express. All classes implementing a shared protocol, all functions in an auth flow, all concepts from a paper section forming one idea.
|
||||
|
||||
**Token benchmark** - printed automatically after every run. On a mixed corpus (Karpathy repos + papers + images): **71.5x** fewer tokens per query vs reading raw files. The first run extracts and builds the graph (this costs tokens). Every subsequent query reads the compact graph instead of raw files — that's where the savings compound. The SHA256 cache means re-runs only re-process changed files.
|
||||
**Token benchmark** - printed automatically after every run. On a mixed corpus (Karpathy repos + papers + images): **71.5x** fewer tokens per query vs reading raw files.
|
||||
|
||||
**Auto-sync** (`--watch`) - run in a background terminal and the graph updates itself as your codebase changes. Code file saves trigger an instant rebuild (AST only, no LLM). Doc/image changes notify you to run `--update` for the LLM re-pass.
|
||||
|
||||
**Git hooks** (`graphify hook install`) - installs post-commit and post-checkout hooks. Graph rebuilds automatically after every commit and every branch switch. If a rebuild fails, the hook exits with a non-zero code so git surfaces the error instead of silently continuing. No background process needed.
|
||||
**Git hooks** (`graphify hook install`) - installs post-commit and post-checkout hooks. Graph rebuilds automatically after every commit and every branch switch. No background process needed.
|
||||
|
||||
**Wiki** (`--wiki`) - Wikipedia-style markdown articles per community and god node, with an `index.md` entry point. Point any agent at `index.md` and it can navigate the knowledge base by reading files instead of parsing JSON.
|
||||
|
||||
@@ -291,19 +151,11 @@ Token reduction scales with corpus size. 6 files fits in a context window anyway
|
||||
|
||||
## Privacy
|
||||
|
||||
graphify sends file contents to your AI coding assistant's underlying model API for semantic extraction of docs, papers, and images — Anthropic (Claude Code), OpenAI (Codex), or whichever provider your platform uses. Code files are processed locally via tree-sitter AST — no file contents leave your machine for code. Video and audio files are transcribed locally with faster-whisper — audio never leaves your machine. No telemetry, usage tracking, or analytics of any kind. The only network calls are to your platform's model API during extraction, using your own API key.
|
||||
graphify sends file contents to the Claude API (Anthropic) for semantic extraction of docs, papers, and images. Code files are processed locally via tree-sitter AST — no file contents leave your machine for code. No telemetry, usage tracking, or analytics of any kind. The only network calls are to Anthropic's API during extraction, using your own API key via Claude Code.
|
||||
|
||||
## Tech stack
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + 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.
|
||||
|
||||
## 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)
|
||||
|
||||
## Star history
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + Claude + vis.js. No Neo4j required, no server, runs entirely locally.
|
||||
|
||||
<details>
|
||||
<summary>Contributing</summary>
|
||||
|
||||
-222
@@ -1,222 +0,0 @@
|
||||
# graphify
|
||||
|
||||
[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://pypi.org/project/graphifyy/)
|
||||
|
||||
**一个面向 AI 编码助手的技能。** 在 Claude Code、Codex、OpenCode、OpenClaw、Factory Droid 或 Trae 中输入 `/graphify`,它会读取你的文件、构建知识图谱,并把原本不明显的结构关系还给你。更快理解代码库,找到架构决策背后的"为什么"。
|
||||
|
||||
完全多模态。你可以直接丢进去代码、PDF、Markdown、截图、流程图、白板照片,甚至其他语言的图片 —— graphify 会用 Claude vision 从这些内容中提取概念和关系,并把它们连接到同一张图里。
|
||||
|
||||
> Andrej Karpathy 会维护一个 `/raw` 文件夹,把论文、推文、截图和笔记都丢进去。graphify 就是在解决这类问题 —— 相比直接读取原始文件,每次查询的 token 消耗可降低 **71.5 倍**,结果还能跨会话持久保存,并且会明确区分哪些内容是实际发现的,哪些只是合理推断。
|
||||
|
||||
```
|
||||
/graphify . # 可用于任意目录:代码库、笔记、论文都可以
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html 可交互图谱:可点节点、搜索、按社区过滤
|
||||
├── GRAPH_REPORT.md God nodes、意外连接、建议提问
|
||||
├── graph.json 持久化图谱:数周后仍可查询,无需重新读原始文件
|
||||
└── cache/ SHA256 缓存:重复运行时只处理变更过的文件
|
||||
```
|
||||
|
||||
## 工作原理
|
||||
|
||||
graphify 分两轮执行。第一轮是确定性的 AST 提取,对代码文件做结构分析(类、函数、导入、调用图、docstring、解释性注释),这一轮不需要 LLM。第二轮会并行调用 Claude 子代理处理文档、论文和图片,从中提取概念、关系和设计动机。最后把两边结果合并到一个 NetworkX 图里,用 Leiden 社区发现算法做聚类,并导出成可交互 HTML、可查询 JSON,以及一份人类可读的审计报告。
|
||||
|
||||
**聚类是基于图拓扑完成的,不依赖 embeddings。** Leiden 按边密度发现社区。Claude 抽取出的语义相似边(`semantically_similar_to`,标记为 `INFERRED`)本来就存在于图中,所以会直接影响社区划分。图结构本身就是相似性信号,不需要额外的 embedding 步骤,也不需要向量数据库。
|
||||
|
||||
每条关系都会被标记为 `EXTRACTED`(直接在源材料中找到)、`INFERRED`(合理推断,并附带置信度分数)或 `AMBIGUOUS`(有歧义,需要复核)。所以你始终知道哪些是实际发现的,哪些是模型猜出来的。
|
||||
|
||||
## 安装
|
||||
|
||||
**要求:** Python 3.10+,并且使用以下平台之一:[Claude Code](https://claude.ai/code)、[Codex](https://openai.com/codex)、[OpenCode](https://opencode.ai)、[OpenClaw](https://openclaw.ai)、[Factory Droid](https://factory.ai) 或 [Trae](https://trae.ai)
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> PyPI 包当前暂时叫 `graphifyy`,因为 `graphify` 这个名字还在回收中。CLI 命令和 skill 命令仍然都是 `graphify`。
|
||||
|
||||
### 平台支持
|
||||
|
||||
| 平台 | 安装命令 |
|
||||
|------|----------|
|
||||
| Claude Code | `graphify install` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
|
||||
Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `multi_agent = true`,这样才能并行提取。OpenClaw 目前的并行 agent 支持还比较早期,所以使用顺序提取。Trae 使用 Agent 工具进行并行子代理调度,**不支持** PreToolUse hook,因此 AGENTS.md 是其常驻机制。
|
||||
|
||||
然后打开你的 AI 编码助手,输入:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
### 让助手始终优先使用图谱(推荐)
|
||||
|
||||
图构建完成后,在项目里运行一次:
|
||||
|
||||
| 平台 | 命令 |
|
||||
|------|------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
| Factory Droid | `graphify droid install` |
|
||||
| Trae | `graphify trae install` |
|
||||
| Trae CN | `graphify trae-cn install` |
|
||||
|
||||
**Claude Code** 会做两件事:
|
||||
1. 在 `CLAUDE.md` 中写入一段规则,告诉 Claude 在回答架构问题前先读 `graphify-out/GRAPH_REPORT.md`
|
||||
2. 安装一个 **PreToolUse hook**(写入 `settings.json`),在每次 `Glob` 和 `Grep` 前触发
|
||||
|
||||
如果知识图谱存在,Claude 会先看到:_"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ —— 这样 Claude 会优先按图谱导航,而不是一上来就 grep 整个项目。
|
||||
|
||||
**Codex、OpenCode、OpenClaw、Factory Droid、Trae** 会把同样的规则写进项目根目录的 `AGENTS.md`。这些平台没有 PreToolUse hook,所以 `AGENTS.md` 是它们的常驻机制。
|
||||
|
||||
卸载时使用对应平台的 uninstall 命令即可(例如 `graphify claude uninstall`)。
|
||||
|
||||
**常驻模式和显式触发有什么区别?**
|
||||
|
||||
常驻 hook 会优先暴露 `GRAPH_REPORT.md` —— 这是一页式总结,包含 god nodes、社区结构和意外连接。你的助手在搜索文件前会先读它,因此会按结构导航,而不是按关键字乱搜。这已经能覆盖大部分日常问题。
|
||||
|
||||
`/graphify query`、`/graphify path` 和 `/graphify explain` 会更深入:它们会逐跳遍历底层 `graph.json`,追踪节点之间的精确路径,并展示边级别细节(关系类型、置信度、源位置)。当你想从图谱里精确回答某个问题,而不仅仅是获得整体感知时,就该用这些命令。
|
||||
|
||||
可以这样理解:常驻 hook 是先给助手一张地图,`/graphify` 这几个命令则是让它沿着地图精确导航。
|
||||
|
||||
<details>
|
||||
<summary>手动安装(curl)</summary>
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/graphify
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
|
||||
> ~/.claude/skills/graphify/SKILL.md
|
||||
```
|
||||
|
||||
把下面内容加到 `~/.claude/CLAUDE.md`:
|
||||
|
||||
```
|
||||
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## 用法
|
||||
|
||||
```
|
||||
/graphify # 对当前目录运行
|
||||
/graphify ./raw # 对指定目录运行
|
||||
/graphify ./raw --mode deep # 更激进地抽取 INFERRED 边
|
||||
/graphify ./raw --update # 只重新提取变更文件,并合并到已有图谱
|
||||
/graphify ./raw --cluster-only # 只重新聚类已有图谱,不重新提取
|
||||
/graphify ./raw --no-viz # 跳过 HTML,只生成 report + JSON
|
||||
/graphify ./raw --obsidian # 额外生成 Obsidian vault(可选)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # 拉取论文、保存并更新图谱
|
||||
/graphify add https://x.com/karpathy/status/... # 拉取推文
|
||||
/graphify add https://... --author "Name" # 标记原作者
|
||||
/graphify add https://... --contributor "Name" # 标记是谁把它加入语料库的
|
||||
|
||||
/graphify query "what connects attention to the optimizer?"
|
||||
/graphify query "what connects attention to the optimizer?" --dfs # 追踪一条具体路径
|
||||
/graphify query "what connects attention to the optimizer?" --budget 1500 # 把预算限制在 N tokens
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
/graphify ./raw --watch # 文件变更时自动同步图谱(代码:立即更新;文档:提醒你)
|
||||
/graphify ./raw --wiki # 构建可供 agent 抓取的 wiki(index.md + 每个 community 一篇文章)
|
||||
/graphify ./raw --svg # 导出 graph.svg
|
||||
/graphify ./raw --graphml # 导出 graph.graphml(Gephi、yEd)
|
||||
/graphify ./raw --neo4j # 生成给 Neo4j 用的 cypher.txt
|
||||
/graphify ./raw --neo4j-push bolt://localhost:7687 # 直接推送到运行中的 Neo4j
|
||||
/graphify ./raw --mcp # 启动 MCP stdio server
|
||||
|
||||
# git hooks - 跨平台,在 commit 和切分支后重建图谱
|
||||
graphify hook install
|
||||
graphify hook uninstall
|
||||
graphify hook status
|
||||
|
||||
# 常驻助手规则 - 按平台区分
|
||||
graphify claude install # CLAUDE.md + PreToolUse hook(Claude Code)
|
||||
graphify claude uninstall
|
||||
graphify codex install # AGENTS.md(Codex)
|
||||
graphify opencode install # AGENTS.md(OpenCode)
|
||||
graphify claw install # AGENTS.md(OpenClaw)
|
||||
graphify droid install # AGENTS.md(Factory Droid)
|
||||
graphify trae install # AGENTS.md(Trae)
|
||||
graphify trae uninstall
|
||||
graphify trae-cn install # AGENTS.md(Trae CN)
|
||||
graphify trae-cn uninstall
|
||||
```
|
||||
|
||||
支持混合文件类型:
|
||||
|
||||
| 类型 | 扩展名 | 提取方式 |
|
||||
|------|--------|----------|
|
||||
| 代码 | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php` | tree-sitter AST + 调用图 + docstring / 注释中的 rationale |
|
||||
| 文档 | `.md .txt .rst` | 通过 Claude 提取概念、关系和设计动机 |
|
||||
| 论文 | `.pdf` | 引文挖掘 + 概念提取 |
|
||||
| 图片 | `.png .jpg .webp .gif` | Claude vision —— 截图、图表、任意语言都可以 |
|
||||
|
||||
## 你会得到什么
|
||||
|
||||
**God nodes** —— 度最高的概念节点(整个系统最容易汇聚到的地方)
|
||||
|
||||
**意外连接** —— 按综合得分排序。代码-论文之间的边会比代码-代码边权重更高。每条结果都会附带一段人话解释。
|
||||
|
||||
**建议提问** —— 图谱特别擅长回答的 4 到 5 个问题。
|
||||
|
||||
**“为什么”** —— docstring、行内注释(`# NOTE:`、`# IMPORTANT:`、`# HACK:`、`# WHY:`)以及文档里的设计动机都会被抽取成 `rationale_for` 节点。不只是知道代码“做了什么”,还能知道“为什么要这么写”。
|
||||
|
||||
**置信度分数** —— 每条 `INFERRED` 边都有 `confidence_score`(0.0-1.0)。你不只知道哪些是猜出来的,还知道模型对这个猜测有多有把握。`EXTRACTED` 边恒为 1.0。
|
||||
|
||||
**语义相似边** —— 跨文件的概念连接,即使结构上没有直接依赖也能建立关联。比如两个函数做的是同一类问题但彼此没有调用,或者某个代码类和某篇论文里的算法概念本质相同。
|
||||
|
||||
**超边(Hyperedges)** —— 用来表达 3 个以上节点的群组关系,这是普通两两边表达不出来的。比如:一组类共同实现一个协议、认证链路里的一组函数、同一篇论文某一节里的多个概念共同组成一个想法。
|
||||
|
||||
**Token 基准** —— 每次运行后都会自动打印。对混合语料(Karpathy 的仓库 + 论文 + 图片),每次查询的 token 消耗可以比直接读原文件少 **71.5 倍**。第一次运行需要先提取并建图,这一步会花 token;后续查询直接读取压缩后的图谱,节省会越来越明显。SHA256 缓存保证重复运行时只重新处理变更文件。
|
||||
|
||||
**自动同步**(`--watch`)—— 在后台终端里跑着,代码库一变化,图谱就会跟着更新。代码文件保存会立刻触发重建(只走 AST,不用 LLM);文档/图片变更则会提醒你跑 `--update` 进行 LLM 再提取。
|
||||
|
||||
**Git hooks**(`graphify hook install`)—— 安装 `post-commit` 和 `post-checkout` hook。每次 commit 后、每次切分支后都会自动重建图谱,不需要额外开一个后台进程。
|
||||
|
||||
**Wiki**(`--wiki`)—— 为每个 community 和 god node 生成类似维基百科的 Markdown 文章,并提供 `index.md` 作为入口。任何 agent 只要读 `index.md`,就能通过普通文件导航整个知识库,而不必直接解析 JSON。
|
||||
|
||||
## Worked examples
|
||||
|
||||
| 语料 | 文件数 | 压缩比 | 输出 |
|
||||
|------|--------|--------|------|
|
||||
| Karpathy 的仓库 + 5 篇论文 + 4 张图片 | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
|
||||
| graphify 源码 + Transformer 论文 | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
|
||||
| httpx(合成 Python 库) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
|
||||
|
||||
Token 压缩效果会随着语料规模增大而更明显。6 个文件本来就塞得进上下文窗口,所以 graphify 在这种场景里的价值更多是结构清晰度,而不是 token 压缩。到了 52 个文件(代码 + 论文 + 图片)这种规模,就能做到 71x+。每个 `worked/` 目录里都带了原始输入和真实输出(`GRAPH_REPORT.md`、`graph.json`),你可以自己跑一遍核对数字。
|
||||
|
||||
## 隐私
|
||||
|
||||
graphify 会把文档、论文和图片的内容发送给你所用 AI 编码助手背后的模型 API 来做语义提取 —— 可能是 Anthropic(Claude Code)、OpenAI(Codex),或者你当前平台使用的其他提供方。代码文件则完全在本地通过 tree-sitter AST 处理,不会把代码内容发出去。项目本身没有任何遥测、使用跟踪或分析。唯一的网络请求就是语义提取阶段调用你平台自己的模型 API,使用的也是你自己的 API key。
|
||||
|
||||
## 技术栈
|
||||
|
||||
NetworkX + Leiden(graspologic)+ tree-sitter + vis.js。语义提取由 Claude(Claude Code)、GPT-4(Codex)或你当前平台所运行的模型完成。不需要 Neo4j,不需要 server,整体是纯本地运行。
|
||||
|
||||
<details>
|
||||
<summary>贡献</summary>
|
||||
|
||||
**Worked examples** 是最能建立信任的贡献方式。对一个真实语料跑 `/graphify`,把输出保存到 `worked/{slug}/`,再写一份诚实的 `review.md`,评价图谱哪些地方做得对、哪些地方做得不对,然后提交 PR。
|
||||
|
||||
**提取 bug** —— 提 issue 时请附上输入文件、对应的缓存项(`graphify-out/cache/`)以及它漏提取或瞎编了什么。
|
||||
|
||||
模块职责和新增语言的方法见 [ARCHITECTURE.md](ARCHITECTURE.md)。
|
||||
|
||||
</details>
|
||||
+4
-4
@@ -4,8 +4,8 @@
|
||||
|
||||
| Version | Supported |
|
||||
|---------|-----------|
|
||||
| 0.3.x | Yes |
|
||||
| < 0.3 | No |
|
||||
| 0.1.x | Yes |
|
||||
| < 0.1 | No |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
@@ -28,13 +28,13 @@ graphify is a **local development tool**. It runs as a Claude Code skill and opt
|
||||
|
||||
| Vector | Mitigation |
|
||||
|--------|-----------|
|
||||
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes, blocks private/loopback/link-local IPs, and blocks cloud metadata endpoints. Redirect targets are re-validated. All fetch paths including tweet oEmbed go through `safe_fetch()`. |
|
||||
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes. Redirect targets are re-validated by `_NoFileRedirectHandler` - a redirect to `file://` is blocked. |
|
||||
| Oversized downloads | `safe_fetch()` streams responses and aborts at 50 MB. `safe_fetch_text()` aborts at 10 MB. |
|
||||
| Non-2xx HTTP responses | `safe_fetch()` raises `HTTPError` on non-2xx status codes - error pages are not silently treated as content. |
|
||||
| Path traversal in MCP server | `security.validate_graph_path()` resolves paths and requires them to be inside `graphify-out/`. Also requires the `graphify-out/` directory to exist. |
|
||||
| XSS in graph HTML output | `security.sanitize_label()` strips control characters, caps at 256 chars, and HTML-escapes all node labels and edge titles before pyvis embeds them. |
|
||||
| Prompt injection via node labels | `sanitize_label()` also applied to MCP text output - node labels from user-controlled source files cannot break the text format returned to agents. |
|
||||
| YAML frontmatter injection | `_yaml_str()` escapes backslashes, double quotes, and newlines before embedding user-controlled strings (webpage titles, query questions) in YAML frontmatter. |
|
||||
| YAML frontmatter injection | Newlines stripped from user-provided strings before embedding in YAML frontmatter (e.g. in `save_query_result()`). |
|
||||
| Encoding crashes on source files | All tree-sitter byte slices decoded with `errors="replace"` - non-UTF-8 source files degrade gracefully instead of crashing extraction. |
|
||||
| Symlink traversal | `os.walk(..., followlinks=False)` is explicit throughout `detect.py`. |
|
||||
| Corrupted graph.json | `_load_graph()` in `serve.py` wraps `json.JSONDecodeError` and prints a clear recovery message instead of crashing. |
|
||||
|
||||
+48
-675
@@ -1,28 +1,11 @@
|
||||
"""graphify CLI - `graphify install` sets up the Claude Code skill."""
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from importlib.metadata import version as _pkg_version
|
||||
__version__ = _pkg_version("graphifyy")
|
||||
except Exception:
|
||||
__version__ = "unknown"
|
||||
|
||||
|
||||
def _check_skill_version(skill_dst: Path) -> None:
|
||||
"""Warn if the installed skill is from an older graphify version."""
|
||||
version_file = skill_dst.parent / ".graphify_version"
|
||||
if not version_file.exists():
|
||||
return
|
||||
installed = version_file.read_text(encoding="utf-8").strip()
|
||||
if installed != __version__:
|
||||
print(f" warning: skill is from graphify {installed}, package is {__version__}. Run 'graphify install' to update.")
|
||||
|
||||
_SETTINGS_HOOK = {
|
||||
"matcher": "Glob|Grep",
|
||||
"hooks": [
|
||||
@@ -30,8 +13,8 @@ _SETTINGS_HOOK = {
|
||||
"type": "command",
|
||||
"command": (
|
||||
"[ -f graphify-out/graph.json ] && "
|
||||
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"
|
||||
"echo 'graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md "
|
||||
"for god nodes and community structure before searching raw files.' || true"
|
||||
),
|
||||
}
|
||||
],
|
||||
@@ -46,103 +29,39 @@ _SKILL_REGISTRATION = (
|
||||
)
|
||||
|
||||
|
||||
_PLATFORM_CONFIG: dict[str, dict] = {
|
||||
"claude": {
|
||||
"skill_file": "skill.md",
|
||||
"skill_dst": Path(".claude") / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": True,
|
||||
},
|
||||
"codex": {
|
||||
"skill_file": "skill-codex.md",
|
||||
"skill_dst": Path(".agents") / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": False,
|
||||
},
|
||||
"opencode": {
|
||||
"skill_file": "skill-opencode.md",
|
||||
"skill_dst": Path(".config") / "opencode" / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": False,
|
||||
},
|
||||
"aider": {
|
||||
"skill_file": "skill-aider.md",
|
||||
"skill_dst": Path(".aider") / "graphify" / "SKILL.md",
|
||||
"claude_md": False,
|
||||
},
|
||||
"copilot": {
|
||||
"skill_file": "skill-copilot.md",
|
||||
"skill_dst": Path(".copilot") / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": False,
|
||||
},
|
||||
"claw": {
|
||||
"skill_file": "skill-claw.md",
|
||||
"skill_dst": Path(".claw") / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": False,
|
||||
},
|
||||
"droid": {
|
||||
"skill_file": "skill-droid.md",
|
||||
"skill_dst": Path(".factory") / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": False,
|
||||
},
|
||||
"trae": {
|
||||
"skill_file": "skill-trae.md",
|
||||
"skill_dst": Path(".trae") / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": False,
|
||||
},
|
||||
"trae-cn": {
|
||||
"skill_file": "skill-trae.md",
|
||||
"skill_dst": Path(".trae-cn") / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": False,
|
||||
},
|
||||
"windows": {
|
||||
"skill_file": "skill-windows.md",
|
||||
"skill_dst": Path(".claude") / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": True,
|
||||
},
|
||||
}
|
||||
def _bundled_skill() -> Path:
|
||||
"""Path to the skill.md bundled with this package."""
|
||||
return Path(__file__).parent / "skill.md"
|
||||
|
||||
|
||||
def install(platform: str = "claude") -> None:
|
||||
if platform == "gemini":
|
||||
gemini_install()
|
||||
return
|
||||
if platform == "cursor":
|
||||
_cursor_install()
|
||||
return
|
||||
if platform not in _PLATFORM_CONFIG:
|
||||
print(
|
||||
f"error: unknown platform '{platform}'. Choose from: {', '.join(_PLATFORM_CONFIG)}, gemini, cursor",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
cfg = _PLATFORM_CONFIG[platform]
|
||||
skill_src = Path(__file__).parent / cfg["skill_file"]
|
||||
def install() -> None:
|
||||
skill_src = _bundled_skill()
|
||||
if not skill_src.exists():
|
||||
print(f"error: {cfg['skill_file']} not found in package - reinstall graphify", file=sys.stderr)
|
||||
print("error: skill.md not found in package - reinstall graphify", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
skill_dst = Path.home() / cfg["skill_dst"]
|
||||
# Copy skill to ~/.claude/skills/graphify/SKILL.md
|
||||
skill_dst = Path.home() / ".claude" / "skills" / "graphify" / "SKILL.md"
|
||||
skill_dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy(skill_src, skill_dst)
|
||||
(skill_dst.parent / ".graphify_version").write_text(__version__, encoding="utf-8")
|
||||
print(f" skill installed -> {skill_dst}")
|
||||
print(f" skill installed → {skill_dst}")
|
||||
|
||||
if cfg["claude_md"]:
|
||||
# Register in ~/.claude/CLAUDE.md (Claude Code only)
|
||||
claude_md = Path.home() / ".claude" / "CLAUDE.md"
|
||||
if claude_md.exists():
|
||||
content = claude_md.read_text(encoding="utf-8")
|
||||
if "graphify" in content:
|
||||
print(f" CLAUDE.md -> already registered (no change)")
|
||||
else:
|
||||
claude_md.write_text(content.rstrip() + _SKILL_REGISTRATION, encoding="utf-8")
|
||||
print(f" CLAUDE.md -> skill registered in {claude_md}")
|
||||
# Register in ~/.claude/CLAUDE.md
|
||||
claude_md = Path.home() / ".claude" / "CLAUDE.md"
|
||||
if claude_md.exists():
|
||||
content = claude_md.read_text()
|
||||
if "graphify" in content:
|
||||
print(f" CLAUDE.md → already registered (no change)")
|
||||
else:
|
||||
claude_md.parent.mkdir(parents=True, exist_ok=True)
|
||||
claude_md.write_text(_SKILL_REGISTRATION.lstrip(), encoding="utf-8")
|
||||
print(f" CLAUDE.md -> created at {claude_md}")
|
||||
claude_md.write_text(content.rstrip() + _SKILL_REGISTRATION)
|
||||
print(f" CLAUDE.md → skill registered in {claude_md}")
|
||||
else:
|
||||
claude_md.parent.mkdir(parents=True, exist_ok=True)
|
||||
claude_md.write_text(_SKILL_REGISTRATION.lstrip())
|
||||
print(f" CLAUDE.md → created at {claude_md}")
|
||||
|
||||
print()
|
||||
print("Done. Open your AI coding assistant and type:")
|
||||
print("Done. Open Claude Code in any directory and type:")
|
||||
print()
|
||||
print(" /graphify .")
|
||||
print()
|
||||
@@ -161,384 +80,13 @@ Rules:
|
||||
|
||||
_CLAUDE_MD_MARKER = "## graphify"
|
||||
|
||||
# AGENTS.md section for Codex, OpenCode, and OpenClaw.
|
||||
# All three platforms read AGENTS.md in the project root for persistent instructions.
|
||||
_AGENTS_MD_SECTION = """\
|
||||
## graphify
|
||||
|
||||
This project has a graphify knowledge graph at graphify-out/.
|
||||
|
||||
Rules:
|
||||
- Before answering architecture or codebase questions, read graphify-out/GRAPH_REPORT.md for god nodes and community structure
|
||||
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
|
||||
- After modifying code files in this session, run `python3 -c "from graphify.watch import _rebuild_code; from pathlib import Path; _rebuild_code(Path('.'))"` to keep the graph current
|
||||
"""
|
||||
|
||||
_AGENTS_MD_MARKER = "## graphify"
|
||||
|
||||
_GEMINI_MD_SECTION = """\
|
||||
## graphify
|
||||
|
||||
This project has a graphify knowledge graph at graphify-out/.
|
||||
|
||||
Rules:
|
||||
- Before answering architecture or codebase questions, read graphify-out/GRAPH_REPORT.md for god nodes and community structure
|
||||
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
|
||||
- After modifying code files in this session, run `python3 -c "from graphify.watch import _rebuild_code; from pathlib import Path; _rebuild_code(Path('.'))"` to keep the graph current
|
||||
"""
|
||||
|
||||
_GEMINI_MD_MARKER = "## graphify"
|
||||
|
||||
_GEMINI_HOOK = {
|
||||
"matcher": "read_file|list_directory",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": (
|
||||
"[ -f graphify-out/graph.json ] && "
|
||||
r"""echo '{"decision":"allow","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}' """
|
||||
r"""|| echo '{"decision":"allow"}'"""
|
||||
),
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def gemini_install(project_dir: Path | None = None) -> None:
|
||||
"""Copy skill file to ~/.gemini/skills/graphify/, write GEMINI.md section, and install BeforeTool hook."""
|
||||
# Copy skill file to ~/.gemini/skills/graphify/SKILL.md
|
||||
skill_src = Path(__file__).parent / "skill.md"
|
||||
skill_dst = Path.home() / ".gemini" / "skills" / "graphify" / "SKILL.md"
|
||||
skill_dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy(skill_src, skill_dst)
|
||||
(skill_dst.parent / ".graphify_version").write_text(__version__, encoding="utf-8")
|
||||
print(f" skill installed -> {skill_dst}")
|
||||
|
||||
target = (project_dir or Path(".")) / "GEMINI.md"
|
||||
|
||||
if target.exists():
|
||||
content = target.read_text(encoding="utf-8")
|
||||
if _GEMINI_MD_MARKER in content:
|
||||
print("graphify already configured in GEMINI.md")
|
||||
else:
|
||||
target.write_text(content.rstrip() + "\n\n" + _GEMINI_MD_SECTION, encoding="utf-8")
|
||||
print(f"graphify section written to {target.resolve()}")
|
||||
else:
|
||||
target.write_text(_GEMINI_MD_SECTION, encoding="utf-8")
|
||||
print(f"graphify section written to {target.resolve()}")
|
||||
|
||||
_install_gemini_hook(project_dir or Path("."))
|
||||
print()
|
||||
print("Gemini CLI will now check the knowledge graph before answering")
|
||||
print("codebase questions and rebuild it after code changes.")
|
||||
|
||||
|
||||
def _install_gemini_hook(project_dir: Path) -> None:
|
||||
settings_path = project_dir / ".gemini" / "settings.json"
|
||||
settings_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
settings = json.loads(settings_path.read_text(encoding="utf-8")) if settings_path.exists() else {}
|
||||
except json.JSONDecodeError:
|
||||
settings = {}
|
||||
before_tool = settings.setdefault("hooks", {}).setdefault("BeforeTool", [])
|
||||
settings["hooks"]["BeforeTool"] = [h for h in before_tool if "graphify" not in str(h)]
|
||||
settings["hooks"]["BeforeTool"].append(_GEMINI_HOOK)
|
||||
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
|
||||
print(" .gemini/settings.json -> BeforeTool hook registered")
|
||||
|
||||
|
||||
def _uninstall_gemini_hook(project_dir: Path) -> None:
|
||||
settings_path = project_dir / ".gemini" / "settings.json"
|
||||
if not settings_path.exists():
|
||||
return
|
||||
try:
|
||||
settings = json.loads(settings_path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
before_tool = settings.get("hooks", {}).get("BeforeTool", [])
|
||||
filtered = [h for h in before_tool if "graphify" not in str(h)]
|
||||
if len(filtered) == len(before_tool):
|
||||
return
|
||||
settings["hooks"]["BeforeTool"] = filtered
|
||||
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
|
||||
print(" .gemini/settings.json -> BeforeTool hook removed")
|
||||
|
||||
|
||||
def gemini_uninstall(project_dir: Path | None = None) -> None:
|
||||
"""Remove the graphify section from GEMINI.md, uninstall hook, and remove skill file."""
|
||||
# Remove skill file
|
||||
skill_dst = Path.home() / ".gemini" / "skills" / "graphify" / "SKILL.md"
|
||||
if skill_dst.exists():
|
||||
skill_dst.unlink()
|
||||
print(f" skill removed -> {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):
|
||||
try:
|
||||
d.rmdir()
|
||||
except OSError:
|
||||
break
|
||||
|
||||
target = (project_dir or Path(".")) / "GEMINI.md"
|
||||
if not target.exists():
|
||||
print("No GEMINI.md found in current directory - nothing to do")
|
||||
return
|
||||
content = target.read_text(encoding="utf-8")
|
||||
if _GEMINI_MD_MARKER not in content:
|
||||
print("graphify section not found in GEMINI.md - nothing to do")
|
||||
return
|
||||
cleaned = re.sub(r"\n*## graphify\n.*?(?=\n## |\Z)", "", content, flags=re.DOTALL).rstrip()
|
||||
if cleaned:
|
||||
target.write_text(cleaned + "\n", encoding="utf-8")
|
||||
print(f"graphify section removed from {target.resolve()}")
|
||||
else:
|
||||
target.unlink()
|
||||
print(f"GEMINI.md was empty after removal - deleted {target.resolve()}")
|
||||
_uninstall_gemini_hook(project_dir or Path("."))
|
||||
|
||||
|
||||
_CURSOR_RULE_PATH = Path(".cursor") / "rules" / "graphify.mdc"
|
||||
_CURSOR_RULE = """\
|
||||
---
|
||||
description: graphify knowledge graph context
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
This project has a graphify knowledge graph at graphify-out/.
|
||||
|
||||
- Before answering architecture or codebase questions, read graphify-out/GRAPH_REPORT.md for god nodes and community structure
|
||||
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
|
||||
- After modifying code files in this session, run `python3 -c "from graphify.watch import _rebuild_code; from pathlib import Path; _rebuild_code(Path('.'))"` to keep the graph current
|
||||
"""
|
||||
|
||||
|
||||
def _cursor_install(project_dir: Path) -> None:
|
||||
"""Write .cursor/rules/graphify.mdc with alwaysApply: true."""
|
||||
rule_path = (project_dir or Path(".")) / _CURSOR_RULE_PATH
|
||||
rule_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if rule_path.exists():
|
||||
print(f"graphify rule already exists at {rule_path} (no change)")
|
||||
return
|
||||
rule_path.write_text(_CURSOR_RULE, encoding="utf-8")
|
||||
print(f"graphify rule written to {rule_path.resolve()}")
|
||||
print()
|
||||
print("Cursor will now always include the knowledge graph context.")
|
||||
print("Run /graphify . first to build the graph if you haven't already.")
|
||||
|
||||
|
||||
def _cursor_uninstall(project_dir: Path) -> None:
|
||||
"""Remove .cursor/rules/graphify.mdc."""
|
||||
rule_path = (project_dir or Path(".")) / _CURSOR_RULE_PATH
|
||||
if not rule_path.exists():
|
||||
print("No graphify Cursor rule found - nothing to do")
|
||||
return
|
||||
rule_path.unlink()
|
||||
print(f"graphify Cursor rule removed from {rule_path.resolve()}")
|
||||
|
||||
|
||||
# OpenCode tool.execute.before plugin — fires before every tool call.
|
||||
# Injects a graph reminder into bash command output when graph.json exists.
|
||||
_OPENCODE_PLUGIN_JS = """\
|
||||
// graphify OpenCode plugin
|
||||
// Injects a knowledge graph reminder before bash tool calls when the graph exists.
|
||||
import { existsSync } from "fs";
|
||||
import { join } from "path";
|
||||
|
||||
export const GraphifyPlugin = async ({ directory }) => {
|
||||
let reminded = false;
|
||||
|
||||
return {
|
||||
"tool.execute.before": async (input, output) => {
|
||||
if (reminded) return;
|
||||
if (!existsSync(join(directory, "graphify-out", "graph.json"))) return;
|
||||
|
||||
if (input.tool === "bash") {
|
||||
output.args.command =
|
||||
'echo "[graphify] Knowledge graph available. Read graphify-out/GRAPH_REPORT.md for god nodes and architecture context before searching files." && ' +
|
||||
output.args.command;
|
||||
reminded = true;
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
"""
|
||||
|
||||
_OPENCODE_PLUGIN_PATH = Path(".opencode") / "plugins" / "graphify.js"
|
||||
_OPENCODE_CONFIG_PATH = Path("opencode.json")
|
||||
|
||||
|
||||
def _install_opencode_plugin(project_dir: Path) -> None:
|
||||
"""Write graphify.js plugin and register it in opencode.json."""
|
||||
plugin_file = project_dir / _OPENCODE_PLUGIN_PATH
|
||||
plugin_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
plugin_file.write_text(_OPENCODE_PLUGIN_JS, encoding="utf-8")
|
||||
print(f" {_OPENCODE_PLUGIN_PATH} -> tool.execute.before hook written")
|
||||
|
||||
config_file = project_dir / _OPENCODE_CONFIG_PATH
|
||||
if config_file.exists():
|
||||
try:
|
||||
config = json.loads(config_file.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
config = {}
|
||||
else:
|
||||
config = {}
|
||||
|
||||
plugins = config.setdefault("plugin", [])
|
||||
entry = str(_OPENCODE_PLUGIN_PATH)
|
||||
if entry not in plugins:
|
||||
plugins.append(entry)
|
||||
config_file.write_text(json.dumps(config, indent=2), encoding="utf-8")
|
||||
print(f" {_OPENCODE_CONFIG_PATH} -> plugin registered")
|
||||
else:
|
||||
print(f" {_OPENCODE_CONFIG_PATH} -> plugin already registered (no change)")
|
||||
|
||||
|
||||
def _uninstall_opencode_plugin(project_dir: Path) -> None:
|
||||
"""Remove graphify.js plugin and deregister from opencode.json."""
|
||||
plugin_file = project_dir / _OPENCODE_PLUGIN_PATH
|
||||
if plugin_file.exists():
|
||||
plugin_file.unlink()
|
||||
print(f" {_OPENCODE_PLUGIN_PATH} -> removed")
|
||||
|
||||
config_file = project_dir / _OPENCODE_CONFIG_PATH
|
||||
if not config_file.exists():
|
||||
return
|
||||
try:
|
||||
config = json.loads(config_file.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
plugins = config.get("plugin", [])
|
||||
entry = str(_OPENCODE_PLUGIN_PATH)
|
||||
if entry in plugins:
|
||||
plugins.remove(entry)
|
||||
if not plugins:
|
||||
config.pop("plugin")
|
||||
config_file.write_text(json.dumps(config, indent=2), encoding="utf-8")
|
||||
print(f" {_OPENCODE_CONFIG_PATH} -> plugin deregistered")
|
||||
|
||||
|
||||
_CODEX_HOOK = {
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"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."}' """
|
||||
"|| true"
|
||||
),
|
||||
}
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _install_codex_hook(project_dir: Path) -> None:
|
||||
"""Add graphify PreToolUse hook to .codex/hooks.json."""
|
||||
hooks_path = project_dir / ".codex" / "hooks.json"
|
||||
hooks_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if hooks_path.exists():
|
||||
try:
|
||||
existing = json.loads(hooks_path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
existing = {}
|
||||
else:
|
||||
existing = {}
|
||||
|
||||
pre_tool = existing.setdefault("hooks", {}).setdefault("PreToolUse", [])
|
||||
existing["hooks"]["PreToolUse"] = [h for h in pre_tool if "graphify" not in str(h)]
|
||||
existing["hooks"]["PreToolUse"].extend(_CODEX_HOOK["hooks"]["PreToolUse"])
|
||||
hooks_path.write_text(json.dumps(existing, indent=2), encoding="utf-8")
|
||||
print(f" .codex/hooks.json -> PreToolUse hook registered")
|
||||
|
||||
|
||||
def _uninstall_codex_hook(project_dir: Path) -> None:
|
||||
"""Remove graphify PreToolUse hook from .codex/hooks.json."""
|
||||
hooks_path = project_dir / ".codex" / "hooks.json"
|
||||
if not hooks_path.exists():
|
||||
return
|
||||
try:
|
||||
existing = json.loads(hooks_path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
pre_tool = existing.get("hooks", {}).get("PreToolUse", [])
|
||||
filtered = [h for h in pre_tool if "graphify" not in str(h)]
|
||||
existing["hooks"]["PreToolUse"] = filtered
|
||||
hooks_path.write_text(json.dumps(existing, indent=2), encoding="utf-8")
|
||||
print(f" .codex/hooks.json -> PreToolUse hook removed")
|
||||
|
||||
|
||||
def _agents_install(project_dir: Path, platform: str) -> None:
|
||||
"""Write the graphify section to the local AGENTS.md (Codex/OpenCode/OpenClaw)."""
|
||||
target = (project_dir or Path(".")) / "AGENTS.md"
|
||||
|
||||
if target.exists():
|
||||
content = target.read_text(encoding="utf-8")
|
||||
if _AGENTS_MD_MARKER in content:
|
||||
print(f"graphify already configured in AGENTS.md")
|
||||
else:
|
||||
target.write_text(content.rstrip() + "\n\n" + _AGENTS_MD_SECTION, encoding="utf-8")
|
||||
print(f"graphify section written to {target.resolve()}")
|
||||
else:
|
||||
target.write_text(_AGENTS_MD_SECTION, encoding="utf-8")
|
||||
print(f"graphify section written to {target.resolve()}")
|
||||
|
||||
if platform == "codex":
|
||||
_install_codex_hook(project_dir or Path("."))
|
||||
elif platform == "opencode":
|
||||
_install_opencode_plugin(project_dir or Path("."))
|
||||
|
||||
print()
|
||||
print(f"{platform.capitalize()} will now check the knowledge graph before answering")
|
||||
print("codebase questions and rebuild it after code changes.")
|
||||
if platform not in ("codex", "opencode"):
|
||||
print()
|
||||
print("Note: unlike Claude Code, there is no PreToolUse hook equivalent for")
|
||||
print(f"{platform.capitalize()} — the AGENTS.md rules are the always-on mechanism.")
|
||||
|
||||
|
||||
def _agents_uninstall(project_dir: Path) -> None:
|
||||
"""Remove the graphify section from the local AGENTS.md."""
|
||||
target = (project_dir or Path(".")) / "AGENTS.md"
|
||||
|
||||
if not target.exists():
|
||||
print("No AGENTS.md found in current directory - nothing to do")
|
||||
return
|
||||
|
||||
content = target.read_text(encoding="utf-8")
|
||||
if _AGENTS_MD_MARKER not in content:
|
||||
print("graphify section not found in AGENTS.md - nothing to do")
|
||||
return
|
||||
|
||||
cleaned = re.sub(
|
||||
r"\n*## graphify\n.*?(?=\n## |\Z)",
|
||||
"",
|
||||
content,
|
||||
flags=re.DOTALL,
|
||||
).rstrip()
|
||||
if cleaned:
|
||||
target.write_text(cleaned + "\n", encoding="utf-8")
|
||||
print(f"graphify section removed from {target.resolve()}")
|
||||
else:
|
||||
target.unlink()
|
||||
print(f"AGENTS.md was empty after removal - deleted {target.resolve()}")
|
||||
|
||||
_uninstall_opencode_plugin(project_dir or Path("."))
|
||||
|
||||
|
||||
def claude_install(project_dir: Path | None = None) -> None:
|
||||
"""Write the graphify section to the local CLAUDE.md."""
|
||||
target = (project_dir or Path(".")) / "CLAUDE.md"
|
||||
|
||||
if target.exists():
|
||||
content = target.read_text(encoding="utf-8")
|
||||
content = target.read_text()
|
||||
if _CLAUDE_MD_MARKER in content:
|
||||
print("graphify already configured in CLAUDE.md")
|
||||
return
|
||||
@@ -546,7 +94,7 @@ def claude_install(project_dir: Path | None = None) -> None:
|
||||
else:
|
||||
new_content = _CLAUDE_MD_SECTION
|
||||
|
||||
target.write_text(new_content, encoding="utf-8")
|
||||
target.write_text(new_content)
|
||||
print(f"graphify section written to {target.resolve()}")
|
||||
|
||||
# Also write Claude Code PreToolUse hook to .claude/settings.json
|
||||
@@ -564,7 +112,7 @@ def _install_claude_hook(project_dir: Path) -> None:
|
||||
|
||||
if settings_path.exists():
|
||||
try:
|
||||
settings = json.loads(settings_path.read_text(encoding="utf-8"))
|
||||
settings = json.loads(settings_path.read_text())
|
||||
except json.JSONDecodeError:
|
||||
settings = {}
|
||||
else:
|
||||
@@ -573,10 +121,14 @@ def _install_claude_hook(project_dir: Path) -> None:
|
||||
hooks = settings.setdefault("hooks", {})
|
||||
pre_tool = hooks.setdefault("PreToolUse", [])
|
||||
|
||||
hooks["PreToolUse"] = [h for h in pre_tool if not (h.get("matcher") == "Glob|Grep" and "graphify" in str(h))]
|
||||
hooks["PreToolUse"].append(_SETTINGS_HOOK)
|
||||
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
|
||||
print(f" .claude/settings.json -> PreToolUse hook registered")
|
||||
# Check if already installed
|
||||
if any(h.get("matcher") == "Glob|Grep" and "graphify" in str(h) for h in pre_tool):
|
||||
print(f" .claude/settings.json → hook already registered (no change)")
|
||||
return
|
||||
|
||||
pre_tool.append(_SETTINGS_HOOK)
|
||||
settings_path.write_text(json.dumps(settings, indent=2))
|
||||
print(f" .claude/settings.json → PreToolUse hook registered")
|
||||
|
||||
|
||||
def _uninstall_claude_hook(project_dir: Path) -> None:
|
||||
@@ -585,7 +137,7 @@ def _uninstall_claude_hook(project_dir: Path) -> None:
|
||||
if not settings_path.exists():
|
||||
return
|
||||
try:
|
||||
settings = json.loads(settings_path.read_text(encoding="utf-8"))
|
||||
settings = json.loads(settings_path.read_text())
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
pre_tool = settings.get("hooks", {}).get("PreToolUse", [])
|
||||
@@ -593,8 +145,8 @@ def _uninstall_claude_hook(project_dir: Path) -> None:
|
||||
if len(filtered) == len(pre_tool):
|
||||
return
|
||||
settings["hooks"]["PreToolUse"] = filtered
|
||||
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
|
||||
print(f" .claude/settings.json -> PreToolUse hook removed")
|
||||
settings_path.write_text(json.dumps(settings, indent=2))
|
||||
print(f" .claude/settings.json → PreToolUse hook removed")
|
||||
|
||||
|
||||
def claude_uninstall(project_dir: Path | None = None) -> None:
|
||||
@@ -605,7 +157,7 @@ def claude_uninstall(project_dir: Path | None = None) -> None:
|
||||
print("No CLAUDE.md found in current directory - nothing to do")
|
||||
return
|
||||
|
||||
content = target.read_text(encoding="utf-8")
|
||||
content = target.read_text()
|
||||
if _CLAUDE_MD_MARKER not in content:
|
||||
print("graphify section not found in CLAUDE.md - nothing to do")
|
||||
return
|
||||
@@ -618,7 +170,7 @@ def claude_uninstall(project_dir: Path | None = None) -> None:
|
||||
flags=re.DOTALL,
|
||||
).rstrip()
|
||||
if cleaned:
|
||||
target.write_text(cleaned + "\n", encoding="utf-8")
|
||||
target.write_text(cleaned + "\n")
|
||||
print(f"graphify section removed from {target.resolve()}")
|
||||
else:
|
||||
target.unlink()
|
||||
@@ -628,72 +180,23 @@ 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)
|
||||
|
||||
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(" 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)")
|
||||
print(" --graph <path> path to graph.json (default graphify-out/graph.json)")
|
||||
print(" save-result save a Q&A result to graphify-out/memory/ for graph feedback loop")
|
||||
print(" --question Q the question asked")
|
||||
print(" --answer A the answer to save")
|
||||
print(" --type T query type: query|path_query|explain (default: query)")
|
||||
print(" --nodes N1 N2 ... source node labels cited in the answer")
|
||||
print(" --memory-dir DIR memory directory (default: graphify-out/memory)")
|
||||
print(" install copy skill to ~/.claude/skills/ and register in CLAUDE.md")
|
||||
print(" benchmark [graph.json] measure token reduction vs naive full-corpus approach")
|
||||
print(" hook install install post-commit/post-checkout git hooks (all platforms)")
|
||||
print(" hook uninstall remove git hooks")
|
||||
print(" hook status check if git hooks are installed")
|
||||
print(" gemini install write GEMINI.md section + BeforeTool hook (Gemini CLI)")
|
||||
print(" gemini uninstall remove GEMINI.md section + BeforeTool hook")
|
||||
print(" cursor install write .cursor/rules/graphify.mdc (Cursor)")
|
||||
print(" cursor uninstall remove .cursor/rules/graphify.mdc")
|
||||
print(" claude install write graphify section to CLAUDE.md + PreToolUse hook (Claude Code)")
|
||||
print(" claude uninstall remove graphify section from CLAUDE.md + PreToolUse hook")
|
||||
print(" codex install write graphify section to AGENTS.md (Codex)")
|
||||
print(" codex uninstall remove graphify section from AGENTS.md")
|
||||
print(" opencode install write graphify section to AGENTS.md + tool.execute.before plugin (OpenCode)")
|
||||
print(" opencode uninstall remove graphify section from AGENTS.md + plugin")
|
||||
print(" aider install write graphify section to AGENTS.md (Aider)")
|
||||
print(" aider uninstall remove graphify section from AGENTS.md")
|
||||
print(" copilot install copy graphify skill to ~/.copilot/skills (GitHub Copilot CLI)")
|
||||
print(" copilot uninstall remove graphify skill from ~/.copilot/skills")
|
||||
print(" claw install write graphify section to AGENTS.md (OpenClaw)")
|
||||
print(" claw uninstall remove graphify section from AGENTS.md")
|
||||
print(" droid install write graphify section to AGENTS.md (Factory Droid)")
|
||||
print(" droid uninstall remove graphify section from AGENTS.md")
|
||||
print(" trae install write graphify section to AGENTS.md (Trae)")
|
||||
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(" hook install install post-commit git hook (auto-rebuilds graph on commit)")
|
||||
print(" hook uninstall remove post-commit git hook")
|
||||
print(" hook status check if hook is installed")
|
||||
print(" claude install write graphify section to local CLAUDE.md")
|
||||
print(" claude uninstall remove graphify section from local CLAUDE.md")
|
||||
print()
|
||||
return
|
||||
|
||||
cmd = sys.argv[1]
|
||||
if cmd == "install":
|
||||
# Default to windows platform on Windows, claude elsewhere
|
||||
default_platform = "windows" if platform.system() == "Windows" else "claude"
|
||||
chosen_platform = default_platform
|
||||
args = sys.argv[2:]
|
||||
i = 0
|
||||
while i < len(args):
|
||||
if args[i].startswith("--platform="):
|
||||
chosen_platform = args[i].split("=", 1)[1]
|
||||
i += 1
|
||||
elif args[i] == "--platform" and i + 1 < len(args):
|
||||
chosen_platform = args[i + 1]
|
||||
i += 2
|
||||
else:
|
||||
i += 1
|
||||
install(platform=chosen_platform)
|
||||
install()
|
||||
elif cmd == "claude":
|
||||
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
if subcmd == "install":
|
||||
@@ -703,57 +206,6 @@ def main() -> None:
|
||||
else:
|
||||
print("Usage: graphify claude [install|uninstall]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
elif cmd == "gemini":
|
||||
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
if subcmd == "install":
|
||||
gemini_install()
|
||||
elif subcmd == "uninstall":
|
||||
gemini_uninstall()
|
||||
else:
|
||||
print("Usage: graphify gemini [install|uninstall]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
elif cmd == "cursor":
|
||||
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
if subcmd == "install":
|
||||
_cursor_install(Path("."))
|
||||
elif subcmd == "uninstall":
|
||||
_cursor_uninstall(Path("."))
|
||||
else:
|
||||
print("Usage: graphify cursor [install|uninstall]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
elif cmd == "copilot":
|
||||
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
if subcmd == "install":
|
||||
install(platform="copilot")
|
||||
elif subcmd == "uninstall":
|
||||
skill_dst = Path.home() / _PLATFORM_CONFIG["copilot"]["skill_dst"]
|
||||
removed = []
|
||||
if skill_dst.exists():
|
||||
skill_dst.unlink()
|
||||
removed.append(f"skill removed: {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
|
||||
print("; ".join(removed) if removed else "nothing to remove")
|
||||
else:
|
||||
print("Usage: graphify copilot [install|uninstall]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
elif cmd in ("aider", "codex", "opencode", "claw", "droid", "trae", "trae-cn"):
|
||||
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
if subcmd == "install":
|
||||
_agents_install(Path("."), cmd)
|
||||
elif subcmd == "uninstall":
|
||||
_agents_uninstall(Path("."))
|
||||
if cmd == "codex":
|
||||
_uninstall_codex_hook(Path("."))
|
||||
else:
|
||||
print(f"Usage: graphify {cmd} [install|uninstall]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
elif cmd == "hook":
|
||||
from graphify.hooks import install as hook_install, uninstall as hook_uninstall, status as hook_status
|
||||
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
@@ -766,85 +218,6 @@ def main() -> None:
|
||||
else:
|
||||
print("Usage: graphify hook [install|uninstall|status]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
elif cmd == "query":
|
||||
if len(sys.argv) < 3:
|
||||
print("Usage: graphify query \"<question>\" [--dfs] [--budget N] [--graph path]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
from graphify.serve import _score_nodes, _bfs, _dfs, _subgraph_to_text
|
||||
from graphify.security import sanitize_label
|
||||
from networkx.readwrite import json_graph
|
||||
question = sys.argv[2]
|
||||
use_dfs = "--dfs" in sys.argv
|
||||
budget = 2000
|
||||
graph_path = "graphify-out/graph.json"
|
||||
args = sys.argv[3:]
|
||||
i = 0
|
||||
while i < len(args):
|
||||
if args[i] == "--budget" and i + 1 < len(args):
|
||||
try:
|
||||
budget = int(args[i + 1])
|
||||
except ValueError:
|
||||
print(f"error: --budget must be an integer", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
i += 2
|
||||
elif args[i].startswith("--budget="):
|
||||
try:
|
||||
budget = int(args[i].split("=", 1)[1])
|
||||
except ValueError:
|
||||
print(f"error: --budget must be an integer", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
i += 1
|
||||
elif args[i] == "--graph" and i + 1 < len(args):
|
||||
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)
|
||||
sys.exit(1)
|
||||
if not gp.suffix == ".json":
|
||||
print(f"error: graph file must be a .json file", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
try:
|
||||
import json as _json
|
||||
import networkx as _nx
|
||||
_raw = _json.loads(gp.read_text(encoding="utf-8"))
|
||||
try:
|
||||
G = json_graph.node_link_graph(_raw, edges="links")
|
||||
except TypeError:
|
||||
G = json_graph.node_link_graph(_raw)
|
||||
except Exception as exc:
|
||||
print(f"error: could not load graph: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
terms = [t.lower() for t in question.split() if len(t) > 2]
|
||||
scored = _score_nodes(G, terms)
|
||||
if not scored:
|
||||
print("No matching nodes found.")
|
||||
sys.exit(0)
|
||||
start = [nid for _, nid in scored[:5]]
|
||||
nodes, edges = (_dfs if use_dfs else _bfs)(G, start, depth=2)
|
||||
print(_subgraph_to_text(G, nodes, edges, token_budget=budget))
|
||||
elif cmd == "save-result":
|
||||
# graphify save-result --question Q --answer A --type T [--nodes N1 N2 ...]
|
||||
import argparse as _ap
|
||||
p = _ap.ArgumentParser(prog="graphify save-result")
|
||||
p.add_argument("--question", required=True)
|
||||
p.add_argument("--answer", required=True)
|
||||
p.add_argument("--type", dest="query_type", default="query")
|
||||
p.add_argument("--nodes", nargs="*", default=[])
|
||||
p.add_argument("--memory-dir", default="graphify-out/memory")
|
||||
opts = p.parse_args(sys.argv[2:])
|
||||
from graphify.ingest import save_query_result as _sqr
|
||||
out = _sqr(
|
||||
question=opts.question,
|
||||
answer=opts.answer,
|
||||
memory_dir=Path(opts.memory_dir),
|
||||
query_type=opts.query_type,
|
||||
source_nodes=opts.nodes or None,
|
||||
)
|
||||
print(f"Saved to {out}")
|
||||
elif cmd == "benchmark":
|
||||
from graphify.benchmark import run_benchmark, print_benchmark
|
||||
graph_path = sys.argv[2] if len(sys.argv) > 2 else "graphify-out/graph.json"
|
||||
@@ -853,7 +226,7 @@ def main() -> None:
|
||||
detect_path = Path(".graphify_detect.json")
|
||||
if detect_path.exists():
|
||||
try:
|
||||
detect_data = json.loads(detect_path.read_text(encoding="utf-8"))
|
||||
detect_data = json.loads(detect_path.read_text())
|
||||
corpus_words = detect_data.get("total_words")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
+13
-16
@@ -16,16 +16,12 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
|
||||
These are synthetic nodes created by the AST extractor and should be excluded
|
||||
from god nodes, surprising connections, and knowledge gap reporting.
|
||||
"""
|
||||
attrs = G.nodes[node_id]
|
||||
label = attrs.get("label", "")
|
||||
label = G.nodes[node_id].get("label", "")
|
||||
if not label:
|
||||
return False
|
||||
# File-level hub: label matches the actual source filename (not just any label ending in .py)
|
||||
source_file = attrs.get("source_file", "")
|
||||
if source_file:
|
||||
from pathlib import Path as _Path
|
||||
if label == _Path(source_file).name:
|
||||
return True
|
||||
# File-level hub: label is a filename with a code extension
|
||||
if label.split(".")[-1] in ("py", "ts", "js", "go", "rs", "java", "rb", "cpp", "c", "h"):
|
||||
return True
|
||||
# Method stub: AST extractor labels methods as '.method_name()'
|
||||
if label.startswith(".") and label.endswith("()"):
|
||||
return True
|
||||
@@ -109,16 +105,19 @@ def _is_concept_node(G: nx.Graph, node_id: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
from graphify.detect import CODE_EXTENSIONS, DOC_EXTENSIONS, PAPER_EXTENSIONS, IMAGE_EXTENSIONS
|
||||
_CODE_EXTENSIONS = {"py", "ts", "tsx", "js", "go", "rs", "java", "rb", "cpp", "c", "h", "cs", "kt", "scala", "php"}
|
||||
_DOC_EXTENSIONS = {"md", "txt", "rst"}
|
||||
_PAPER_EXTENSIONS = {"pdf"}
|
||||
_IMAGE_EXTENSIONS = {"png", "jpg", "jpeg", "webp", "gif", "svg"}
|
||||
|
||||
|
||||
def _file_category(path: str) -> str:
|
||||
ext = ("." + path.rsplit(".", 1)[-1].lower()) if "." in path else ""
|
||||
if ext in CODE_EXTENSIONS:
|
||||
ext = path.rsplit(".", 1)[-1].lower() if "." in path else ""
|
||||
if ext in _CODE_EXTENSIONS:
|
||||
return "code"
|
||||
if ext in PAPER_EXTENSIONS:
|
||||
if ext in _PAPER_EXTENSIONS:
|
||||
return "paper"
|
||||
if ext in IMAGE_EXTENSIONS:
|
||||
if ext in _IMAGE_EXTENSIONS:
|
||||
return "image"
|
||||
return "doc"
|
||||
|
||||
@@ -469,9 +468,7 @@ def graph_diff(G_old: nx.Graph, G_new: nx.Graph) -> dict:
|
||||
]
|
||||
|
||||
def edge_key(G: nx.Graph, u: str, v: str, data: dict) -> tuple:
|
||||
if G.is_directed():
|
||||
return (u, v, data.get("relation", ""))
|
||||
return (min(u, v), max(u, v), data.get("relation", ""))
|
||||
return (u, v, data.get("relation", ""))
|
||||
|
||||
old_edge_keys = {
|
||||
edge_key(G_old, u, v, d)
|
||||
|
||||
@@ -76,10 +76,7 @@ def run_benchmark(
|
||||
Returns dict with: corpus_tokens, avg_query_tokens, reduction_ratio, per_question
|
||||
"""
|
||||
data = json.loads(Path(graph_path).read_text())
|
||||
try:
|
||||
G = json_graph.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
G = json_graph.node_link_graph(data)
|
||||
G = json_graph.node_link_graph(data, edges="links")
|
||||
|
||||
if corpus_words is None:
|
||||
# Rough estimate: each node label is ~3 words, plus source context
|
||||
|
||||
+6
-42
@@ -1,43 +1,17 @@
|
||||
# assemble node+edge dicts into a NetworkX graph, preserving edge direction
|
||||
#
|
||||
# Node deduplication — three layers:
|
||||
#
|
||||
# 1. Within a file (AST): each extractor tracks a `seen_ids` set. A node ID is
|
||||
# emitted at most once per file, so duplicate class/function definitions in
|
||||
# the same source file are collapsed to the first occurrence.
|
||||
#
|
||||
# 2. Between files (build): NetworkX G.add_node() is idempotent — calling it
|
||||
# twice with the same ID overwrites the attributes with the second call's
|
||||
# values. Nodes are added in extraction order (AST first, then semantic),
|
||||
# so if the same entity is extracted by both passes the semantic node
|
||||
# silently overwrites the AST node. This is intentional: semantic nodes
|
||||
# carry richer labels and cross-file context, while AST nodes have precise
|
||||
# source_location. If you need to change the priority, reorder extractions
|
||||
# passed to build().
|
||||
#
|
||||
# 3. Semantic merge (skill): before calling build(), the skill merges cached
|
||||
# and new semantic results using an explicit `seen` set keyed on node["id"],
|
||||
# so duplicates across cache hits and new extractions are resolved there
|
||||
# before any graph construction happens.
|
||||
#
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
import networkx as nx
|
||||
from .validate import validate_extraction
|
||||
|
||||
|
||||
def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
|
||||
"""Build a NetworkX graph from an extraction dict.
|
||||
|
||||
directed=True produces a DiGraph that preserves edge direction (source→target).
|
||||
directed=False (default) produces an undirected Graph for backward compatibility.
|
||||
"""
|
||||
def build_from_json(extraction: dict) -> nx.Graph:
|
||||
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]
|
||||
if real_errors:
|
||||
print(f"[graphify] Extraction warning ({len(real_errors)} issues): {real_errors[0]}", file=sys.stderr)
|
||||
G: nx.Graph = nx.DiGraph() if directed else nx.Graph()
|
||||
G = nx.Graph()
|
||||
for node in extraction.get("nodes", []):
|
||||
G.add_node(node["id"], **{k: v for k, v in node.items() if k != "id"})
|
||||
node_set = set(G.nodes())
|
||||
@@ -57,22 +31,12 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
|
||||
return G
|
||||
|
||||
|
||||
def build(extractions: list[dict], *, directed: bool = False) -> nx.Graph:
|
||||
"""Merge multiple extraction results into one graph.
|
||||
|
||||
directed=True produces a DiGraph that preserves edge direction (source→target).
|
||||
directed=False (default) produces an undirected Graph for backward compatibility.
|
||||
|
||||
Extractions are merged in order. For nodes with the same ID, the last
|
||||
extraction's attributes win (NetworkX add_node overwrites). Pass AST
|
||||
results before semantic results so semantic labels take precedence, or
|
||||
reverse the order if you prefer AST source_location precision to win.
|
||||
"""
|
||||
combined: dict = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
def build(extractions: list[dict]) -> nx.Graph:
|
||||
"""Merge multiple extraction results into one graph."""
|
||||
combined: dict = {"nodes": [], "edges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
for ext in extractions:
|
||||
combined["nodes"].extend(ext.get("nodes", []))
|
||||
combined["edges"].extend(ext.get("edges", []))
|
||||
combined["hyperedges"].extend(ext.get("hyperedges", []))
|
||||
combined["input_tokens"] += ext.get("input_tokens", 0)
|
||||
combined["output_tokens"] += ext.get("output_tokens", 0)
|
||||
return build_from_json(combined, directed=directed)
|
||||
return build_from_json(combined)
|
||||
+3
-33
@@ -3,34 +3,12 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _body_content(content: bytes) -> bytes:
|
||||
"""Strip YAML frontmatter from Markdown content, returning only the body."""
|
||||
text = content.decode(errors="replace")
|
||||
if text.startswith("---"):
|
||||
end = text.find("\n---", 3)
|
||||
if end != -1:
|
||||
return text[end + 4:].encode()
|
||||
return content
|
||||
|
||||
|
||||
def file_hash(path: Path) -> str:
|
||||
"""SHA256 of file contents + resolved path. Prevents cache collisions on identical content.
|
||||
|
||||
For Markdown files (.md), only the body below the YAML frontmatter is hashed,
|
||||
so metadata-only changes (e.g. reviewed, status, tags) do not invalidate the cache.
|
||||
"""
|
||||
p = Path(path)
|
||||
raw = p.read_bytes()
|
||||
content = _body_content(raw) if p.suffix.lower() == ".md" else raw
|
||||
h = hashlib.sha256()
|
||||
h.update(content)
|
||||
h.update(b"\x00")
|
||||
h.update(str(p.resolve()).encode())
|
||||
return h.hexdigest()
|
||||
"""SHA256 of file contents, hex digest."""
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def cache_dir(root: Path = Path(".")) -> Path:
|
||||
@@ -68,13 +46,7 @@ def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
|
||||
"""
|
||||
h = file_hash(path)
|
||||
entry = cache_dir(root) / f"{h}.json"
|
||||
tmp = entry.with_suffix(".tmp")
|
||||
try:
|
||||
tmp.write_text(json.dumps(result))
|
||||
os.replace(tmp, entry)
|
||||
except Exception:
|
||||
tmp.unlink(missing_ok=True)
|
||||
raise
|
||||
entry.write_text(json.dumps(result))
|
||||
|
||||
|
||||
def cached_files(root: Path = Path(".")) -> set[str]:
|
||||
@@ -146,8 +118,6 @@ def save_semantic_cache(
|
||||
saved = 0
|
||||
for fpath, result in by_file.items():
|
||||
p = Path(fpath)
|
||||
if not p.is_absolute():
|
||||
p = Path(root) / p
|
||||
if p.exists():
|
||||
save_cached(p, result, root)
|
||||
saved += 1
|
||||
|
||||
+20
-40
@@ -1,57 +1,42 @@
|
||||
"""Community detection on NetworkX graphs. Uses Leiden (graspologic) if available, falls back to Louvain (networkx). Splits oversized communities. Returns cohesion scores."""
|
||||
from __future__ import annotations
|
||||
import contextlib
|
||||
import inspect
|
||||
import io
|
||||
import sys
|
||||
import networkx as nx
|
||||
|
||||
|
||||
def _suppress_output():
|
||||
"""Context manager to suppress stdout/stderr during library calls.
|
||||
|
||||
graspologic's leiden() emits ANSI escape sequences (progress bars,
|
||||
colored warnings) that corrupt PowerShell 5.1's scroll buffer on
|
||||
Windows (see issue #19). Redirecting stdout/stderr to devnull during
|
||||
the call prevents this without losing any graphify output.
|
||||
"""
|
||||
return contextlib.redirect_stdout(io.StringIO())
|
||||
|
||||
|
||||
def _partition(G: nx.Graph) -> dict[str, int]:
|
||||
"""Run community detection. Returns {node_id: community_id}.
|
||||
|
||||
Tries Leiden (graspologic) first — best quality.
|
||||
Falls back to Louvain (built into networkx) if graspologic is not installed.
|
||||
|
||||
Output from graspologic is suppressed to prevent ANSI escape codes
|
||||
from corrupting terminal scroll buffers on Windows PowerShell 5.1.
|
||||
"""
|
||||
try:
|
||||
from graspologic.partition import leiden
|
||||
# Suppress graspologic output to prevent ANSI escape codes from
|
||||
# corrupting PowerShell 5.1 scroll buffer (issue #19)
|
||||
old_stderr = sys.stderr
|
||||
try:
|
||||
sys.stderr = io.StringIO()
|
||||
with _suppress_output():
|
||||
result = leiden(G)
|
||||
finally:
|
||||
sys.stderr = old_stderr
|
||||
return result
|
||||
return leiden(G)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Fallback: networkx louvain (available since networkx 2.7).
|
||||
# Inspect kwargs to stay compatible across NetworkX versions — max_level
|
||||
# was added in a later release and prevents hangs on large sparse graphs.
|
||||
kwargs: dict = {"seed": 42, "threshold": 1e-4}
|
||||
if "max_level" in inspect.signature(nx.community.louvain_communities).parameters:
|
||||
kwargs["max_level"] = 10
|
||||
communities = nx.community.louvain_communities(G, **kwargs)
|
||||
# Fallback: networkx louvain (available since networkx 2.7)
|
||||
communities = nx.community.louvain_communities(G, seed=42)
|
||||
return {node: cid for cid, nodes in enumerate(communities) for node in nodes}
|
||||
|
||||
|
||||
def build_graph(nodes: list[dict], edges: list[dict]) -> nx.Graph:
|
||||
"""Build a NetworkX graph from graphify node/edge dicts.
|
||||
|
||||
Preserves original edge direction as _src/_tgt attributes so that
|
||||
display functions can show relationships in the correct direction,
|
||||
even though the graph is undirected for structural analysis.
|
||||
"""
|
||||
G = nx.Graph()
|
||||
for n in nodes:
|
||||
G.add_node(n["id"], **{k: v for k, v in n.items() if k != "id"})
|
||||
for e in edges:
|
||||
attrs = {k: v for k, v in e.items() if k not in ("source", "target")}
|
||||
attrs["_src"] = e["source"]
|
||||
attrs["_tgt"] = e["target"]
|
||||
G.add_edge(e["source"], e["target"], **attrs)
|
||||
return G
|
||||
|
||||
_MAX_COMMUNITY_FRACTION = 0.25 # communities larger than 25% of graph get split
|
||||
_MIN_SPLIT_SIZE = 10 # only split if community has at least this many nodes
|
||||
|
||||
@@ -62,14 +47,9 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
|
||||
Community IDs are stable across runs: 0 = largest community after splitting.
|
||||
Oversized communities (> 25% of graph nodes, min 10) are split by running
|
||||
a second Leiden pass on the subgraph.
|
||||
|
||||
Accepts directed or undirected graphs. DiGraphs are converted to undirected
|
||||
internally since Louvain/Leiden require undirected input.
|
||||
"""
|
||||
if G.number_of_nodes() == 0:
|
||||
return {}
|
||||
if G.is_directed():
|
||||
G = G.to_undirected()
|
||||
if G.number_of_edges() == 0:
|
||||
return {i: [n] for i, n in enumerate(sorted(G.nodes))}
|
||||
|
||||
|
||||
+6
-222
@@ -1,6 +1,5 @@
|
||||
# file discovery, type classification, and corpus health checks
|
||||
from __future__ import annotations
|
||||
import fnmatch
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -13,17 +12,14 @@ class FileType(str, Enum):
|
||||
DOCUMENT = "document"
|
||||
PAPER = "paper"
|
||||
IMAGE = "image"
|
||||
VIDEO = "video"
|
||||
|
||||
|
||||
_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', '.tsx', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php'}
|
||||
DOC_EXTENSIONS = {'.md', '.txt', '.rst'}
|
||||
PAPER_EXTENSIONS = {'.pdf'}
|
||||
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
|
||||
OFFICE_EXTENSIONS = {'.docx', '.xlsx'}
|
||||
VIDEO_EXTENSIONS = {'.mp4', '.mov', '.webm', '.mkv', '.avi', '.m4v', '.mp3', '.wav', '.m4a', '.ogg'}
|
||||
|
||||
CORPUS_WARN_THRESHOLD = 50_000 # words - below this, warn "you may not need a graph"
|
||||
CORPUS_UPPER_THRESHOLD = 500_000 # words - above this, warn about token cost
|
||||
@@ -76,17 +72,11 @@ def _looks_like_paper(path: Path) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
_ASSET_DIR_MARKERS = {".imageset", ".xcassets", ".appiconset", ".colorset", ".launchimage"}
|
||||
|
||||
|
||||
def classify_file(path: Path) -> FileType | None:
|
||||
ext = path.suffix.lower()
|
||||
if ext in CODE_EXTENSIONS:
|
||||
return FileType.CODE
|
||||
if ext in PAPER_EXTENSIONS:
|
||||
# PDFs inside Xcode asset catalogs are vector icons, not papers
|
||||
if any(part.endswith(tuple(_ASSET_DIR_MARKERS)) for part in path.parts):
|
||||
return None
|
||||
return FileType.PAPER
|
||||
if ext in IMAGE_EXTENSIONS:
|
||||
return FileType.IMAGE
|
||||
@@ -95,10 +85,6 @@ def classify_file(path: Path) -> FileType | None:
|
||||
if _looks_like_paper(path):
|
||||
return FileType.PAPER
|
||||
return FileType.DOCUMENT
|
||||
if ext in OFFICE_EXTENSIONS:
|
||||
return FileType.DOCUMENT
|
||||
if ext in VIDEO_EXTENSIONS:
|
||||
return FileType.VIDEO
|
||||
return None
|
||||
|
||||
|
||||
@@ -117,115 +103,10 @@ def extract_pdf_text(path: Path) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def docx_to_markdown(path: Path) -> str:
|
||||
"""Convert a .docx file to markdown text using python-docx."""
|
||||
try:
|
||||
from docx import Document
|
||||
from docx.oxml.ns import qn
|
||||
doc = Document(str(path))
|
||||
lines = []
|
||||
for para in doc.paragraphs:
|
||||
style = para.style.name if para.style else ""
|
||||
text = para.text.strip()
|
||||
if not text:
|
||||
lines.append("")
|
||||
continue
|
||||
if style.startswith("Heading 1"):
|
||||
lines.append(f"# {text}")
|
||||
elif style.startswith("Heading 2"):
|
||||
lines.append(f"## {text}")
|
||||
elif style.startswith("Heading 3"):
|
||||
lines.append(f"### {text}")
|
||||
elif style.startswith("List"):
|
||||
lines.append(f"- {text}")
|
||||
else:
|
||||
lines.append(text)
|
||||
# Tables
|
||||
for table in doc.tables:
|
||||
rows = [[cell.text.strip() for cell in row.cells] for row in table.rows]
|
||||
if not rows:
|
||||
continue
|
||||
header = "| " + " | ".join(rows[0]) + " |"
|
||||
sep = "| " + " | ".join("---" for _ in rows[0]) + " |"
|
||||
lines.extend([header, sep])
|
||||
for row in rows[1:]:
|
||||
lines.append("| " + " | ".join(row) + " |")
|
||||
return "\n".join(lines)
|
||||
except ImportError:
|
||||
return ""
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def xlsx_to_markdown(path: Path) -> str:
|
||||
"""Convert an .xlsx file to markdown text using openpyxl."""
|
||||
try:
|
||||
import openpyxl
|
||||
wb = openpyxl.load_workbook(str(path), read_only=True, data_only=True)
|
||||
sections = []
|
||||
for sheet_name in wb.sheetnames:
|
||||
ws = wb[sheet_name]
|
||||
rows = []
|
||||
for row in ws.iter_rows(values_only=True):
|
||||
# Skip entirely empty rows
|
||||
if all(cell is None for cell in row):
|
||||
continue
|
||||
rows.append([str(cell) if cell is not None else "" for cell in row])
|
||||
if not rows:
|
||||
continue
|
||||
sections.append(f"## Sheet: {sheet_name}")
|
||||
if len(rows) >= 1:
|
||||
header = "| " + " | ".join(rows[0]) + " |"
|
||||
sep = "| " + " | ".join("---" for _ in rows[0]) + " |"
|
||||
sections.extend([header, sep])
|
||||
for row in rows[1:]:
|
||||
sections.append("| " + " | ".join(row) + " |")
|
||||
wb.close()
|
||||
return "\n".join(sections)
|
||||
except ImportError:
|
||||
return ""
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def convert_office_file(path: Path, out_dir: Path) -> Path | None:
|
||||
"""Convert a .docx or .xlsx to a markdown sidecar in out_dir.
|
||||
|
||||
Returns the path of the converted .md file, or None if conversion failed
|
||||
or the required library is not installed.
|
||||
"""
|
||||
ext = path.suffix.lower()
|
||||
if ext == ".docx":
|
||||
text = docx_to_markdown(path)
|
||||
elif ext == ".xlsx":
|
||||
text = xlsx_to_markdown(path)
|
||||
else:
|
||||
return None
|
||||
|
||||
if not text.strip():
|
||||
return None
|
||||
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
# Use a stable name derived from the original path to avoid collisions
|
||||
import hashlib
|
||||
name_hash = hashlib.sha256(str(path.resolve()).encode()).hexdigest()[:8]
|
||||
out_path = out_dir / f"{path.stem}_{name_hash}.md"
|
||||
out_path.write_text(
|
||||
f"<!-- converted from {path.name} -->\n\n{text}",
|
||||
encoding="utf-8",
|
||||
)
|
||||
return out_path
|
||||
|
||||
|
||||
def count_words(path: Path) -> int:
|
||||
try:
|
||||
ext = path.suffix.lower()
|
||||
if ext == ".pdf":
|
||||
if path.suffix.lower() == ".pdf":
|
||||
return len(extract_pdf_text(path).split())
|
||||
if ext == ".docx":
|
||||
return len(docx_to_markdown(path).split())
|
||||
if ext == ".xlsx":
|
||||
return len(xlsx_to_markdown(path).split())
|
||||
return len(path.read_text(errors="ignore").split())
|
||||
except Exception:
|
||||
return 0
|
||||
@@ -253,81 +134,16 @@ def _is_noise_dir(part: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _load_graphifyignore(root: Path) -> list[str]:
|
||||
"""Read .graphifyignore from root **and ancestor directories**, returning patterns.
|
||||
|
||||
Walks upward from *root* towards the filesystem root, collecting patterns
|
||||
from every ``.graphifyignore`` encountered (like ``.gitignore`` discovery).
|
||||
The search stops at the filesystem root or at a ``.git`` directory boundary
|
||||
so it doesn't leak outside the repository.
|
||||
|
||||
Lines starting with # are comments. Blank lines are ignored.
|
||||
Patterns follow gitignore semantics: glob matched against the path
|
||||
relative to root. A leading slash anchors to root. A trailing slash
|
||||
matches directories only (we match both dir and file for simplicity).
|
||||
"""
|
||||
patterns: list[str] = []
|
||||
current = root.resolve()
|
||||
while True:
|
||||
ignore_file = current / ".graphifyignore"
|
||||
if ignore_file.exists():
|
||||
for line in ignore_file.read_text(errors="ignore").splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#"):
|
||||
patterns.append(line)
|
||||
# Stop climbing once we've processed the git repo root
|
||||
if (current / ".git").exists():
|
||||
break
|
||||
parent = current.parent
|
||||
if parent == current:
|
||||
break # filesystem root
|
||||
current = parent
|
||||
return patterns
|
||||
|
||||
|
||||
def _is_ignored(path: Path, root: Path, patterns: list[str]) -> bool:
|
||||
"""Return True if path matches any .graphifyignore pattern."""
|
||||
if not patterns:
|
||||
return False
|
||||
try:
|
||||
rel = str(path.relative_to(root))
|
||||
except ValueError:
|
||||
return False
|
||||
rel = rel.replace(os.sep, "/")
|
||||
parts = rel.split("/")
|
||||
for pattern in patterns:
|
||||
# Normalize: strip leading/trailing slashes for matching purposes
|
||||
p = pattern.strip("/")
|
||||
if not p:
|
||||
continue
|
||||
# Match against full relative path
|
||||
if fnmatch.fnmatch(rel, p):
|
||||
return True
|
||||
# Match against filename alone
|
||||
if fnmatch.fnmatch(path.name, p):
|
||||
return True
|
||||
# Match against any path segment or prefix
|
||||
# e.g. "vendor" or "vendor/" should match "vendor/lib.py"
|
||||
for i, part in enumerate(parts):
|
||||
if fnmatch.fnmatch(part, p):
|
||||
return True
|
||||
if fnmatch.fnmatch("/".join(parts[:i + 1]), p):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
def detect(root: Path) -> dict:
|
||||
files: dict[FileType, list[str]] = {
|
||||
FileType.CODE: [],
|
||||
FileType.DOCUMENT: [],
|
||||
FileType.PAPER: [],
|
||||
FileType.IMAGE: [],
|
||||
FileType.VIDEO: [],
|
||||
}
|
||||
total_words = 0
|
||||
|
||||
skipped_sensitive: list[str] = []
|
||||
ignore_patterns = _load_graphifyignore(root)
|
||||
|
||||
# Always include graphify-out/memory/ - query results filed back into the graph
|
||||
memory_dir = root / "graphify-out" / "memory"
|
||||
@@ -340,21 +156,13 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
|
||||
for scan_root in scan_paths:
|
||||
in_memory_tree = memory_dir.exists() and str(scan_root).startswith(str(memory_dir))
|
||||
for dirpath, dirnames, filenames in os.walk(scan_root, followlinks=follow_symlinks):
|
||||
for dirpath, dirnames, filenames in os.walk(scan_root, followlinks=False):
|
||||
dp = Path(dirpath)
|
||||
if follow_symlinks and os.path.islink(dirpath):
|
||||
real = os.path.realpath(dirpath)
|
||||
parent_real = os.path.realpath(os.path.dirname(dirpath))
|
||||
if parent_real == real or parent_real.startswith(real + os.sep):
|
||||
dirnames.clear()
|
||||
continue
|
||||
if not in_memory_tree:
|
||||
# Prune noise dirs in-place so os.walk never descends into them
|
||||
dirnames[:] = [
|
||||
d for d in dirnames
|
||||
if not d.startswith(".")
|
||||
and not _is_noise_dir(d)
|
||||
and not _is_ignored(dp / d, root, ignore_patterns)
|
||||
if not d.startswith(".") and not _is_noise_dir(d)
|
||||
]
|
||||
for fname in filenames:
|
||||
p = dp / fname
|
||||
@@ -362,8 +170,6 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
seen.add(p)
|
||||
all_files.append(p)
|
||||
|
||||
converted_dir = root / "graphify-out" / "converted"
|
||||
|
||||
for p in all_files:
|
||||
# For memory dir files, skip hidden/noise filtering
|
||||
in_memory = memory_dir.exists() and str(p).startswith(str(memory_dir))
|
||||
@@ -372,29 +178,13 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
# but catch hidden files at the root level
|
||||
if p.name.startswith("."):
|
||||
continue
|
||||
# Skip files inside our own converted/ dir (avoid re-processing sidecars)
|
||||
if str(p).startswith(str(converted_dir)):
|
||||
continue
|
||||
if _is_ignored(p, root, ignore_patterns):
|
||||
continue
|
||||
if _is_sensitive(p):
|
||||
skipped_sensitive.append(str(p))
|
||||
continue
|
||||
ftype = classify_file(p)
|
||||
if ftype:
|
||||
# Office files: convert to markdown sidecar so subagents can read them
|
||||
if p.suffix.lower() in OFFICE_EXTENSIONS:
|
||||
md_path = convert_office_file(p, converted_dir)
|
||||
if md_path:
|
||||
files[ftype].append(str(md_path))
|
||||
total_words += count_words(md_path)
|
||||
else:
|
||||
# Conversion failed (library not installed) - skip with note
|
||||
skipped_sensitive.append(str(p) + " [office conversion failed - pip install graphifyy[office]]")
|
||||
continue
|
||||
files[ftype].append(str(p))
|
||||
if ftype != FileType.VIDEO:
|
||||
total_words += count_words(p)
|
||||
total_words += count_words(p)
|
||||
|
||||
total_files = sum(len(v) for v in files.values())
|
||||
needs_graph = total_words >= CORPUS_WARN_THRESHOLD
|
||||
@@ -420,7 +210,6 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
"needs_graph": needs_graph,
|
||||
"warning": warning,
|
||||
"skipped_sensitive": skipped_sensitive,
|
||||
"graphifyignore_patterns": len(ignore_patterns),
|
||||
}
|
||||
|
||||
|
||||
@@ -477,14 +266,9 @@ def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
|
||||
else:
|
||||
unchanged_files[ftype].append(f)
|
||||
|
||||
# Files in manifest that no longer exist - their cached nodes are now ghost nodes
|
||||
current_files = {f for flist in full["files"].values() for f in flist}
|
||||
deleted_files = [f for f in manifest if f not in current_files]
|
||||
|
||||
new_total = sum(len(v) for v in new_files.values())
|
||||
full["incremental"] = True
|
||||
full["new_files"] = new_files
|
||||
full["unchanged_files"] = unchanged_files
|
||||
full["new_total"] = new_total
|
||||
full["deleted_files"] = deleted_files
|
||||
return full
|
||||
+27
-65
@@ -1,6 +1,5 @@
|
||||
# write graph to HTML, JSON, SVG, GraphML, Obsidian vault, and Neo4j Cypher
|
||||
from __future__ import annotations
|
||||
import html as _html
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
@@ -9,7 +8,6 @@ from pathlib import Path
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
from graphify.security import sanitize_label
|
||||
from graphify.analyze import _node_community_map
|
||||
|
||||
COMMUNITY_COLORS = [
|
||||
"#4E79A7", "#F28E2B", "#E15759", "#76B7B2", "#59A14F",
|
||||
@@ -19,6 +17,11 @@ COMMUNITY_COLORS = [
|
||||
MAX_NODES_FOR_VIZ = 5_000
|
||||
|
||||
|
||||
def _node_community_map(communities: dict[int, list[str]]) -> dict[str, int]:
|
||||
"""Invert communities dict: node_id -> community_id."""
|
||||
return {n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
|
||||
|
||||
def _html_styles() -> str:
|
||||
return """<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
@@ -110,11 +113,6 @@ const RAW_NODES = {nodes_json};
|
||||
const RAW_EDGES = {edges_json};
|
||||
const LEGEND = {legend_json};
|
||||
|
||||
// HTML-escape helper — prevents XSS when injecting graph data into innerHTML
|
||||
function esc(s) {{
|
||||
return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''');
|
||||
}}
|
||||
|
||||
// Build vis datasets
|
||||
const nodesDS = new vis.DataSet(RAW_NODES.map(n => ({{
|
||||
id: n.id, label: n.label, color: n.color, size: n.size,
|
||||
@@ -170,13 +168,13 @@ function showInfo(nodeId) {{
|
||||
const neighborItems = neighborIds.map(nid => {{
|
||||
const nb = nodesDS.get(nid);
|
||||
const color = nb ? nb.color.background : '#555';
|
||||
return `<span class="neighbor-link" style="border-left-color:${{esc(color)}}" onclick="focusNode(${{JSON.stringify(nid)}})">${{esc(nb ? nb.label : nid)}}</span>`;
|
||||
return `<span class="neighbor-link" style="border-left-color:${{color}}" onclick="focusNode('${{nid}}')">${{nb ? nb.label : nid}}</span>`;
|
||||
}}).join('');
|
||||
document.getElementById('info-content').innerHTML = `
|
||||
<div class="field"><b>${{esc(n.label)}}</b></div>
|
||||
<div class="field">Type: ${{esc(n._file_type || 'unknown')}}</div>
|
||||
<div class="field">Community: ${{esc(n._community_name)}}</div>
|
||||
<div class="field">Source: ${{esc(n._source_file || '-')}}</div>
|
||||
<div class="field"><b>${{n.label}}</b></div>
|
||||
<div class="field">Type: ${{n._file_type || 'unknown'}}</div>
|
||||
<div class="field">Community: ${{n._community_name}}</div>
|
||||
<div class="field">Source: ${{n._source_file || '-'}}</div>
|
||||
<div class="field">Degree: ${{n._degree}}</div>
|
||||
${{neighborIds.length ? `<div class="field" style="margin-top:8px;color:#aaa;font-size:11px">Neighbors (${{neighborIds.length}})</div><div id="neighbors-list">${{neighborItems}}</div>` : ''}}
|
||||
`;
|
||||
@@ -188,28 +186,9 @@ function focusNode(nodeId) {{
|
||||
showInfo(nodeId);
|
||||
}}
|
||||
|
||||
// Track hovered node — hover detection is more reliable than click params
|
||||
let hoveredNodeId = null;
|
||||
network.on('hoverNode', params => {{
|
||||
hoveredNodeId = params.node;
|
||||
container.style.cursor = 'pointer';
|
||||
}});
|
||||
network.on('blurNode', () => {{
|
||||
hoveredNodeId = null;
|
||||
container.style.cursor = 'default';
|
||||
}});
|
||||
container.addEventListener('click', () => {{
|
||||
if (hoveredNodeId !== null) {{
|
||||
showInfo(hoveredNodeId);
|
||||
network.selectNodes([hoveredNodeId]);
|
||||
}}
|
||||
}});
|
||||
network.on('click', params => {{
|
||||
if (params.nodes.length > 0) {{
|
||||
showInfo(params.nodes[0]);
|
||||
}} else if (hoveredNodeId === null) {{
|
||||
document.getElementById('info-content').innerHTML = '<span class="empty">Click a node to inspect it</span>';
|
||||
}}
|
||||
if (params.nodes.length > 0) showInfo(params.nodes[0]);
|
||||
else document.getElementById('info-content').innerHTML = '<span class="empty">Click a node to inspect it</span>';
|
||||
}});
|
||||
|
||||
const searchInput = document.getElementById('search');
|
||||
@@ -284,10 +263,7 @@ def attach_hyperedges(G: nx.Graph, hyperedges: list) -> None:
|
||||
|
||||
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) -> None:
|
||||
node_community = _node_community_map(communities)
|
||||
try:
|
||||
data = json_graph.node_link_data(G, edges="links")
|
||||
except TypeError:
|
||||
data = json_graph.node_link_data(G)
|
||||
data = json_graph.node_link_data(G, edges="links")
|
||||
for node in data["nodes"]:
|
||||
node["community"] = node_community.get(node["id"])
|
||||
for link in data["links"]:
|
||||
@@ -299,27 +275,18 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) ->
|
||||
json.dump(data, f, indent=2)
|
||||
|
||||
|
||||
def _cypher_escape(s: str) -> str:
|
||||
"""Escape a string for safe embedding in a Cypher single-quoted literal."""
|
||||
return s.replace("\\", "\\\\").replace("'", "\\'")
|
||||
|
||||
|
||||
def to_cypher(G: nx.Graph, output_path: str) -> None:
|
||||
lines = ["// Neo4j Cypher import - generated by /graphify", ""]
|
||||
for node_id, data in G.nodes(data=True):
|
||||
label = _cypher_escape(data.get("label", node_id))
|
||||
node_id_esc = _cypher_escape(node_id)
|
||||
_ft = re.sub(r"[^A-Za-z0-9_]", "", data.get("file_type", "unknown").capitalize())
|
||||
ftype = (_ft if _ft and _ft[0].isalpha() else "Entity")
|
||||
lines.append(f"MERGE (n:{ftype} {{id: '{node_id_esc}', label: '{label}'}});")
|
||||
label = data.get("label", node_id).replace("'", "\\'")
|
||||
ftype = data.get("file_type", "unknown").capitalize()
|
||||
lines.append(f"MERGE (n:{ftype} {{id: '{node_id}', label: '{label}'}});")
|
||||
lines.append("")
|
||||
for u, v, data in G.edges(data=True):
|
||||
rel = re.sub(r"[^A-Za-z0-9_]", "_", data.get("relation", "RELATES_TO").upper())
|
||||
conf = _cypher_escape(data.get("confidence", "EXTRACTED"))
|
||||
u_esc = _cypher_escape(u)
|
||||
v_esc = _cypher_escape(v)
|
||||
rel = data.get("relation", "RELATES_TO").upper().replace(" ", "_").replace("-", "_")
|
||||
conf = data.get("confidence", "EXTRACTED")
|
||||
lines.append(
|
||||
f"MATCH (a {{id: '{u_esc}'}}), (b {{id: '{v_esc}'}}) "
|
||||
f"MATCH (a {{id: '{u}'}}), (b {{id: '{v}'}}) "
|
||||
f"MERGE (a)-[:{rel} {{confidence: '{conf}'}}]->(b);"
|
||||
)
|
||||
with open(output_path, "w") as f:
|
||||
@@ -364,9 +331,9 @@ def to_html(
|
||||
"color": {"background": color, "border": color, "highlight": {"background": "#ffffff", "border": color}},
|
||||
"size": round(size, 1),
|
||||
"font": {"size": font_size, "color": "#ffffff"},
|
||||
"title": _html.escape(label),
|
||||
"title": f"{label}",
|
||||
"community": cid,
|
||||
"community_name": sanitize_label((community_labels or {}).get(cid, f"Community {cid}")),
|
||||
"community_name": (community_labels or {}).get(cid, f"Community {cid}"),
|
||||
"source_file": sanitize_label(data.get("source_file", "")),
|
||||
"file_type": data.get("file_type", ""),
|
||||
"degree": deg,
|
||||
@@ -381,7 +348,7 @@ def to_html(
|
||||
"from": u,
|
||||
"to": v,
|
||||
"label": relation,
|
||||
"title": _html.escape(f"{relation} [{confidence}]"),
|
||||
"title": f"{relation} [{confidence}]",
|
||||
"dashes": confidence != "EXTRACTED",
|
||||
"width": 2 if confidence == "EXTRACTED" else 1,
|
||||
"color": {"opacity": 0.7 if confidence == "EXTRACTED" else 0.35},
|
||||
@@ -392,7 +359,7 @@ def to_html(
|
||||
legend_data = []
|
||||
for cid in sorted((community_labels or {}).keys()):
|
||||
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
|
||||
lbl = _html.escape(sanitize_label((community_labels or {}).get(cid, f"Community {cid}")))
|
||||
lbl = (community_labels or {}).get(cid, f"Community {cid}")
|
||||
n = len(communities.get(cid, []))
|
||||
legend_data.append({"cid": cid, "color": color, "label": lbl, "count": n})
|
||||
|
||||
@@ -400,7 +367,7 @@ def to_html(
|
||||
edges_json = json.dumps(vis_edges)
|
||||
legend_json = json.dumps(legend_data)
|
||||
hyperedges_json = json.dumps(getattr(G, "graph", {}).get("hyperedges", []))
|
||||
title = _html.escape(sanitize_label(str(output_path)))
|
||||
title = sanitize_label(str(output_path))
|
||||
stats = f"{G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(communities)} communities"
|
||||
|
||||
html = f"""<!DOCTYPE html>
|
||||
@@ -463,7 +430,7 @@ 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"
|
||||
return re.sub(r'[\\/*?:"<>|#^[\]]', "", label).strip() or "unnamed"
|
||||
|
||||
node_filename: dict[str, str] = {}
|
||||
seen_names: dict[str, int] = {}
|
||||
@@ -699,7 +666,7 @@ 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"
|
||||
return re.sub(r'[\\/*?:"<>|#^[\]]', "", label).strip() or "unnamed"
|
||||
|
||||
# Build node_filenames if not provided (same dedup logic as to_obsidian)
|
||||
if node_filenames is None:
|
||||
@@ -865,11 +832,6 @@ def push_to_neo4j(
|
||||
def _safe_rel(relation: str) -> str:
|
||||
return re.sub(r"[^A-Z0-9_]", "_", relation.upper().replace(" ", "_").replace("-", "_")) or "RELATED_TO"
|
||||
|
||||
def _safe_label(label: str) -> str:
|
||||
"""Sanitize a Neo4j node label to prevent Cypher injection."""
|
||||
sanitized = re.sub(r"[^A-Za-z0-9_]", "", label)
|
||||
return sanitized if sanitized else "Entity"
|
||||
|
||||
driver = GraphDatabase.driver(uri, auth=(user, password))
|
||||
nodes_pushed = 0
|
||||
edges_pushed = 0
|
||||
@@ -881,7 +843,7 @@ def push_to_neo4j(
|
||||
cid = node_community.get(node_id)
|
||||
if cid is not None:
|
||||
props["community"] = cid
|
||||
ftype = _safe_label(data.get("file_type", "Entity").capitalize())
|
||||
ftype = data.get("file_type", "Entity").capitalize()
|
||||
session.run(
|
||||
f"MERGE (n:{ftype} {{id: $id}}) SET n += $props",
|
||||
id=node_id,
|
||||
|
||||
+1662
-1855
File diff suppressed because it is too large.
Load diff
+18
-51
@@ -1,37 +1,13 @@
|
||||
# git hook integration - install/uninstall graphify post-commit and post-checkout hooks
|
||||
from __future__ import annotations
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
_HOOK_MARKER = "# graphify-hook-start"
|
||||
_HOOK_MARKER_END = "# graphify-hook-end"
|
||||
_CHECKOUT_MARKER = "# graphify-checkout-hook-start"
|
||||
_CHECKOUT_MARKER_END = "# graphify-checkout-hook-end"
|
||||
|
||||
_PYTHON_DETECT = """\
|
||||
# Detect the correct Python interpreter (handles pipx, venv, system installs)
|
||||
GRAPHIFY_BIN=$(command -v graphify 2>/dev/null)
|
||||
if [ -n "$GRAPHIFY_BIN" ]; then
|
||||
_SHEBANG=$(head -1 "$GRAPHIFY_BIN" | sed 's/^#![[:space:]]*//')
|
||||
case "$_SHEBANG" in
|
||||
*/env\\ *) GRAPHIFY_PYTHON="${_SHEBANG#*/env }" ;;
|
||||
*) GRAPHIFY_PYTHON="$_SHEBANG" ;;
|
||||
esac
|
||||
# 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" ;;
|
||||
esac
|
||||
if ! "$GRAPHIFY_PYTHON" -c "import graphify" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON="python3"
|
||||
fi
|
||||
else
|
||||
GRAPHIFY_PYTHON="python3"
|
||||
fi
|
||||
"""
|
||||
_HOOK_MARKER = "# graphify-hook"
|
||||
_CHECKOUT_MARKER = "# graphify-checkout-hook"
|
||||
|
||||
_HOOK_SCRIPT = """\
|
||||
# graphify-hook-start
|
||||
#!/bin/bash
|
||||
# graphify-hook
|
||||
# Auto-rebuilds the knowledge graph after each commit (code files only, no LLM needed).
|
||||
# Installed by: graphify hook install
|
||||
|
||||
@@ -40,9 +16,8 @@ if [ -z "$CHANGED" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
""" + _PYTHON_DETECT + """
|
||||
export GRAPHIFY_CHANGED="$CHANGED"
|
||||
$GRAPHIFY_PYTHON -c "
|
||||
python3 -c "
|
||||
import os, sys
|
||||
from pathlib import Path
|
||||
|
||||
@@ -65,14 +40,14 @@ try:
|
||||
_rebuild_code(Path('.'))
|
||||
except Exception as exc:
|
||||
print(f'[graphify hook] Rebuild failed: {exc}')
|
||||
sys.exit(1)
|
||||
sys.exit(0)
|
||||
"
|
||||
# graphify-hook-end
|
||||
"""
|
||||
|
||||
|
||||
_CHECKOUT_SCRIPT = """\
|
||||
# graphify-checkout-hook-start
|
||||
#!/bin/bash
|
||||
# graphify-checkout-hook
|
||||
# Auto-rebuilds the knowledge graph (code only) when switching branches.
|
||||
# Installed by: graphify hook install
|
||||
|
||||
@@ -90,19 +65,15 @@ if [ ! -d "graphify-out" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
""" + _PYTHON_DETECT + """
|
||||
echo "[graphify] Branch switched - rebuilding knowledge graph (code files)..."
|
||||
$GRAPHIFY_PYTHON -c "
|
||||
python3 -c "
|
||||
from graphify.watch import _rebuild_code
|
||||
from pathlib import Path
|
||||
import sys
|
||||
try:
|
||||
_rebuild_code(Path('.'))
|
||||
except Exception as exc:
|
||||
print(f'[graphify] Rebuild failed: {exc}')
|
||||
sys.exit(1)
|
||||
"
|
||||
# graphify-checkout-hook-end
|
||||
"""
|
||||
|
||||
|
||||
@@ -124,29 +95,25 @@ def _install_hook(hooks_dir: Path, name: str, script: str, marker: str) -> str:
|
||||
return f"already installed at {hook_path}"
|
||||
hook_path.write_text(content.rstrip() + "\n\n" + script)
|
||||
return f"appended to existing {name} hook at {hook_path}"
|
||||
hook_path.write_text("#!/bin/sh\n" + script)
|
||||
hook_path.write_text(script)
|
||||
hook_path.chmod(0o755)
|
||||
return f"installed at {hook_path}"
|
||||
|
||||
|
||||
def _uninstall_hook(hooks_dir: Path, name: str, marker: str, marker_end: str) -> str:
|
||||
"""Remove graphify section from a git hook using start/end markers."""
|
||||
def _uninstall_hook(hooks_dir: Path, name: str, marker: str) -> str:
|
||||
"""Remove graphify section from a git hook."""
|
||||
hook_path = hooks_dir / name
|
||||
if not hook_path.exists():
|
||||
return f"no {name} hook found - nothing to remove."
|
||||
content = hook_path.read_text()
|
||||
if marker not in content:
|
||||
return f"graphify hook not found in {name} - nothing to remove."
|
||||
new_content = re.sub(
|
||||
rf"{re.escape(marker)}.*?{re.escape(marker_end)}\n?",
|
||||
"",
|
||||
content,
|
||||
flags=re.DOTALL,
|
||||
).strip()
|
||||
if not new_content or new_content in ("#!/bin/bash", "#!/bin/sh"):
|
||||
before = content.split(marker)[0].rstrip()
|
||||
non_empty = [l for l in before.splitlines() if l.strip() and not l.startswith("#!")]
|
||||
if not non_empty:
|
||||
hook_path.unlink()
|
||||
return f"removed {name} hook at {hook_path}"
|
||||
hook_path.write_text(new_content + "\n")
|
||||
hook_path.write_text(before + "\n")
|
||||
return f"graphify removed from {name} at {hook_path} (other hook content preserved)"
|
||||
|
||||
|
||||
@@ -172,8 +139,8 @@ def uninstall(path: Path = Path(".")) -> str:
|
||||
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
|
||||
|
||||
hooks_dir = root / ".git" / "hooks"
|
||||
commit_msg = _uninstall_hook(hooks_dir, "post-commit", _HOOK_MARKER, _HOOK_MARKER_END)
|
||||
checkout_msg = _uninstall_hook(hooks_dir, "post-checkout", _CHECKOUT_MARKER, _CHECKOUT_MARKER_END)
|
||||
commit_msg = _uninstall_hook(hooks_dir, "post-commit", _HOOK_MARKER)
|
||||
checkout_msg = _uninstall_hook(hooks_dir, "post-checkout", _CHECKOUT_MARKER)
|
||||
|
||||
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
|
||||
|
||||
|
||||
+5
-14
@@ -10,11 +10,6 @@ from pathlib import Path
|
||||
from graphify.security import safe_fetch, safe_fetch_text, validate_url
|
||||
|
||||
|
||||
def _yaml_str(s: str) -> str:
|
||||
"""Escape a string for embedding in a YAML double-quoted scalar."""
|
||||
return s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
|
||||
|
||||
|
||||
def _safe_filename(url: str, suffix: str) -> str:
|
||||
"""Turn a URL into a safe filename."""
|
||||
parsed = urllib.parse.urlparse(url)
|
||||
@@ -72,7 +67,9 @@ def _fetch_tweet(url: str, author: str | None, contributor: str | None) -> tuple
|
||||
oembed_url = url.replace("x.com", "twitter.com")
|
||||
oembed_api = f"https://publish.twitter.com/oembed?url={urllib.parse.quote(oembed_url)}&omit_script=true"
|
||||
try:
|
||||
data = json.loads(safe_fetch_text(oembed_api))
|
||||
req = urllib.request.Request(oembed_api, headers={"User-Agent": "graphify/1.0"})
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
data = json.loads(resp.read())
|
||||
tweet_text = re.sub(r"<[^>]+>", "", data.get("html", "")).strip()
|
||||
tweet_author = data.get("author_name", "unknown")
|
||||
except Exception:
|
||||
@@ -111,7 +108,7 @@ def _fetch_webpage(url: str, author: str | None, contributor: str | None) -> tup
|
||||
content = f"""---
|
||||
source_url: {url}
|
||||
type: webpage
|
||||
title: "{_yaml_str(title)}"
|
||||
title: "{title}"
|
||||
captured_at: {now}
|
||||
contributor: {contributor or author or 'unknown'}
|
||||
---
|
||||
@@ -207,12 +204,6 @@ def ingest(url: str, target_dir: Path, author: str | None = None, contributor: s
|
||||
print(f"Downloaded image: {out.name}")
|
||||
return out
|
||||
|
||||
if url_type == "youtube":
|
||||
from graphify.transcribe import download_audio
|
||||
out = download_audio(url, target_dir)
|
||||
print(f"Downloaded audio: {out.name}")
|
||||
return out
|
||||
|
||||
if url_type == "tweet":
|
||||
content, filename = _fetch_tweet(url, author, contributor)
|
||||
elif url_type == "arxiv":
|
||||
@@ -259,7 +250,7 @@ def save_query_result(
|
||||
"---",
|
||||
f'type: "{query_type}"',
|
||||
f'date: "{now.isoformat()}"',
|
||||
f'question: "{_yaml_str(question)}"',
|
||||
f'question: "{re.sub(chr(10) + chr(13), " ", question).replace(chr(34), chr(39))}"',
|
||||
'contributor: "graphify"',
|
||||
]
|
||||
if source_nodes:
|
||||
|
||||
+7
-38
@@ -8,28 +8,20 @@ import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
import ipaddress
|
||||
import socket
|
||||
|
||||
_ALLOWED_SCHEMES = {"http", "https"}
|
||||
_MAX_FETCH_BYTES = 52_428_800 # 50 MB hard cap for binary downloads
|
||||
_MAX_TEXT_BYTES = 10_485_760 # 10 MB hard cap for HTML / text
|
||||
|
||||
# AWS metadata, link-local, and common cloud metadata endpoints
|
||||
_BLOCKED_HOSTS = {"metadata.google.internal", "metadata.google.com"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# URL validation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def validate_url(url: str) -> str:
|
||||
"""Raise ValueError if *url* is not http or https, or targets a private/internal IP.
|
||||
"""Raise ValueError if *url* is not http or https.
|
||||
|
||||
Blocks file://, ftp://, data:, and any other scheme that could be used
|
||||
for SSRF or local file access. Also blocks requests to private/reserved
|
||||
IP ranges (127.x, 10.x, 169.254.x, etc.) and cloud metadata endpoints
|
||||
to prevent SSRF in cloud environments.
|
||||
for SSRF or local file access.
|
||||
"""
|
||||
parsed = urllib.parse.urlparse(url)
|
||||
if parsed.scheme.lower() not in _ALLOWED_SCHEMES:
|
||||
@@ -37,30 +29,6 @@ def validate_url(url: str) -> str:
|
||||
f"Blocked URL scheme '{parsed.scheme}' - only http and https are allowed. "
|
||||
f"Got: {url!r}"
|
||||
)
|
||||
|
||||
hostname = parsed.hostname
|
||||
if hostname:
|
||||
# Block known cloud metadata hostnames
|
||||
if hostname.lower() in _BLOCKED_HOSTS:
|
||||
raise ValueError(
|
||||
f"Blocked cloud metadata endpoint '{hostname}'. "
|
||||
f"Got: {url!r}"
|
||||
)
|
||||
|
||||
# Resolve hostname and block private/reserved IP ranges
|
||||
try:
|
||||
infos = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM)
|
||||
for info in infos:
|
||||
addr = info[4][0]
|
||||
ip = ipaddress.ip_address(addr)
|
||||
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local:
|
||||
raise ValueError(
|
||||
f"Blocked private/internal IP {addr} (resolved from '{hostname}'). "
|
||||
f"Got: {url!r}"
|
||||
)
|
||||
except socket.gaierror:
|
||||
pass # DNS failure will surface later during fetch
|
||||
|
||||
return url
|
||||
|
||||
|
||||
@@ -186,12 +154,13 @@ _MAX_LABEL_LEN = 256
|
||||
|
||||
|
||||
def sanitize_label(text: str) -> str:
|
||||
"""Strip control characters and cap length.
|
||||
"""Strip control characters, cap length, then HTML-escape.
|
||||
|
||||
Safe for embedding in JSON data (inside <script> tags) and plain text.
|
||||
For direct HTML injection, wrap the result with html.escape().
|
||||
Applied to all node labels and edge titles before they are embedded
|
||||
in pyvis HTML output or returned via the MCP server, preventing both
|
||||
XSS and broken visualisations from malformed source identifiers.
|
||||
"""
|
||||
text = _CONTROL_CHAR_RE.sub("", text)
|
||||
if len(text) > _MAX_LABEL_LEN:
|
||||
text = text[:_MAX_LABEL_LEN]
|
||||
return text
|
||||
return html.escape(text)
|
||||
+6
-17
@@ -5,22 +5,14 @@ import sys
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
from graphify.security import sanitize_label
|
||||
from graphify.security import validate_graph_path, sanitize_label
|
||||
|
||||
|
||||
def _load_graph(graph_path: str) -> nx.Graph:
|
||||
try:
|
||||
resolved = Path(graph_path).resolve()
|
||||
if resolved.suffix != ".json":
|
||||
raise ValueError(f"Graph path must be a .json file, got: {graph_path!r}")
|
||||
if not resolved.exists():
|
||||
raise FileNotFoundError(f"Graph file not found: {resolved}")
|
||||
safe = resolved
|
||||
safe = validate_graph_path(graph_path)
|
||||
data = json.loads(safe.read_text())
|
||||
try:
|
||||
return json_graph.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
return json_graph.node_link_graph(data)
|
||||
return json_graph.node_link_graph(data, edges="links")
|
||||
except (ValueError, FileNotFoundError) as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -83,8 +75,8 @@ def _dfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], lis
|
||||
|
||||
|
||||
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000) -> str:
|
||||
"""Render subgraph as text, cutting at token_budget (approx 3 chars/token)."""
|
||||
char_budget = token_budget * 3
|
||||
"""Render subgraph as text, cutting at token_budget (approx 4 chars/token)."""
|
||||
char_budget = token_budget * 4
|
||||
lines = []
|
||||
for nid in sorted(nodes, key=lambda n: G.degree(n), reverse=True):
|
||||
d = G.nodes[nid]
|
||||
@@ -314,10 +306,7 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
|
||||
handler = _handlers.get(name)
|
||||
if not handler:
|
||||
return [types.TextContent(type="text", text=f"Unknown tool: {name}")]
|
||||
try:
|
||||
return [types.TextContent(type="text", text=handler(arguments))]
|
||||
except Exception as exc:
|
||||
return [types.TextContent(type="text", text=f"Error executing {name}: {exc}")]
|
||||
return [types.TextContent(type="text", text=handler(arguments))]
|
||||
|
||||
import asyncio
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+130
-188
@@ -15,8 +15,6 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <path> # full pipeline on specific path
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
/graphify <path> --no-viz # skip visualization, just report + JSON
|
||||
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
|
||||
@@ -26,8 +24,6 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
|
||||
/graphify <path> --mcp # start MCP stdio server for agent access
|
||||
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
|
||||
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
|
||||
/graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
|
||||
/graphify add <url> # fetch URL, save to ./raw, update graph
|
||||
/graphify add <url> --author "Name" # tag who wrote it
|
||||
/graphify add <url> --contributor "Name" # tag who added it to the corpus
|
||||
@@ -66,32 +62,28 @@ Follow these steps in order. Do not skip steps.
|
||||
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
|
||||
if [ -n "$GRAPHIFY_BIN" ]; then
|
||||
PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
|
||||
case "$PYTHON" in
|
||||
*[!a-zA-Z0-9/_.-]*) PYTHON="python3" ;;
|
||||
esac
|
||||
else
|
||||
PYTHON="python3"
|
||||
fi
|
||||
"$PYTHON" -c "import graphify" 2>/dev/null || "$PYTHON" -m pip install graphifyy -q 2>/dev/null || "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
# Write interpreter path for all subsequent steps (persists across invocations)
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
$PYTHON -c "import graphify" 2>/dev/null || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
# Write interpreter path for all subsequent steps
|
||||
$PYTHON -c "import sys; open('.graphify_python', 'w').write(sys.executable)"
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
|
||||
**In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
|
||||
**In every subsequent bash block, replace `python3` with `$(cat .graphify_python)` to use the correct interpreter.**
|
||||
|
||||
### Step 2 - Detect files
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
result = detect(Path('INPUT_PATH'))
|
||||
print(json.dumps(result))
|
||||
" > graphify-out/.graphify_detect.json
|
||||
" > .graphify_detect.json
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
@@ -102,61 +94,13 @@ Corpus: X files · ~Y words
|
||||
docs: N files (.md .txt ...)
|
||||
papers: N files (.pdf ...)
|
||||
images: N files
|
||||
video: N files (.mp4 .mp3 ...)
|
||||
```
|
||||
|
||||
Omit any category with 0 files from the summary.
|
||||
|
||||
Then act on it:
|
||||
- If `total_files` is 0: stop with "No supported files found in [path]."
|
||||
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
|
||||
- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.
|
||||
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
|
||||
|
||||
### Step 2.5 - Transcribe video / audio files (only if video files detected)
|
||||
|
||||
Skip this step entirely if `detect` returned zero `video` files.
|
||||
|
||||
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
|
||||
|
||||
**Strategy:** Read the god nodes from `graphify-out/.graphify_detect.json` (or the analysis file if it exists from a previous run). You are already a language model — write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
|
||||
|
||||
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
|
||||
|
||||
**Step 1 - Write the Whisper prompt yourself.**
|
||||
|
||||
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
|
||||
|
||||
- Labels: `transformer, attention, encoder, decoder` → `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
|
||||
- Labels: `kubernetes, deployment, pod, helm` → `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
|
||||
|
||||
Set it as `WHISPER_PROMPT` to use in the next command.
|
||||
|
||||
**Step 2 - Transcribe:**
|
||||
|
||||
```bash
|
||||
GRAPHIFY_WHISPER_MODEL=base # or whatever --whisper-model the user passed
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, os
|
||||
from pathlib import Path
|
||||
from graphify.transcribe import transcribe_all
|
||||
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
video_files = detect.get('files', {}).get('video', [])
|
||||
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
|
||||
|
||||
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
|
||||
print(json.dumps(transcript_paths))
|
||||
" > graphify-out/.graphify_transcripts.json
|
||||
```
|
||||
|
||||
After transcription:
|
||||
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
|
||||
- Add them to the docs list before dispatching semantic subagents in Step 3B
|
||||
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
|
||||
- If transcription fails for a file, print a warning and continue with the rest
|
||||
|
||||
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, set `GRAPHIFY_WHISPER_MODEL=<name>` in the environment before running the command above.
|
||||
- Otherwise: proceed directly to Step 3 - no need to ask anything.
|
||||
|
||||
### Step 3 - Extract entities and relationships
|
||||
|
||||
@@ -173,23 +117,23 @@ Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is determin
|
||||
For any code files detected, run AST extraction in parallel with Part B subagents:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.extract import collect_files, extract
|
||||
from pathlib import Path
|
||||
import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
if code_files:
|
||||
result = extract(code_files)
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2))
|
||||
Path('.graphify_ast.json').write_text(json.dumps(result, indent=2))
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
|
||||
Path('.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
|
||||
print('No code files - skipping AST extraction')
|
||||
"
|
||||
```
|
||||
@@ -201,7 +145,7 @@ else:
|
||||
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
|
||||
|
||||
Before dispatching subagents, print a timing estimate:
|
||||
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
|
||||
- Load `total_words` and file counts from `.graphify_detect.json`
|
||||
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
|
||||
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
|
||||
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
|
||||
@@ -211,28 +155,28 @@ Before dispatching subagents, print a timing estimate:
|
||||
Before dispatching any subagents, check which files already have cached extraction results:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from graphify.cache import check_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
all_files = [f for files in detect['files'].values() for f in files]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
|
||||
|
||||
if cached_nodes or cached_edges or cached_hyperedges:
|
||||
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
|
||||
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached))
|
||||
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
|
||||
Path('.graphify_uncached.txt').write_text('\n'.join(uncached))
|
||||
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
|
||||
"
|
||||
```
|
||||
|
||||
Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
|
||||
Only dispatch subagents for files listed in `.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
|
||||
|
||||
**Step B1 - Split into chunks**
|
||||
|
||||
Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
|
||||
Load files from `.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context).
|
||||
|
||||
**Step B2 - Dispatch ALL subagents in a single message**
|
||||
|
||||
@@ -311,25 +255,25 @@ If more than half the chunks failed, stop and tell the user.
|
||||
|
||||
Save new results to cache:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from graphify.cache import save_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text()) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
|
||||
print(f'Cached {saved} files')
|
||||
"
|
||||
```
|
||||
|
||||
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
|
||||
Merge cached + new results into `.graphify_semantic.json`:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text()) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text()) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
cached = json.loads(Path('.graphify_cached.json').read_text()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
|
||||
all_nodes = cached['nodes'] + new.get('nodes', [])
|
||||
all_edges = cached['edges'] + new.get('edges', [])
|
||||
@@ -348,21 +292,21 @@ merged = {
|
||||
'input_tokens': new.get('input_tokens', 0),
|
||||
'output_tokens': new.get('output_tokens', 0),
|
||||
}
|
||||
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
|
||||
Path('.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
|
||||
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
|
||||
"
|
||||
```
|
||||
Clean up temp files: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json`
|
||||
Clean up temp files: `rm -f .graphify_cached.json .graphify_uncached.txt .graphify_semantic_new.json`
|
||||
|
||||
#### Part C - Merge AST + semantic into final extraction
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from pathlib import Path
|
||||
|
||||
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text())
|
||||
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text())
|
||||
ast = json.loads(Path('.graphify_ast.json').read_text())
|
||||
sem = json.loads(Path('.graphify_semantic.json').read_text())
|
||||
|
||||
# Merge: AST nodes first, semantic nodes deduplicated by id
|
||||
seen = {n['id'] for n in ast['nodes']}
|
||||
@@ -381,7 +325,7 @@ merged = {
|
||||
'input_tokens': sem.get('input_tokens', 0),
|
||||
'output_tokens': sem.get('output_tokens', 0),
|
||||
}
|
||||
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2))
|
||||
Path('.graphify_extract.json').write_text(json.dumps(merged, indent=2))
|
||||
total = len(merged_nodes)
|
||||
edges = len(merged_edges)
|
||||
print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
|
||||
@@ -390,11 +334,9 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** note whether `--directed` was given. If so, pass `directed=True` to `build_from_json()` in the code block below. This builds a `DiGraph` that preserves edge direction (source→target) instead of the default undirected `Graph`.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
@@ -403,8 +345,8 @@ from graphify.report import generate
|
||||
from graphify.export import to_json
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = cluster(G)
|
||||
@@ -427,7 +369,7 @@ analysis = {
|
||||
'surprises': surprises,
|
||||
'questions': questions,
|
||||
}
|
||||
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
if G.number_of_nodes() == 0:
|
||||
print('ERROR: Graph is empty - extraction produced no nodes.')
|
||||
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
|
||||
@@ -442,12 +384,12 @@ Replace INPUT_PATH with the actual path.
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
|
||||
Read `.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
|
||||
|
||||
Then regenerate the report and save the labels for the visualizer:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import score_all
|
||||
@@ -455,9 +397,9 @@ from graphify.analyze import god_nodes, surprising_connections, suggest_question
|
||||
from graphify.report import generate
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -472,7 +414,7 @@ questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
|
||||
Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
|
||||
print('Report updated with community labels')
|
||||
"
|
||||
```
|
||||
@@ -486,33 +428,29 @@ Replace INPUT_PATH with the actual path.
|
||||
|
||||
If `--obsidian` was given:
|
||||
|
||||
- If `--obsidian-dir <path>` was also given, use that path as the vault directory. Otherwise default to `graphify-out/obsidian`.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_obsidian, to_canvas
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
labels = {int(k): v for k, v in labels_raw.items()}
|
||||
|
||||
obsidian_dir = 'OBSIDIAN_DIR' # replace with --obsidian-dir value, or 'graphify-out/obsidian' if not given
|
||||
n = to_obsidian(G, communities, 'graphify-out/obsidian', community_labels=labels or None, cohesion=cohesion)
|
||||
print(f'Obsidian vault: {n} notes in graphify-out/obsidian/')
|
||||
|
||||
n = to_obsidian(G, communities, obsidian_dir, community_labels=labels or None, cohesion=cohesion)
|
||||
print(f'Obsidian vault: {n} notes in {obsidian_dir}/')
|
||||
|
||||
to_canvas(G, communities, f'{obsidian_dir}/graph.canvas', community_labels=labels or None)
|
||||
print(f'Canvas: {obsidian_dir}/graph.canvas - open in Obsidian for structured community layout')
|
||||
to_canvas(G, communities, 'graphify-out/obsidian/graph.canvas', community_labels=labels or None)
|
||||
print('Canvas: graphify-out/obsidian/graph.canvas - open in Obsidian for structured community layout')
|
||||
print()
|
||||
print(f'Open {obsidian_dir}/ as a vault in Obsidian.')
|
||||
print('Open graphify-out/obsidian/ as a vault in Obsidian.')
|
||||
print(' Graph view - nodes colored by community (set automatically)')
|
||||
print(' graph.canvas - structured layout with communities as groups')
|
||||
print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries')
|
||||
@@ -522,15 +460,15 @@ print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries
|
||||
Generate the HTML graph (always, unless `--no-viz`):
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_html
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -549,13 +487,13 @@ else:
|
||||
**If `--neo4j`** - generate a Cypher file for manual import:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_cypher
|
||||
from pathlib import Path
|
||||
|
||||
G = build_from_json(json.loads(Path('graphify-out/.graphify_extract.json').read_text()))
|
||||
G = build_from_json(json.loads(Path('.graphify_extract.json').read_text()))
|
||||
to_cypher(G, 'graphify-out/cypher.txt')
|
||||
print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt')
|
||||
"
|
||||
@@ -564,15 +502,15 @@ print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt'
|
||||
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster
|
||||
from graphify.export import push_to_neo4j
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
|
||||
@@ -586,15 +524,15 @@ Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default
|
||||
### Step 7b - SVG export (only if --svg flag)
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_svg
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -608,14 +546,14 @@ print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
|
||||
### Step 7c - GraphML export (only if --graphml flag)
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_graphml
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -647,15 +585,15 @@ To configure in Claude Desktop, add to `claude_desktop_config.json`:
|
||||
|
||||
### Step 8 - Token reduction benchmark (only if total_words > 5000)
|
||||
|
||||
If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run:
|
||||
If `total_words` from `.graphify_detect.json` is greater than 5,000, run:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from graphify.benchmark import run_benchmark, print_benchmark
|
||||
from pathlib import Path
|
||||
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
result = run_benchmark('graphify-out/graph.json', corpus_words=detection['total_words'])
|
||||
print_benchmark(result)
|
||||
"
|
||||
@@ -668,18 +606,18 @@ Print the output directly in chat. If `total_words <= 5000`, skip silently - the
|
||||
### Step 9 - Save manifest, update cost tracker, clean up, and report
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
from graphify.detect import save_manifest
|
||||
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
save_manifest(detect['files'])
|
||||
|
||||
# Update cumulative cost tracker
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
extract = json.loads(Path('.graphify_extract.json').read_text())
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
output_tok = extract.get('output_tokens', 0)
|
||||
|
||||
@@ -702,7 +640,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
|
||||
"
|
||||
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_labels.json
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_python
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -716,8 +654,6 @@ Graph complete. Outputs in PATH_TO_DIR/graphify-out/
|
||||
obsidian/ - Obsidian vault (only if --obsidian was given)
|
||||
```
|
||||
|
||||
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
|
||||
|
||||
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
|
||||
|
||||
Then paste these sections from GRAPH_REPORT.md directly into the chat:
|
||||
@@ -737,30 +673,12 @@ The graph is the map. Your job after the pipeline is to be the guide.
|
||||
|
||||
---
|
||||
|
||||
## Interpreter guard for subcommands
|
||||
|
||||
Before running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out/`), re-resolve the interpreter first:
|
||||
|
||||
```bash
|
||||
if [ ! -f graphify-out/.graphify_python ]; then
|
||||
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
|
||||
if [ -n "$GRAPHIFY_BIN" ]; then
|
||||
PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
|
||||
case "$PYTHON" in *[!a-zA-Z0-9/_.-]*) PYTHON="python3" ;; esac
|
||||
else
|
||||
PYTHON="python3"
|
||||
fi
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
fi
|
||||
```
|
||||
|
||||
## For --update (incremental re-extraction)
|
||||
|
||||
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.detect import detect_incremental, save_manifest
|
||||
from pathlib import Path
|
||||
@@ -768,7 +686,7 @@ from pathlib import Path
|
||||
result = detect_incremental(Path('INPUT_PATH'))
|
||||
new_total = result.get('new_total', 0)
|
||||
print(json.dumps(result, indent=2))
|
||||
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result))
|
||||
Path('.graphify_incremental.json').write_text(json.dumps(result))
|
||||
if new_total == 0:
|
||||
print('No files changed since last run. Nothing to update.')
|
||||
raise SystemExit(0)
|
||||
@@ -779,12 +697,12 @@ print(f'{new_total} new/changed file(s) to re-extract.')
|
||||
If new files exist, first check whether all changed files are code files:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
result = json.loads(open('graphify-out/.graphify_incremental.json').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {}
|
||||
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc'}
|
||||
result = json.loads(open('.graphify_incremental.json').read()) if Path('.graphify_incremental.json').exists() else {}
|
||||
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts'}
|
||||
new_files = result.get('new_files', {})
|
||||
all_changed = [f for files in new_files.values() for f in files]
|
||||
code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
|
||||
@@ -799,7 +717,7 @@ If `code_only` is False (any changed file is a doc/paper/image): run the full St
|
||||
Then:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_json
|
||||
@@ -812,17 +730,9 @@ existing_data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
G_existing = json_graph.node_link_graph(existing_data, edges='links')
|
||||
|
||||
# Load new extraction
|
||||
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
new_extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
G_new = build_from_json(new_extraction)
|
||||
|
||||
# Prune nodes from deleted files
|
||||
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text())
|
||||
deleted = set(incremental.get('deleted_files', []))
|
||||
if deleted:
|
||||
to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted]
|
||||
G_existing.remove_nodes_from(to_remove)
|
||||
print(f'Pruned {len(to_remove)} ghost nodes from {len(deleted)} deleted file(s)')
|
||||
|
||||
# Merge: new nodes/edges into existing graph
|
||||
G_existing.update(G_new)
|
||||
print(f'Merged: {G_existing.number_of_nodes()} nodes, {G_existing.number_of_edges()} edges')
|
||||
@@ -834,7 +744,7 @@ Then run Steps 4–8 on the merged graph as normal.
|
||||
After Step 4, show the graph diff:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from graphify.analyze import graph_diff
|
||||
from graphify.build import build_from_json
|
||||
@@ -843,8 +753,8 @@ import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
# Load old graph (before update) from backup written before merge
|
||||
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text()) if Path('graphify-out/.graphify_old.json').exists() else None
|
||||
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
old_data = json.loads(Path('.graphify_old.json').read_text()) if Path('.graphify_old.json').exists() else None
|
||||
new_extract = json.loads(Path('.graphify_extract.json').read_text())
|
||||
G_new = build_from_json(new_extract)
|
||||
|
||||
if old_data:
|
||||
@@ -858,8 +768,8 @@ if old_data:
|
||||
"
|
||||
```
|
||||
|
||||
Before the merge step, save the old graph: `cp graphify-out/graph.json graphify-out/.graphify_old.json`
|
||||
Clean up after: `rm -f graphify-out/.graphify_old.json`
|
||||
Before the merge step, save the old graph: `cp graphify-out/graph.json .graphify_old.json`
|
||||
Clean up after: `rm -f .graphify_old.json`
|
||||
|
||||
---
|
||||
|
||||
@@ -868,7 +778,7 @@ Clean up after: `rm -f graphify-out/.graphify_old.json`
|
||||
Skip Steps 1–3. Load the existing graph from `graphify-out/graph.json` and re-run clustering:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections
|
||||
@@ -901,7 +811,7 @@ analysis = {
|
||||
'gods': gods,
|
||||
'surprises': surprises,
|
||||
}
|
||||
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
print(f'Re-clustered: {len(communities)} communities')
|
||||
"
|
||||
```
|
||||
@@ -921,7 +831,7 @@ Two traversal modes - choose based on the question:
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -939,7 +849,7 @@ Load `graphify-out/graph.json`, then:
|
||||
5. If the graph lacks enough information, say so - do not hallucinate edges.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
@@ -1030,7 +940,18 @@ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`,
|
||||
After writing the answer, save it back into the graph so it improves future queries:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
|
||||
$(cat .graphify_python) -c "
|
||||
from graphify.ingest import save_query_result
|
||||
from pathlib import Path
|
||||
save_query_result(
|
||||
question='QUESTION',
|
||||
answer='ANSWER',
|
||||
memory_dir=Path('graphify-out/memory'),
|
||||
query_type='query',
|
||||
source_nodes=SOURCE_NODES, # list of node labels cited, or []
|
||||
)
|
||||
print('Query result saved to graphify-out/memory/')
|
||||
"
|
||||
```
|
||||
|
||||
Replace `QUESTION` with the question, `ANSWER` with your full answer text, `SOURCE_NODES` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
|
||||
@@ -1043,7 +964,7 @@ Find the shortest path between two named concepts in the graph.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -1053,7 +974,7 @@ if not Path('graphify-out/graph.json').exists():
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
@@ -1105,7 +1026,18 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
|
||||
$(cat .graphify_python) -c "
|
||||
from graphify.ingest import save_query_result
|
||||
from pathlib import Path
|
||||
save_query_result(
|
||||
question='Path from NODE_A to NODE_B',
|
||||
answer='ANSWER',
|
||||
memory_dir=Path('graphify-out/memory'),
|
||||
query_type='path_query',
|
||||
source_nodes=PATH_NODES, # list of node labels on the path
|
||||
)
|
||||
print('Path result saved to graphify-out/memory/')
|
||||
"
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1116,7 +1048,7 @@ Give a plain-language explanation of a single node - everything connected to it.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -1126,7 +1058,7 @@ if not Path('graphify-out/graph.json').exists():
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
@@ -1171,7 +1103,18 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
|
||||
$(cat .graphify_python) -c "
|
||||
from graphify.ingest import save_query_result
|
||||
from pathlib import Path
|
||||
save_query_result(
|
||||
question='Explain NODE_NAME',
|
||||
answer='ANSWER',
|
||||
memory_dir=Path('graphify-out/memory'),
|
||||
query_type='explain',
|
||||
source_nodes=['NODE_NAME'],
|
||||
)
|
||||
print('Explanation saved to graphify-out/memory/')
|
||||
"
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1181,7 +1124,7 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain
|
||||
Fetch a URL and add it to the corpus, then update the graph.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys
|
||||
from graphify.ingest import ingest
|
||||
from pathlib import Path
|
||||
@@ -1201,9 +1144,8 @@ except RuntimeError as e:
|
||||
Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph.
|
||||
|
||||
Supported URL types (auto-detected):
|
||||
- YouTube / any video URL → audio downloaded via yt-dlp, transcribed to `.txt` on next run (requires `pip install 'graphifyy[video]'`)
|
||||
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
|
||||
- arXiv → abstract + metadata saved as `.md`
|
||||
- arXiv → abstract + metadata saved as `.md`
|
||||
- PDF → downloaded as `.pdf`
|
||||
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
|
||||
- Any webpage → converted to markdown via html2text
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
# Video transcription using faster-whisper
|
||||
# Converts video/audio files to text transcripts for graph extraction
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
VIDEO_EXTENSIONS = {'.mp4', '.mov', '.webm', '.mkv', '.avi', '.m4v', '.mp3', '.wav', '.m4a', '.ogg'}
|
||||
URL_PREFIXES = ('http://', 'https://', 'www.')
|
||||
|
||||
_DEFAULT_MODEL = "base"
|
||||
_TRANSCRIPTS_DIR = "graphify-out/transcripts"
|
||||
_FALLBACK_PROMPT = "Use proper punctuation and paragraph breaks."
|
||||
|
||||
|
||||
def _model_name() -> str:
|
||||
return os.environ.get("GRAPHIFY_WHISPER_MODEL", _DEFAULT_MODEL)
|
||||
|
||||
|
||||
def _get_whisper():
|
||||
try:
|
||||
from faster_whisper import WhisperModel
|
||||
return WhisperModel
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Video transcription requires faster-whisper. "
|
||||
"Run: pip install 'graphifyy[video]'"
|
||||
) from exc
|
||||
|
||||
|
||||
def _get_yt_dlp():
|
||||
try:
|
||||
import yt_dlp
|
||||
return yt_dlp
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"YouTube/URL download requires yt-dlp. "
|
||||
"Run: pip install 'graphifyy[video]'"
|
||||
) from exc
|
||||
|
||||
|
||||
def is_url(path: str) -> bool:
|
||||
"""Return True if the string looks like a URL rather than a file path."""
|
||||
return any(path.startswith(p) for p in URL_PREFIXES)
|
||||
|
||||
|
||||
def download_audio(url: str, output_dir: Path) -> Path:
|
||||
"""Download audio-only stream from a URL using yt-dlp.
|
||||
|
||||
Returns the path to the downloaded audio file (.m4a or .opus).
|
||||
Uses cached file if already downloaded.
|
||||
"""
|
||||
yt_dlp = _get_yt_dlp()
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# yt-dlp uses %(title)s which can be long/weird — use a stable name based on URL hash
|
||||
import hashlib
|
||||
url_hash = hashlib.sha1(url.encode()).hexdigest()[:12]
|
||||
out_template = str(output_dir / f"yt_{url_hash}.%(ext)s")
|
||||
|
||||
# Check for already-downloaded file
|
||||
for ext in ('.m4a', '.opus', '.mp3', '.ogg', '.wav', '.webm'):
|
||||
candidate = output_dir / f"yt_{url_hash}{ext}"
|
||||
if candidate.exists():
|
||||
print(f" cached audio: {candidate.name}")
|
||||
return candidate
|
||||
|
||||
ydl_opts = {
|
||||
'format': 'bestaudio[ext=m4a]/bestaudio/best',
|
||||
'outtmpl': out_template,
|
||||
'quiet': True,
|
||||
'no_warnings': True,
|
||||
'noplaylist': True,
|
||||
'postprocessors': [], # no ffmpeg needed — use native audio
|
||||
}
|
||||
|
||||
print(f" downloading audio: {url[:80]} ...", flush=True)
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
||||
info = ydl.extract_info(url, download=True)
|
||||
ext = info.get('ext', 'm4a')
|
||||
downloaded = output_dir / f"yt_{url_hash}.{ext}"
|
||||
if not downloaded.exists():
|
||||
# yt-dlp may have picked a different extension
|
||||
for p in output_dir.glob(f"yt_{url_hash}.*"):
|
||||
downloaded = p
|
||||
break
|
||||
return downloaded
|
||||
|
||||
|
||||
def build_whisper_prompt(god_nodes: list[dict]) -> str:
|
||||
"""Build a domain hint for Whisper from god nodes extracted from the corpus.
|
||||
|
||||
Formats the top god node labels into a topic string for Whisper.
|
||||
The coding agent (Claude Code, Codex, etc.) generates the actual one-sentence
|
||||
domain hint from these labels and passes it via GRAPHIFY_WHISPER_PROMPT or
|
||||
as initial_prompt — no separate API call needed here.
|
||||
"""
|
||||
if not god_nodes:
|
||||
return _FALLBACK_PROMPT
|
||||
|
||||
override = os.environ.get("GRAPHIFY_WHISPER_PROMPT")
|
||||
if override:
|
||||
return override
|
||||
|
||||
labels = [n.get("label", "") for n in god_nodes[:10] if n.get("label")]
|
||||
if not labels:
|
||||
return _FALLBACK_PROMPT
|
||||
|
||||
topics = ", ".join(labels[:5])
|
||||
return f"Technical discussion about {topics}. Use proper punctuation and paragraph breaks."
|
||||
|
||||
|
||||
def transcribe(
|
||||
video_path: Path | str,
|
||||
output_dir: Path | None = None,
|
||||
initial_prompt: str | None = None,
|
||||
force: bool = False,
|
||||
) -> Path:
|
||||
"""Transcribe a video/audio file or URL to a .txt transcript.
|
||||
|
||||
If video_path is a URL, audio is downloaded first via yt-dlp.
|
||||
Returns the path to the saved transcript file.
|
||||
Uses cached transcript if it exists unless force=True.
|
||||
|
||||
initial_prompt: domain hint for Whisper (built from corpus god nodes).
|
||||
force: re-transcribe even if transcript already exists.
|
||||
"""
|
||||
out_dir = Path(output_dir) if output_dir else Path(_TRANSCRIPTS_DIR)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if is_url(str(video_path)):
|
||||
audio_path = download_audio(str(video_path), out_dir / "downloads")
|
||||
else:
|
||||
audio_path = Path(video_path)
|
||||
|
||||
transcript_path = out_dir / (audio_path.stem + ".txt")
|
||||
if transcript_path.exists() and not force:
|
||||
return transcript_path
|
||||
|
||||
WhisperModel = _get_whisper()
|
||||
model_name = _model_name()
|
||||
prompt = initial_prompt or _FALLBACK_PROMPT
|
||||
|
||||
print(f" transcribing {audio_path.name} (model={model_name}) ...", flush=True)
|
||||
model = WhisperModel(model_name, device="cpu", compute_type="int8")
|
||||
segments, info = model.transcribe(
|
||||
str(audio_path),
|
||||
beam_size=5,
|
||||
initial_prompt=prompt,
|
||||
)
|
||||
|
||||
lines = [segment.text.strip() for segment in segments if segment.text.strip()]
|
||||
transcript = "\n".join(lines)
|
||||
|
||||
transcript_path.write_text(transcript, encoding="utf-8")
|
||||
lang = info.language if hasattr(info, "language") else "unknown"
|
||||
print(f" transcript saved -> {transcript_path} (lang={lang}, {len(lines)} segments)")
|
||||
return transcript_path
|
||||
|
||||
|
||||
def transcribe_all(
|
||||
video_files: list[str],
|
||||
output_dir: Path | None = None,
|
||||
initial_prompt: str | None = None,
|
||||
) -> list[str]:
|
||||
"""Transcribe a list of video/audio files or URLs, return paths to transcript .txt files.
|
||||
|
||||
Already-transcribed files are returned from cache instantly.
|
||||
initial_prompt is shared across all files — built once from corpus god nodes.
|
||||
"""
|
||||
if not video_files:
|
||||
return []
|
||||
|
||||
transcript_paths = []
|
||||
for vf in video_files:
|
||||
try:
|
||||
t = transcribe(vf, output_dir, initial_prompt=initial_prompt)
|
||||
transcript_paths.append(str(t))
|
||||
except Exception as exc:
|
||||
print(f" warning: could not transcribe {vf}: {exc}")
|
||||
return transcript_paths
|
||||
@@ -1,7 +1,7 @@
|
||||
# validate extraction JSON against the graphify schema before graph assembly
|
||||
from __future__ import annotations
|
||||
|
||||
VALID_FILE_TYPES = {"code", "document", "paper", "image", "rationale"}
|
||||
VALID_FILE_TYPES = {"code", "document", "paper", "image"}
|
||||
VALID_CONFIDENCES = {"EXTRACTED", "INFERRED", "AMBIGUOUS"}
|
||||
REQUIRED_NODE_FIELDS = {"id", "label", "file_type", "source_file"}
|
||||
REQUIRED_EDGE_FIELDS = {"source", "target", "relation", "confidence", "source_file"}
|
||||
|
||||
+25
-11
@@ -5,28 +5,41 @@ import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
from graphify.detect import CODE_EXTENSIONS, DOC_EXTENSIONS, PAPER_EXTENSIONS, IMAGE_EXTENSIONS
|
||||
_WATCHED_EXTENSIONS = {
|
||||
".py", ".ts", ".js", ".go", ".rs", ".java", ".cpp", ".c", ".rb", ".swift", ".kt",
|
||||
".cs", ".scala", ".php", ".cc", ".cxx", ".hpp", ".h", ".kts",
|
||||
".md", ".txt", ".rst", ".pdf",
|
||||
".png", ".jpg", ".jpeg", ".webp", ".gif", ".svg",
|
||||
}
|
||||
|
||||
_WATCHED_EXTENSIONS = CODE_EXTENSIONS | DOC_EXTENSIONS | PAPER_EXTENSIONS | IMAGE_EXTENSIONS
|
||||
_CODE_EXTENSIONS = CODE_EXTENSIONS
|
||||
_CODE_EXTENSIONS = {
|
||||
".py", ".ts", ".js", ".go", ".rs", ".java", ".cpp", ".c", ".rb", ".swift", ".kt",
|
||||
".cs", ".scala", ".php", ".cc", ".cxx", ".hpp", ".h", ".kts",
|
||||
}
|
||||
|
||||
|
||||
def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
def _rebuild_code(watch_path: Path) -> bool:
|
||||
"""Re-run AST extraction + build + cluster + report for code files. No LLM needed.
|
||||
|
||||
Returns True on success, False on error.
|
||||
"""
|
||||
try:
|
||||
from graphify.extract import extract
|
||||
from graphify.detect import detect
|
||||
from graphify.extract import collect_files, extract
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
|
||||
from graphify.report import generate
|
||||
from graphify.export import to_json
|
||||
|
||||
detected = detect(watch_path, follow_symlinks=follow_symlinks)
|
||||
code_files = [Path(f) for f in detected['files']['code']]
|
||||
code_files = []
|
||||
for ext in _CODE_EXTENSIONS:
|
||||
code_files.extend(watch_path.rglob(f"*{ext}"))
|
||||
code_files = [
|
||||
f for f in code_files
|
||||
if not any(part.startswith(".") for part in f.parts)
|
||||
and "graphify-out" not in f.parts
|
||||
and "__pycache__" not in f.parts
|
||||
]
|
||||
|
||||
if not code_files:
|
||||
print("[graphify watch] No code files found - nothing to rebuild.")
|
||||
@@ -37,7 +50,7 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
detection = {
|
||||
"files": {"code": [str(f) for f in code_files], "document": [], "paper": [], "image": []},
|
||||
"total_files": len(code_files),
|
||||
"total_words": detected.get("total_words", 0),
|
||||
"total_words": sum(len(f.read_text(errors="ignore").split()) for f in code_files),
|
||||
}
|
||||
|
||||
G = build_from_json(result)
|
||||
@@ -105,7 +118,7 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
|
||||
|
||||
last_trigger: float = 0.0
|
||||
pending: bool = False
|
||||
changed: set[Path] = set()
|
||||
changed: list[Path] = []
|
||||
|
||||
class Handler(FileSystemEventHandler):
|
||||
def on_any_event(self, event):
|
||||
@@ -121,7 +134,8 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
|
||||
return
|
||||
last_trigger = time.monotonic()
|
||||
pending = True
|
||||
changed.add(path)
|
||||
if path not in changed:
|
||||
changed.append(path)
|
||||
|
||||
handler = Handler()
|
||||
observer = Observer()
|
||||
|
||||
+7
-16
@@ -4,15 +4,15 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "graphifyy"
|
||||
version = "0.3.29"
|
||||
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, OpenClaw, Factory Droid, Trae) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
|
||||
version = "0.2.2"
|
||||
description = "Claude Code skill - turn any folder of code, docs, papers, images, or tweets into a queryable knowledge graph"
|
||||
readme = "README.md"
|
||||
license = { file = "LICENSE" }
|
||||
keywords = ["claude", "claude-code", "codex", "opencode", "cursor", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
|
||||
license = { text = "MIT" }
|
||||
keywords = ["claude", "claude-code", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"networkx",
|
||||
"tree-sitter>=0.23.0",
|
||||
"tree-sitter",
|
||||
"tree-sitter-python",
|
||||
"tree-sitter-javascript",
|
||||
"tree-sitter-typescript",
|
||||
@@ -26,13 +26,6 @@ dependencies = [
|
||||
"tree-sitter-kotlin",
|
||||
"tree-sitter-scala",
|
||||
"tree-sitter-php",
|
||||
"tree-sitter-swift",
|
||||
"tree-sitter-lua",
|
||||
"tree-sitter-zig",
|
||||
"tree-sitter-powershell",
|
||||
"tree-sitter-elixir",
|
||||
"tree-sitter-objc",
|
||||
"tree-sitter-julia",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
@@ -46,9 +39,7 @@ neo4j = ["neo4j"]
|
||||
pdf = ["pypdf", "html2text"]
|
||||
watch = ["watchdog"]
|
||||
leiden = ["graspologic"]
|
||||
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"]
|
||||
|
||||
[project.scripts]
|
||||
graphify = "graphify.__main__:main"
|
||||
@@ -58,4 +49,4 @@ where = ["."]
|
||||
include = ["graphify*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-aider.md", "skill-copilot.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md"]
|
||||
graphify = ["skill.md"]
|
||||
@@ -58,30 +58,15 @@ Follow these steps in order. Do not skip steps.
|
||||
### Step 1 - Ensure graphify is installed
|
||||
|
||||
```bash
|
||||
# Detect the correct Python interpreter (handles pipx, venv, system installs)
|
||||
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
|
||||
if [ -n "$GRAPHIFY_BIN" ]; then
|
||||
PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
|
||||
case "$PYTHON" in
|
||||
*[!a-zA-Z0-9/_.-]*) PYTHON="python3" ;;
|
||||
esac
|
||||
else
|
||||
PYTHON="python3"
|
||||
fi
|
||||
"$PYTHON" -c "import graphify" 2>/dev/null || "$PYTHON" -m pip install graphifyy -q 2>/dev/null || "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
# Write interpreter path for all subsequent steps
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
python3 -c "import graphify" 2>/dev/null || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
|
||||
**In every subsequent bash block, replace `python3` with `$(cat .graphify_python)` to use the correct interpreter.**
|
||||
|
||||
### Step 2 - Detect files
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
@@ -98,60 +83,13 @@ Corpus: X files · ~Y words
|
||||
docs: N files (.md .txt ...)
|
||||
papers: N files (.pdf ...)
|
||||
images: N files
|
||||
video: N files (.mp4 .mp3 ...)
|
||||
```
|
||||
|
||||
Omit any category with 0 files from the summary.
|
||||
|
||||
Then act on it:
|
||||
- If `total_files` is 0: stop with "No supported files found in [path]."
|
||||
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
|
||||
- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.
|
||||
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
|
||||
|
||||
### Step 2.5 - Transcribe video / audio files (only if video files detected)
|
||||
|
||||
Skip this step entirely if `detect` returned zero `video` files.
|
||||
|
||||
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
|
||||
|
||||
**Strategy:** Read the god nodes from the detect output or analysis file. You are already a language model - write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
|
||||
|
||||
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
|
||||
|
||||
**Step 1 - Write the Whisper prompt yourself.**
|
||||
|
||||
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
|
||||
|
||||
- Labels: `transformer, attention, encoder, decoder` -> `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
|
||||
- Labels: `kubernetes, deployment, pod, helm` -> `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
|
||||
|
||||
Set it as `GRAPHIFY_WHISPER_PROMPT` in the environment before running the transcription command.
|
||||
|
||||
**Step 2 - Transcribe:**
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, os
|
||||
from pathlib import Path
|
||||
from graphify.transcribe import transcribe_all
|
||||
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
video_files = detect.get('files', {}).get('video', [])
|
||||
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
|
||||
|
||||
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
|
||||
print(json.dumps(transcript_paths))
|
||||
" > graphify-out/.graphify_transcripts.json
|
||||
```
|
||||
|
||||
After transcription:
|
||||
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
|
||||
- Add them to the docs list before dispatching semantic subagents in Step 3B
|
||||
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
|
||||
- If transcription fails for a file, print a warning and continue with the rest
|
||||
|
||||
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, set `GRAPHIFY_WHISPER_MODEL=<name>` in the environment before running the command above.
|
||||
- Otherwise: proceed directly to Step 3 - no need to ask anything.
|
||||
|
||||
### Step 3 - Extract entities and relationships
|
||||
|
||||
@@ -168,7 +106,7 @@ Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is determin
|
||||
For any code files detected, run AST extraction in parallel with Part B subagents:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.extract import collect_files, extract
|
||||
from pathlib import Path
|
||||
@@ -206,7 +144,7 @@ Before dispatching subagents, print a timing estimate:
|
||||
Before dispatching any subagents, check which files already have cached extraction results:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from graphify.cache import check_semantic_cache
|
||||
from pathlib import Path
|
||||
@@ -214,10 +152,10 @@ from pathlib import Path
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
all_files = [f for files in detect['files'].values() for f in files]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
|
||||
cached_nodes, cached_edges, uncached = check_semantic_cache(all_files)
|
||||
|
||||
if cached_nodes or cached_edges or cached_hyperedges:
|
||||
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
|
||||
if cached_nodes or cached_edges:
|
||||
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges}))
|
||||
Path('.graphify_uncached.txt').write_text('\n'.join(uncached))
|
||||
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
|
||||
"
|
||||
@@ -227,23 +165,21 @@ Only dispatch subagents for files listed in `.graphify_uncached.txt`. If all fil
|
||||
|
||||
**Step B1 - Split into chunks**
|
||||
|
||||
Load files from `.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
|
||||
Load files from `.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context).
|
||||
|
||||
**Step B2 - Dispatch ALL subagents in a single message (OpenCode)**
|
||||
**Step B2 - Dispatch ALL subagents in a single message**
|
||||
|
||||
> **OpenCode platform:** Uses `@mention` dispatch instead of the Agent tool. All mentions in a single message run in parallel.
|
||||
|
||||
Dispatch one `@mention` per chunk — ALL in the same response:
|
||||
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.
|
||||
|
||||
Concrete example for 3 chunks:
|
||||
```
|
||||
@agent Chunk CHUNK_NUM of TOTAL_CHUNKS: [extraction prompt below with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE substituted]
|
||||
|
||||
@agent Chunk 2 of TOTAL_CHUNKS: [next chunk]
|
||||
[Agent tool call 1: files 1-15]
|
||||
[Agent tool call 2: files 16-30]
|
||||
[Agent tool call 3: files 31-45]
|
||||
```
|
||||
All three in one message. Not three separate messages.
|
||||
|
||||
Wait for all agents to return. Parse each response as JSON. Accumulate nodes/edges/hyperedges across all results and write to `.graphify_semantic_new.json`.
|
||||
|
||||
The extraction prompt each agent receives (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE):
|
||||
Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE):
|
||||
|
||||
```
|
||||
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
|
||||
@@ -259,7 +195,7 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
@@ -286,16 +222,15 @@ Use sparingly — only when the group relationship adds information beyond the p
|
||||
If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author,
|
||||
contributor onto every node from that file.
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
confidence_score rules:
|
||||
- EXTRACTED edges: confidence_score must be 1.0
|
||||
- INFERRED edges: score 0.4-0.9 based on how certain you are.
|
||||
Strong structural inference (e.g. two classes clearly share data): 0.8-0.9.
|
||||
Reasonable but not certain: 0.6-0.7. Weak inference: 0.4-0.5.
|
||||
- AMBIGUOUS edges: score 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
```
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
@@ -308,29 +243,28 @@ If more than half the chunks failed, stop and tell the user.
|
||||
|
||||
Save new results to cache:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from graphify.cache import save_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[]}
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []))
|
||||
print(f'Cached {saved} files')
|
||||
"
|
||||
```
|
||||
|
||||
Merge cached + new results into `.graphify_semantic.json`:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
cached = json.loads(Path('.graphify_cached.json').read_text()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
cached = json.loads(Path('.graphify_cached.json').read_text()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[]}
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[]}
|
||||
|
||||
all_nodes = cached['nodes'] + new.get('nodes', [])
|
||||
all_edges = cached['edges'] + new.get('edges', [])
|
||||
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
|
||||
seen = set()
|
||||
deduped = []
|
||||
for n in all_nodes:
|
||||
@@ -341,7 +275,6 @@ for n in all_nodes:
|
||||
merged = {
|
||||
'nodes': deduped,
|
||||
'edges': all_edges,
|
||||
'hyperedges': all_hyperedges,
|
||||
'input_tokens': new.get('input_tokens', 0),
|
||||
'output_tokens': new.get('output_tokens', 0),
|
||||
}
|
||||
@@ -354,7 +287,7 @@ Clean up temp files: `rm -f .graphify_cached.json .graphify_uncached.txt .graphi
|
||||
#### Part C - Merge AST + semantic into final extraction
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from pathlib import Path
|
||||
|
||||
@@ -370,11 +303,9 @@ for n in sem['nodes']:
|
||||
seen.add(n['id'])
|
||||
|
||||
merged_edges = ast['edges'] + sem['edges']
|
||||
merged_hyperedges = sem.get('hyperedges', [])
|
||||
merged = {
|
||||
'nodes': merged_nodes,
|
||||
'edges': merged_edges,
|
||||
'hyperedges': merged_hyperedges,
|
||||
'input_tokens': sem.get('input_tokens', 0),
|
||||
'output_tokens': sem.get('output_tokens', 0),
|
||||
}
|
||||
@@ -389,7 +320,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
@@ -442,7 +373,7 @@ Read `.graphify_analysis.json`. For each community key, look at its node labels
|
||||
Then regenerate the report and save the labels for the visualizer:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import score_all
|
||||
@@ -475,14 +406,12 @@ print('Report updated with community labels')
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
### Step 6 - Generate Obsidian vault (default) + optional HTML
|
||||
|
||||
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
|
||||
|
||||
If `--obsidian` was given:
|
||||
**Always generate the Obsidian vault and HTML** - they are the primary visualizations. Skip both if `--no-viz` (report + JSON only).
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_obsidian, to_canvas
|
||||
@@ -510,10 +439,10 @@ print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries
|
||||
"
|
||||
```
|
||||
|
||||
Generate the HTML graph (always, unless `--no-viz`):
|
||||
Also generate the HTML graph (always, unless `--no-viz`):
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_html
|
||||
@@ -540,7 +469,7 @@ else:
|
||||
**If `--neo4j`** - generate a Cypher file for manual import:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_cypher
|
||||
@@ -555,7 +484,7 @@ print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt'
|
||||
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster
|
||||
@@ -577,7 +506,7 @@ Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default
|
||||
### Step 7b - SVG export (only if --svg flag)
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_svg
|
||||
@@ -599,7 +528,7 @@ print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
|
||||
### Step 7c - GraphML export (only if --graphml flag)
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_graphml
|
||||
@@ -641,7 +570,7 @@ To configure in Claude Desktop, add to `claude_desktop_config.json`:
|
||||
If `total_words` from `.graphify_detect.json` is greater than 5,000, run:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from graphify.benchmark import run_benchmark, print_benchmark
|
||||
from pathlib import Path
|
||||
@@ -659,7 +588,7 @@ Print the output directly in chat. If `total_words <= 5000`, skip silently - the
|
||||
### Step 9 - Save manifest, update cost tracker, clean up, and report
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
@@ -697,18 +626,24 @@ rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
Tell the user:
|
||||
```
|
||||
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
|
||||
Graph complete. Outputs are in a hidden folder called graphify-out/ inside the directory you ran this on.
|
||||
|
||||
graph.html - interactive graph, open in browser
|
||||
GRAPH_REPORT.md - audit report
|
||||
graph.json - raw graph data
|
||||
obsidian/ - Obsidian vault (only if --obsidian was given)
|
||||
The folder is hidden (dot prefix) so it won't show in Finder or a normal ls.
|
||||
To see it:
|
||||
Mac/Linux: ls -la graphify-out/
|
||||
VS Code: the Explorer panel shows hidden files by default
|
||||
Finder: Cmd+Shift+. to toggle hidden files
|
||||
|
||||
What's inside:
|
||||
graphify-out/obsidian/ - open this folder as a vault in Obsidian (File > Open Vault)
|
||||
graphify-out/GRAPH_REPORT.md - full audit report, also readable here in Claude
|
||||
graphify-out/graph.json - persistent graph, query it later with /graphify query "..."
|
||||
|
||||
Full path: PATH_TO_DIR/graphify-out/
|
||||
```
|
||||
|
||||
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
|
||||
|
||||
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
|
||||
|
||||
Then paste these sections from GRAPH_REPORT.md directly into the chat:
|
||||
@@ -733,7 +668,7 @@ The graph is the map. Your job after the pipeline is to be the guide.
|
||||
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.detect import detect_incremental, save_manifest
|
||||
from pathlib import Path
|
||||
@@ -752,7 +687,7 @@ print(f'{new_total} new/changed file(s) to re-extract.')
|
||||
If new files exist, first check whether all changed files are code files:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
@@ -772,7 +707,7 @@ If `code_only` is False (any changed file is a doc/paper/image): run the full St
|
||||
Then:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_json
|
||||
@@ -799,7 +734,7 @@ Then run Steps 4–8 on the merged graph as normal.
|
||||
After Step 4, show the graph diff:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from graphify.analyze import graph_diff
|
||||
from graphify.build import build_from_json
|
||||
@@ -833,7 +768,7 @@ Clean up after: `rm -f .graphify_old.json`
|
||||
Skip Steps 1–3. Load the existing graph from `graphify-out/graph.json` and re-run clustering:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections
|
||||
@@ -886,7 +821,7 @@ Two traversal modes - choose based on the question:
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -904,7 +839,7 @@ Load `graphify-out/graph.json`, then:
|
||||
5. If the graph lacks enough information, say so - do not hallucinate edges.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
@@ -995,7 +930,18 @@ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`,
|
||||
After writing the answer, save it back into the graph so it improves future queries:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
|
||||
python3 -c "
|
||||
from graphify.ingest import save_query_result
|
||||
from pathlib import Path
|
||||
save_query_result(
|
||||
question='QUESTION',
|
||||
answer='ANSWER',
|
||||
memory_dir=Path('graphify-out/memory'),
|
||||
query_type='query',
|
||||
source_nodes=SOURCE_NODES, # list of node labels cited, or []
|
||||
)
|
||||
print('Query result saved to graphify-out/memory/')
|
||||
"
|
||||
```
|
||||
|
||||
Replace `QUESTION` with the question, `ANSWER` with your full answer text, `SOURCE_NODES` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
|
||||
@@ -1008,7 +954,7 @@ Find the shortest path between two named concepts in the graph.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -1018,7 +964,7 @@ if not Path('graphify-out/graph.json').exists():
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
@@ -1070,7 +1016,18 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
|
||||
python3 -c "
|
||||
from graphify.ingest import save_query_result
|
||||
from pathlib import Path
|
||||
save_query_result(
|
||||
question='Path from NODE_A to NODE_B',
|
||||
answer='ANSWER',
|
||||
memory_dir=Path('graphify-out/memory'),
|
||||
query_type='path_query',
|
||||
source_nodes=PATH_NODES, # list of node labels on the path
|
||||
)
|
||||
print('Path result saved to graphify-out/memory/')
|
||||
"
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1081,7 +1038,7 @@ Give a plain-language explanation of a single node - everything connected to it.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -1091,7 +1048,7 @@ if not Path('graphify-out/graph.json').exists():
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
@@ -1136,7 +1093,18 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
|
||||
python3 -c "
|
||||
from graphify.ingest import save_query_result
|
||||
from pathlib import Path
|
||||
save_query_result(
|
||||
question='Explain NODE_NAME',
|
||||
answer='ANSWER',
|
||||
memory_dir=Path('graphify-out/memory'),
|
||||
query_type='explain',
|
||||
source_nodes=['NODE_NAME'],
|
||||
)
|
||||
print('Explanation saved to graphify-out/memory/')
|
||||
"
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1146,7 +1114,7 @@ $(cat .graphify_python) -m graphify save-result --question "Explain NODE_NAME" -
|
||||
Fetch a URL and add it to the corpus, then update the graph.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys
|
||||
from graphify.ingest import ingest
|
||||
from pathlib import Path
|
||||
Vendored
-28
@@ -1,28 +0,0 @@
|
||||
defmodule MyApp.Accounts.User do
|
||||
@moduledoc """
|
||||
Handles user accounts and authentication.
|
||||
"""
|
||||
|
||||
alias MyApp.Repo
|
||||
import Ecto.Query
|
||||
|
||||
defstruct [:id, :name, :email]
|
||||
|
||||
def create(attrs) do
|
||||
%__MODULE__{}
|
||||
|> validate(attrs)
|
||||
|> Repo.insert()
|
||||
end
|
||||
|
||||
def find(id) do
|
||||
Repo.get(__MODULE__, id)
|
||||
end
|
||||
|
||||
defp validate(user, attrs) do
|
||||
if Map.has_key?(attrs, :email) do
|
||||
user
|
||||
else
|
||||
{:error, :missing_email}
|
||||
end
|
||||
end
|
||||
end
|
||||
Vendored
-33
@@ -1,33 +0,0 @@
|
||||
module Geometry
|
||||
|
||||
using LinearAlgebra
|
||||
import Base: show
|
||||
|
||||
abstract type Shape end
|
||||
|
||||
struct Point <: Shape
|
||||
x::Float64
|
||||
y::Float64
|
||||
end
|
||||
|
||||
mutable struct Circle <: Shape
|
||||
center::Point
|
||||
radius::Float64
|
||||
end
|
||||
|
||||
function area(c::Circle)
|
||||
return pi * c.radius^2
|
||||
end
|
||||
|
||||
function distance(p1::Point, p2::Point)
|
||||
return norm([p1.x - p2.x, p1.y - p2.y])
|
||||
end
|
||||
|
||||
perimeter(c::Circle) = 2 * pi * c.radius
|
||||
|
||||
function describe(s::Shape)
|
||||
show(s)
|
||||
area(s)
|
||||
end
|
||||
|
||||
end
|
||||
Vendored
-42
@@ -1,42 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SampleDelegate.h"
|
||||
|
||||
@interface Animal : NSObject <SampleDelegate>
|
||||
|
||||
@property (nonatomic, strong) NSString *name;
|
||||
|
||||
- (instancetype)initWithName:(NSString *)name;
|
||||
- (void)speak;
|
||||
|
||||
@end
|
||||
|
||||
@implementation Animal
|
||||
|
||||
- (instancetype)initWithName:(NSString *)name {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_name = name;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)speak {
|
||||
NSLog(@"%@ makes a sound.", self.name);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@interface Dog : Animal
|
||||
|
||||
- (void)fetch;
|
||||
|
||||
@end
|
||||
|
||||
@implementation Dog
|
||||
|
||||
- (void)fetch {
|
||||
[self speak];
|
||||
NSLog(@"%@ fetches the ball!", self.name);
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
-32
@@ -1,32 +0,0 @@
|
||||
using namespace System.IO
|
||||
using module MyModule
|
||||
|
||||
function Get-Data {
|
||||
param(
|
||||
[string]$Name,
|
||||
[int]$Count = 10
|
||||
)
|
||||
$result = Process-Items -Name $Name -Count $Count
|
||||
return $result
|
||||
}
|
||||
|
||||
function Process-Items {
|
||||
param([string]$Name, [int]$Count)
|
||||
Write-Output "Processing $Count items for $Name"
|
||||
}
|
||||
|
||||
class DataProcessor {
|
||||
[string]$Source
|
||||
|
||||
DataProcessor([string]$source) {
|
||||
$this.Source = $source
|
||||
}
|
||||
|
||||
[string] Transform([string]$input) {
|
||||
return $input.ToUpper()
|
||||
}
|
||||
|
||||
[void] Save([string]$path) {
|
||||
Set-Content -Path $path -Value $this.Source
|
||||
}
|
||||
}
|
||||
Vendored
-73
@@ -1,73 +0,0 @@
|
||||
import Foundation
|
||||
import UIKit
|
||||
|
||||
protocol Processor {
|
||||
func process() -> [String]
|
||||
}
|
||||
|
||||
protocol Loggable {
|
||||
func log()
|
||||
}
|
||||
|
||||
class DataProcessor: Processor {
|
||||
private var items: [String] = []
|
||||
|
||||
init() {}
|
||||
|
||||
deinit {}
|
||||
|
||||
func addItem(_ item: String) {
|
||||
items.append(item)
|
||||
}
|
||||
|
||||
func process() -> [String] {
|
||||
return validate(items)
|
||||
}
|
||||
|
||||
private func validate(_ data: [String]) -> [String] {
|
||||
return data.filter { !$0.isEmpty }
|
||||
}
|
||||
}
|
||||
|
||||
struct Config {
|
||||
let baseUrl: String
|
||||
let timeout: Int
|
||||
|
||||
subscript(key: String) -> String? {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
enum NetworkError {
|
||||
case timeout
|
||||
case connectionFailed
|
||||
case unauthorized
|
||||
|
||||
func describe() -> String {
|
||||
return "error"
|
||||
}
|
||||
}
|
||||
|
||||
actor CacheManager {
|
||||
private var store: [String: String] = [:]
|
||||
|
||||
func get(_ key: String) -> String? {
|
||||
return store[key]
|
||||
}
|
||||
}
|
||||
|
||||
extension DataProcessor: Loggable {
|
||||
func log() {
|
||||
print("logging")
|
||||
}
|
||||
}
|
||||
|
||||
extension Config {
|
||||
func isValid() -> Bool {
|
||||
return !baseUrl.isEmpty
|
||||
}
|
||||
}
|
||||
|
||||
func createProcessor() -> DataProcessor {
|
||||
return DataProcessor()
|
||||
}
|
||||
Vendored
-37
@@ -1,37 +0,0 @@
|
||||
const std = @import("std");
|
||||
const mem = @import("std").mem;
|
||||
|
||||
const Point = struct {
|
||||
x: f64,
|
||||
y: f64,
|
||||
|
||||
pub fn distance(self: Point, other: Point) f64 {
|
||||
const dx = self.x - other.x;
|
||||
const dy = self.y - other.dy;
|
||||
return std.math.sqrt(dx * dx + dy * dy);
|
||||
}
|
||||
};
|
||||
|
||||
const Color = enum {
|
||||
red,
|
||||
green,
|
||||
blue,
|
||||
};
|
||||
|
||||
const Shape = union(enum) {
|
||||
circle: f64,
|
||||
rect: Point,
|
||||
};
|
||||
|
||||
pub fn add(a: i32, b: i32) i32 {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
pub fn multiply(a: i32, b: i32) i32 {
|
||||
return a * b;
|
||||
}
|
||||
|
||||
pub fn main() void {
|
||||
const result = add(1, 2);
|
||||
_ = multiply(result, 3);
|
||||
}
|
||||
@@ -137,15 +137,6 @@ def test_file_category():
|
||||
assert _file_category("flash.pdf") == "paper"
|
||||
assert _file_category("diagram.png") == "image"
|
||||
assert _file_category("notes.md") == "doc"
|
||||
# Languages added in later releases — would misclassify as "doc" without detect.py import
|
||||
assert _file_category("app.swift") == "code"
|
||||
assert _file_category("plugin.lua") == "code"
|
||||
assert _file_category("build.zig") == "code"
|
||||
assert _file_category("deploy.ps1") == "code"
|
||||
assert _file_category("server.ex") == "code"
|
||||
assert _file_category("component.jsx") == "code"
|
||||
assert _file_category("analysis.jl") == "code"
|
||||
assert _file_category("view.m") == "code"
|
||||
|
||||
|
||||
def test_is_concept_node_empty_source():
|
||||
|
||||
+1
-53
@@ -1,7 +1,7 @@
|
||||
"""Tests for graphify/cache.py."""
|
||||
import pytest
|
||||
from pathlib import Path
|
||||
from graphify.cache import file_hash, cache_dir, load_cached, save_cached, cached_files, clear_cache, _body_content
|
||||
from graphify.cache import file_hash, cache_dir, load_cached, save_cached, cached_files, clear_cache
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -72,55 +72,3 @@ def test_clear_cache(tmp_file, cache_root):
|
||||
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) > 0
|
||||
clear_cache(cache_root)
|
||||
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) == 0
|
||||
|
||||
|
||||
def test_md_frontmatter_only_change_same_hash(tmp_path):
|
||||
"""Changing only frontmatter fields in a .md file does not change the hash."""
|
||||
f = tmp_path / "doc.md"
|
||||
f.write_text("---\nreviewed: 2026-01-01\n---\n\n# Title\n\nBody text.")
|
||||
h1 = file_hash(f)
|
||||
f.write_text("---\nreviewed: 2026-04-09\n---\n\n# Title\n\nBody text.")
|
||||
h2 = file_hash(f)
|
||||
assert h1 == h2
|
||||
|
||||
|
||||
def test_md_body_change_different_hash(tmp_path):
|
||||
"""Changing the body of a .md file produces a different hash."""
|
||||
f = tmp_path / "doc.md"
|
||||
f.write_text("---\nreviewed: 2026-01-01\n---\n\n# Title\n\nOriginal body.")
|
||||
h1 = file_hash(f)
|
||||
f.write_text("---\nreviewed: 2026-01-01\n---\n\n# Title\n\nChanged body.")
|
||||
h2 = file_hash(f)
|
||||
assert h1 != h2
|
||||
|
||||
|
||||
def test_md_no_frontmatter_hashed_normally(tmp_path):
|
||||
"""A .md file with no frontmatter is hashed by its full content."""
|
||||
f = tmp_path / "doc.md"
|
||||
f.write_text("# Just a heading\n\nNo frontmatter here.")
|
||||
h1 = file_hash(f)
|
||||
f.write_text("# Just a heading\n\nDifferent content.")
|
||||
h2 = file_hash(f)
|
||||
assert h1 != h2
|
||||
|
||||
|
||||
def test_non_md_file_hashed_fully(tmp_path):
|
||||
"""Non-.md files are still hashed by their full content."""
|
||||
f = tmp_path / "script.py"
|
||||
f.write_text("# comment\nx = 1")
|
||||
h1 = file_hash(f)
|
||||
f.write_text("# changed comment\nx = 1")
|
||||
h2 = file_hash(f)
|
||||
assert h1 != h2
|
||||
|
||||
|
||||
def test_body_content_strips_frontmatter():
|
||||
"""_body_content correctly strips YAML frontmatter."""
|
||||
content = b"---\ntitle: Test\n---\n\nActual body."
|
||||
assert _body_content(content) == b"\n\nActual body."
|
||||
|
||||
|
||||
def test_body_content_no_frontmatter():
|
||||
"""_body_content returns content unchanged when no frontmatter present."""
|
||||
content = b"No frontmatter here."
|
||||
assert _body_content(content) == content
|
||||
@@ -1,5 +1,4 @@
|
||||
import json
|
||||
import sys
|
||||
import networkx as nx
|
||||
from pathlib import Path
|
||||
from graphify.build import build_from_json
|
||||
@@ -51,26 +50,3 @@ def test_score_all_keys_match_communities():
|
||||
communities = cluster(G)
|
||||
scores = score_all(G, communities)
|
||||
assert set(scores.keys()) == set(communities.keys())
|
||||
|
||||
|
||||
def test_cluster_does_not_write_to_stdout(capsys):
|
||||
"""Clustering should not emit ANSI escape codes or other output.
|
||||
|
||||
graspologic's leiden() can emit ANSI escape sequences that break
|
||||
PowerShell 5.1's scroll buffer on Windows (issue #19). The output
|
||||
suppression in _partition() should prevent any output from leaking.
|
||||
"""
|
||||
G = make_graph()
|
||||
cluster(G)
|
||||
captured = capsys.readouterr()
|
||||
assert captured.out == "", f"cluster() wrote to stdout: {captured.out!r}"
|
||||
|
||||
|
||||
def test_cluster_does_not_write_to_stderr(capsys):
|
||||
"""Same as above but for stderr — ANSI codes can go to either stream."""
|
||||
G = make_graph()
|
||||
cluster(G)
|
||||
captured = capsys.readouterr()
|
||||
# Allow logging output (starts with [graphify]) but no raw ANSI codes
|
||||
for line in captured.err.splitlines():
|
||||
assert "\x1b" not in line, f"cluster() wrote ANSI to stderr: {line!r}"
|
||||
+1
-168
@@ -1,5 +1,5 @@
|
||||
from pathlib import Path
|
||||
from graphify.detect import classify_file, count_words, detect, FileType, _looks_like_paper, _is_ignored, _load_graphifyignore
|
||||
from graphify.detect import classify_file, count_words, detect, FileType, _looks_like_paper
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
@@ -15,15 +15,6 @@ def test_classify_markdown():
|
||||
def test_classify_pdf():
|
||||
assert classify_file(Path("paper.pdf")) == FileType.PAPER
|
||||
|
||||
def test_classify_pdf_in_xcassets_skipped():
|
||||
# PDFs inside Xcode asset catalogs are vector icons, not papers
|
||||
asset_pdf = Path("MyApp/Images.xcassets/icon.imageset/icon.pdf")
|
||||
assert classify_file(asset_pdf) is None
|
||||
|
||||
def test_classify_pdf_in_xcassets_root_skipped():
|
||||
asset_pdf = Path("Pods/HXPHPicker/Assets.xcassets/photo.pdf")
|
||||
assert classify_file(asset_pdf) is None
|
||||
|
||||
def test_classify_unknown_returns_none():
|
||||
assert classify_file(Path("archive.zip")) is None
|
||||
|
||||
@@ -78,161 +69,3 @@ def test_classify_attention_paper():
|
||||
if paper_path.exists():
|
||||
result = classify_file(paper_path)
|
||||
assert result == FileType.PAPER
|
||||
|
||||
|
||||
def test_graphifyignore_excludes_file(tmp_path):
|
||||
"""Files matching .graphifyignore patterns are excluded from detect()."""
|
||||
(tmp_path / ".graphifyignore").write_text("vendor/\n*.generated.py\n")
|
||||
vendor = tmp_path / "vendor"
|
||||
vendor.mkdir()
|
||||
(vendor / "lib.py").write_text("x = 1")
|
||||
(tmp_path / "main.py").write_text("print('hi')")
|
||||
(tmp_path / "schema.generated.py").write_text("x = 1")
|
||||
|
||||
result = detect(tmp_path)
|
||||
file_list = result["files"]["code"]
|
||||
assert any("main.py" in f for f in file_list)
|
||||
assert not any("vendor" in f for f in file_list)
|
||||
assert not any("generated" in f for f in file_list)
|
||||
assert result["graphifyignore_patterns"] == 2
|
||||
|
||||
|
||||
def test_graphifyignore_missing_is_fine(tmp_path):
|
||||
"""No .graphifyignore is not an error."""
|
||||
(tmp_path / "main.py").write_text("x = 1")
|
||||
result = detect(tmp_path)
|
||||
assert result["graphifyignore_patterns"] == 0
|
||||
|
||||
|
||||
def test_graphifyignore_comments_ignored(tmp_path):
|
||||
"""Comment lines in .graphifyignore are not treated as patterns."""
|
||||
(tmp_path / ".graphifyignore").write_text("# this is a comment\n\nmain.py\n")
|
||||
(tmp_path / "main.py").write_text("x = 1")
|
||||
(tmp_path / "other.py").write_text("x = 2")
|
||||
result = detect(tmp_path)
|
||||
assert not any("main.py" in f for f in result["files"]["code"])
|
||||
assert any("other.py" in f for f in result["files"]["code"])
|
||||
|
||||
|
||||
def test_detect_follows_symlinked_directory(tmp_path):
|
||||
real_dir = tmp_path / "real_lib"
|
||||
real_dir.mkdir()
|
||||
(real_dir / "util.py").write_text("x = 1")
|
||||
(tmp_path / "linked_lib").symlink_to(real_dir)
|
||||
|
||||
result_no = detect(tmp_path, follow_symlinks=False)
|
||||
result_yes = detect(tmp_path, follow_symlinks=True)
|
||||
|
||||
assert any("real_lib" in f for f in result_no["files"]["code"])
|
||||
assert not any("linked_lib" in f for f in result_no["files"]["code"])
|
||||
assert any("linked_lib" in f for f in result_yes["files"]["code"])
|
||||
|
||||
|
||||
def test_detect_follows_symlinked_file(tmp_path):
|
||||
(tmp_path / "real.py").write_text("x = 1")
|
||||
(tmp_path / "link.py").symlink_to(tmp_path / "real.py")
|
||||
|
||||
result = detect(tmp_path, follow_symlinks=True)
|
||||
code = result["files"]["code"]
|
||||
assert any("real.py" in f for f in code)
|
||||
assert any("link.py" in f for f in code)
|
||||
|
||||
|
||||
def test_graphifyignore_discovered_from_parent(tmp_path):
|
||||
"""A .graphifyignore in a parent directory applies to subdirectory scans."""
|
||||
(tmp_path / ".graphifyignore").write_text("vendor/\n")
|
||||
sub = tmp_path / "packages" / "mylib"
|
||||
sub.mkdir(parents=True)
|
||||
(sub / "main.py").write_text("x = 1")
|
||||
vendor = sub / "vendor"
|
||||
vendor.mkdir()
|
||||
(vendor / "dep.py").write_text("y = 2")
|
||||
|
||||
result = detect(sub)
|
||||
code_files = result["files"]["code"]
|
||||
assert any("main.py" in f for f in code_files)
|
||||
assert not any("vendor" in f for f in code_files)
|
||||
assert result["graphifyignore_patterns"] >= 1
|
||||
|
||||
|
||||
def test_graphifyignore_stops_at_git_boundary(tmp_path):
|
||||
"""Upward search stops at the git repo root (.git directory)."""
|
||||
(tmp_path / ".graphifyignore").write_text("main.py\n")
|
||||
repo = tmp_path / "repo"
|
||||
repo.mkdir()
|
||||
(repo / ".git").mkdir()
|
||||
sub = repo / "sub"
|
||||
sub.mkdir()
|
||||
(sub / "main.py").write_text("x = 1")
|
||||
|
||||
result = detect(sub)
|
||||
code_files = result["files"]["code"]
|
||||
assert any("main.py" in f for f in code_files)
|
||||
assert result["graphifyignore_patterns"] == 0
|
||||
|
||||
|
||||
def test_graphifyignore_at_git_root_is_included(tmp_path):
|
||||
"""A .graphifyignore at the git repo root is included when scanning a subdir."""
|
||||
repo = tmp_path / "repo"
|
||||
repo.mkdir()
|
||||
(repo / ".git").mkdir()
|
||||
(repo / ".graphifyignore").write_text("vendor/\n")
|
||||
sub = repo / "packages" / "mylib"
|
||||
sub.mkdir(parents=True)
|
||||
(sub / "main.py").write_text("x = 1")
|
||||
vendor = sub / "vendor"
|
||||
vendor.mkdir()
|
||||
(vendor / "dep.py").write_text("y = 2")
|
||||
|
||||
result = detect(sub)
|
||||
code_files = result["files"]["code"]
|
||||
assert any("main.py" in f for f in code_files)
|
||||
assert not any("vendor" in f for f in code_files)
|
||||
assert result["graphifyignore_patterns"] == 1
|
||||
|
||||
|
||||
def test_detect_handles_circular_symlinks(tmp_path):
|
||||
sub = tmp_path / "a"
|
||||
sub.mkdir()
|
||||
(sub / "main.py").write_text("x = 1")
|
||||
(sub / "loop").symlink_to(tmp_path)
|
||||
|
||||
result = detect(tmp_path, follow_symlinks=True)
|
||||
assert any("main.py" in f for f in result["files"]["code"])
|
||||
|
||||
|
||||
def test_classify_video_extensions():
|
||||
"""Video and audio file extensions should classify as VIDEO."""
|
||||
from graphify.detect import FileType
|
||||
assert classify_file(Path("lecture.mp4")) == FileType.VIDEO
|
||||
assert classify_file(Path("podcast.mp3")) == FileType.VIDEO
|
||||
assert classify_file(Path("talk.mov")) == FileType.VIDEO
|
||||
assert classify_file(Path("recording.wav")) == FileType.VIDEO
|
||||
assert classify_file(Path("webinar.webm")) == FileType.VIDEO
|
||||
assert classify_file(Path("audio.m4a")) == FileType.VIDEO
|
||||
|
||||
|
||||
def test_detect_includes_video_key(tmp_path):
|
||||
"""detect() result always includes a 'video' key even with no video files."""
|
||||
(tmp_path / "main.py").write_text("x = 1")
|
||||
result = detect(tmp_path)
|
||||
assert "video" in result["files"]
|
||||
|
||||
|
||||
def test_detect_finds_video_files(tmp_path):
|
||||
"""detect() correctly counts video files and does not add them to word count."""
|
||||
(tmp_path / "lecture.mp4").write_bytes(b"fake video data")
|
||||
(tmp_path / "notes.md").write_text("# Notes\nSome content here.")
|
||||
result = detect(tmp_path)
|
||||
assert len(result["files"]["video"]) == 1
|
||||
assert any("lecture.mp4" in f for f in result["files"]["video"])
|
||||
# total_words should not include video files (they have no readable text)
|
||||
assert result["total_words"] >= 0 # won't crash
|
||||
|
||||
|
||||
def test_detect_video_not_in_words(tmp_path):
|
||||
"""Video files do not contribute to total_words."""
|
||||
(tmp_path / "clip.mp4").write_bytes(b"\x00" * 100)
|
||||
result = detect(tmp_path)
|
||||
# Only video file present — total_words should be 0
|
||||
assert result["total_words"] == 0
|
||||
+4
-30
@@ -60,9 +60,7 @@ def test_collect_files_from_dir():
|
||||
files = collect_files(FIXTURES)
|
||||
supported = {".py", ".js", ".ts", ".tsx", ".go", ".rs",
|
||||
".java", ".c", ".cpp", ".cc", ".cxx", ".rb",
|
||||
".cs", ".kt", ".kts", ".scala", ".php", ".h", ".hpp",
|
||||
".swift", ".lua", ".toc", ".zig", ".ps1", ".ex", ".exs",
|
||||
".m", ".mm"}
|
||||
".cs", ".kt", ".kts", ".scala", ".php", ".h", ".hpp"}
|
||||
assert all(f.suffix in supported for f in files)
|
||||
assert len(files) > 0
|
||||
|
||||
@@ -73,29 +71,6 @@ def test_collect_files_skips_hidden():
|
||||
assert not any(part.startswith(".") for part in f.parts)
|
||||
|
||||
|
||||
def test_collect_files_follows_symlinked_directory(tmp_path):
|
||||
real_dir = tmp_path / "real_src"
|
||||
real_dir.mkdir()
|
||||
(real_dir / "lib.py").write_text("x = 1")
|
||||
(tmp_path / "linked_src").symlink_to(real_dir)
|
||||
|
||||
files_no = collect_files(tmp_path, follow_symlinks=False)
|
||||
files_yes = collect_files(tmp_path, follow_symlinks=True)
|
||||
|
||||
assert [f.name for f in files_no].count("lib.py") == 1
|
||||
assert [f.name for f in files_yes].count("lib.py") == 2
|
||||
|
||||
|
||||
def test_collect_files_handles_circular_symlinks(tmp_path):
|
||||
sub = tmp_path / "pkg"
|
||||
sub.mkdir()
|
||||
(sub / "mod.py").write_text("x = 1")
|
||||
(sub / "cycle").symlink_to(tmp_path)
|
||||
|
||||
files = collect_files(tmp_path, follow_symlinks=True)
|
||||
assert any(f.name == "mod.py" for f in files)
|
||||
|
||||
|
||||
def test_no_dangling_edges_on_extract():
|
||||
"""After merging multiple files, no internal edges should be dangling."""
|
||||
files = list(FIXTURES.glob("*.py"))
|
||||
@@ -115,13 +90,12 @@ def test_calls_edges_emitted():
|
||||
assert len(calls) > 0, "Expected at least one calls edge"
|
||||
|
||||
|
||||
def test_calls_edges_are_extracted():
|
||||
"""AST-resolved call edges are deterministic and should be EXTRACTED/1.0."""
|
||||
def test_calls_edges_are_inferred():
|
||||
result = extract_python(FIXTURES / "sample_calls.py")
|
||||
for edge in result["edges"]:
|
||||
if edge["relation"] == "calls":
|
||||
assert edge["confidence"] == "EXTRACTED"
|
||||
assert edge["weight"] == 1.0
|
||||
assert edge["confidence"] == "INFERRED"
|
||||
assert edge["weight"] == 0.8
|
||||
|
||||
|
||||
def test_calls_no_self_loops():
|
||||
|
||||
@@ -1,320 +0,0 @@
|
||||
"""Tests for graphify install --platform routing."""
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
import pytest
|
||||
|
||||
|
||||
PLATFORMS = {
|
||||
"claude": (".claude/skills/graphify/SKILL.md",),
|
||||
"codex": (".agents/skills/graphify/SKILL.md",),
|
||||
"opencode": (".config/opencode/skills/graphify/SKILL.md",),
|
||||
"claw": (".claw/skills/graphify/SKILL.md",),
|
||||
"droid": (".factory/skills/graphify/SKILL.md",),
|
||||
"trae": (".trae/skills/graphify/SKILL.md",),
|
||||
"trae-cn": (".trae-cn/skills/graphify/SKILL.md",),
|
||||
"windows": (".claude/skills/graphify/SKILL.md",),
|
||||
}
|
||||
|
||||
|
||||
def _install(tmp_path, platform):
|
||||
from graphify.__main__ import install
|
||||
with patch("graphify.__main__.Path.home", return_value=tmp_path):
|
||||
install(platform=platform)
|
||||
|
||||
|
||||
def test_install_default_claude(tmp_path):
|
||||
_install(tmp_path, "claude")
|
||||
assert (tmp_path / ".claude" / "skills" / "graphify" / "SKILL.md").exists()
|
||||
|
||||
|
||||
def test_install_codex(tmp_path):
|
||||
_install(tmp_path, "codex")
|
||||
assert (tmp_path / ".agents" / "skills" / "graphify" / "SKILL.md").exists()
|
||||
|
||||
|
||||
def test_install_opencode(tmp_path):
|
||||
_install(tmp_path, "opencode")
|
||||
assert (tmp_path / ".config" / "opencode" / "skills" / "graphify" / "SKILL.md").exists()
|
||||
|
||||
|
||||
def test_install_claw(tmp_path):
|
||||
_install(tmp_path, "claw")
|
||||
assert (tmp_path / ".claw" / "skills" / "graphify" / "SKILL.md").exists()
|
||||
|
||||
|
||||
def test_install_droid(tmp_path):
|
||||
_install(tmp_path, "droid")
|
||||
assert (tmp_path / ".factory" / "skills" / "graphify" / "SKILL.md").exists()
|
||||
|
||||
|
||||
def test_install_trae(tmp_path):
|
||||
_install(tmp_path, "trae")
|
||||
assert (tmp_path / ".trae" / "skills" / "graphify" / "SKILL.md").exists()
|
||||
|
||||
|
||||
def test_install_trae_cn(tmp_path):
|
||||
_install(tmp_path, "trae-cn")
|
||||
assert (tmp_path / ".trae-cn" / "skills" / "graphify" / "SKILL.md").exists()
|
||||
|
||||
|
||||
def test_install_windows(tmp_path):
|
||||
_install(tmp_path, "windows")
|
||||
assert (tmp_path / ".claude" / "skills" / "graphify" / "SKILL.md").exists()
|
||||
|
||||
|
||||
def test_install_unknown_platform_exits(tmp_path):
|
||||
with pytest.raises(SystemExit):
|
||||
_install(tmp_path, "unknown")
|
||||
|
||||
|
||||
def test_codex_skill_contains_spawn_agent():
|
||||
"""Codex skill file must reference spawn_agent."""
|
||||
import graphify
|
||||
skill = (Path(graphify.__file__).parent / "skill-codex.md").read_text()
|
||||
assert "spawn_agent" in skill
|
||||
|
||||
|
||||
def test_opencode_skill_contains_mention():
|
||||
"""OpenCode skill file must reference @mention."""
|
||||
import graphify
|
||||
skill = (Path(graphify.__file__).parent / "skill-opencode.md").read_text()
|
||||
assert "@mention" in skill
|
||||
|
||||
|
||||
def test_claw_skill_is_sequential():
|
||||
"""OpenClaw skill file must describe sequential extraction."""
|
||||
import graphify
|
||||
skill = (Path(graphify.__file__).parent / "skill-claw.md").read_text()
|
||||
assert "sequential" in skill.lower()
|
||||
assert "spawn_agent" not in skill
|
||||
assert "@mention" not in skill
|
||||
|
||||
|
||||
def test_all_skill_files_exist_in_package():
|
||||
"""All installable platform skill files must be present in the installed package."""
|
||||
import graphify
|
||||
pkg = Path(graphify.__file__).parent
|
||||
for name in ("skill.md", "skill-codex.md", "skill-opencode.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md"):
|
||||
assert (pkg / name).exists(), f"Missing: {name}"
|
||||
|
||||
|
||||
def test_claude_install_registers_claude_md(tmp_path):
|
||||
"""Claude platform install writes CLAUDE.md; others do not."""
|
||||
_install(tmp_path, "claude")
|
||||
assert (tmp_path / ".claude" / "CLAUDE.md").exists()
|
||||
|
||||
|
||||
def test_codex_install_does_not_write_claude_md(tmp_path):
|
||||
_install(tmp_path, "codex")
|
||||
assert not (tmp_path / ".claude" / "CLAUDE.md").exists()
|
||||
|
||||
|
||||
# --- always-on AGENTS.md install/uninstall tests ---
|
||||
|
||||
def _agents_install(tmp_path, platform):
|
||||
from graphify.__main__ import _agents_install as _install_fn
|
||||
_install_fn(tmp_path, platform)
|
||||
|
||||
|
||||
def _agents_uninstall(tmp_path):
|
||||
from graphify.__main__ import _agents_uninstall as _uninstall_fn
|
||||
_uninstall_fn(tmp_path)
|
||||
|
||||
|
||||
def test_codex_agents_install_writes_agents_md(tmp_path):
|
||||
_agents_install(tmp_path, "codex")
|
||||
agents_md = tmp_path / "AGENTS.md"
|
||||
assert agents_md.exists()
|
||||
assert "graphify" in agents_md.read_text()
|
||||
assert "GRAPH_REPORT.md" in agents_md.read_text()
|
||||
|
||||
|
||||
def test_opencode_agents_install_writes_agents_md(tmp_path):
|
||||
_agents_install(tmp_path, "opencode")
|
||||
assert (tmp_path / "AGENTS.md").exists()
|
||||
|
||||
|
||||
def test_claw_agents_install_writes_agents_md(tmp_path):
|
||||
_agents_install(tmp_path, "claw")
|
||||
assert (tmp_path / "AGENTS.md").exists()
|
||||
|
||||
|
||||
def test_agents_install_idempotent(tmp_path):
|
||||
"""Installing twice does not duplicate the section."""
|
||||
_agents_install(tmp_path, "codex")
|
||||
_agents_install(tmp_path, "codex")
|
||||
content = (tmp_path / "AGENTS.md").read_text()
|
||||
assert content.count("## graphify") == 1
|
||||
|
||||
|
||||
def test_agents_install_appends_to_existing(tmp_path):
|
||||
"""Installs into an existing AGENTS.md without overwriting other content."""
|
||||
agents_md = tmp_path / "AGENTS.md"
|
||||
agents_md.write_text("# Existing rules\n\nDo not break things.\n")
|
||||
_agents_install(tmp_path, "codex")
|
||||
content = agents_md.read_text()
|
||||
assert "Do not break things." in content
|
||||
assert "## graphify" in content
|
||||
|
||||
|
||||
def test_agents_uninstall_removes_section(tmp_path):
|
||||
_agents_install(tmp_path, "codex")
|
||||
_agents_uninstall(tmp_path)
|
||||
agents_md = tmp_path / "AGENTS.md"
|
||||
# File deleted when it only contained graphify section
|
||||
assert not agents_md.exists()
|
||||
|
||||
|
||||
def test_agents_uninstall_preserves_other_content(tmp_path):
|
||||
"""Uninstall keeps pre-existing content."""
|
||||
agents_md = tmp_path / "AGENTS.md"
|
||||
agents_md.write_text("# Existing rules\n\nDo not break things.\n")
|
||||
_agents_install(tmp_path, "codex")
|
||||
_agents_uninstall(tmp_path)
|
||||
assert agents_md.exists()
|
||||
content = agents_md.read_text()
|
||||
assert "Do not break things." in content
|
||||
assert "## graphify" not in content
|
||||
|
||||
|
||||
def test_agents_uninstall_no_op_when_not_installed(tmp_path, capsys):
|
||||
_agents_uninstall(tmp_path)
|
||||
out = capsys.readouterr().out
|
||||
assert "nothing to do" in out
|
||||
|
||||
|
||||
# --- OpenCode plugin tests ---
|
||||
|
||||
def test_opencode_agents_install_writes_plugin(tmp_path):
|
||||
"""opencode install writes .opencode/plugins/graphify.js."""
|
||||
_agents_install(tmp_path, "opencode")
|
||||
plugin = tmp_path / ".opencode" / "plugins" / "graphify.js"
|
||||
assert plugin.exists()
|
||||
assert "tool.execute.before" in plugin.read_text()
|
||||
|
||||
|
||||
def test_opencode_agents_install_registers_plugin_in_config(tmp_path):
|
||||
"""opencode install registers the plugin in opencode.json."""
|
||||
_agents_install(tmp_path, "opencode")
|
||||
config_file = tmp_path / "opencode.json"
|
||||
assert config_file.exists()
|
||||
import json as _json
|
||||
config = _json.loads(config_file.read_text())
|
||||
assert any("graphify.js" in p for p in config.get("plugin", []))
|
||||
|
||||
|
||||
def test_opencode_agents_install_merges_existing_config(tmp_path):
|
||||
"""opencode install preserves existing opencode.json keys."""
|
||||
import json as _json
|
||||
config_file = tmp_path / "opencode.json"
|
||||
config_file.write_text(_json.dumps({"model": "claude-opus-4-5", "plugin": []}))
|
||||
_agents_install(tmp_path, "opencode")
|
||||
config = _json.loads(config_file.read_text())
|
||||
assert config["model"] == "claude-opus-4-5"
|
||||
assert any("graphify.js" in p for p in config["plugin"])
|
||||
|
||||
|
||||
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)
|
||||
plugin = tmp_path / ".opencode" / "plugins" / "graphify.js"
|
||||
assert not plugin.exists()
|
||||
config_file = tmp_path / "opencode.json"
|
||||
if config_file.exists():
|
||||
config = _json.loads(config_file.read_text())
|
||||
assert not any("graphify.js" in p for p in config.get("plugin", []))
|
||||
|
||||
|
||||
# ── Cursor ────────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_cursor_install_writes_rule(tmp_path):
|
||||
"""cursor install writes .cursor/rules/graphify.mdc."""
|
||||
from graphify.__main__ import _cursor_install
|
||||
_cursor_install(tmp_path)
|
||||
rule = tmp_path / ".cursor" / "rules" / "graphify.mdc"
|
||||
assert rule.exists()
|
||||
content = rule.read_text()
|
||||
assert "alwaysApply: true" in content
|
||||
assert "graphify-out/GRAPH_REPORT.md" in content
|
||||
|
||||
|
||||
def test_cursor_install_idempotent(tmp_path):
|
||||
"""cursor install does not overwrite an existing rule file."""
|
||||
from graphify.__main__ import _cursor_install
|
||||
_cursor_install(tmp_path)
|
||||
rule = tmp_path / ".cursor" / "rules" / "graphify.mdc"
|
||||
original = rule.read_text()
|
||||
_cursor_install(tmp_path)
|
||||
assert rule.read_text() == original
|
||||
|
||||
|
||||
def test_cursor_uninstall_removes_rule(tmp_path):
|
||||
"""cursor uninstall removes the rule file."""
|
||||
from graphify.__main__ import _cursor_install, _cursor_uninstall
|
||||
_cursor_install(tmp_path)
|
||||
_cursor_uninstall(tmp_path)
|
||||
rule = tmp_path / ".cursor" / "rules" / "graphify.mdc"
|
||||
assert not rule.exists()
|
||||
|
||||
|
||||
def test_cursor_uninstall_noop_if_not_installed(tmp_path):
|
||||
"""cursor uninstall does nothing if rule was never written."""
|
||||
from graphify.__main__ import _cursor_uninstall
|
||||
_cursor_uninstall(tmp_path) # should not raise
|
||||
|
||||
|
||||
# ── Gemini CLI ────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_gemini_install_writes_gemini_md(tmp_path):
|
||||
from graphify.__main__ import gemini_install
|
||||
gemini_install(tmp_path)
|
||||
md = tmp_path / "GEMINI.md"
|
||||
assert md.exists()
|
||||
assert "graphify-out/GRAPH_REPORT.md" in md.read_text()
|
||||
|
||||
def test_gemini_install_writes_hook(tmp_path):
|
||||
import json as _json
|
||||
from graphify.__main__ import gemini_install
|
||||
gemini_install(tmp_path)
|
||||
settings = _json.loads((tmp_path / ".gemini" / "settings.json").read_text())
|
||||
hooks = settings["hooks"]["BeforeTool"]
|
||||
assert any("graphify" in str(h) for h in hooks)
|
||||
|
||||
def test_gemini_install_idempotent(tmp_path):
|
||||
from graphify.__main__ import gemini_install
|
||||
gemini_install(tmp_path)
|
||||
gemini_install(tmp_path)
|
||||
md = tmp_path / "GEMINI.md"
|
||||
assert md.read_text().count("## graphify") == 1
|
||||
|
||||
def test_gemini_install_merges_existing_gemini_md(tmp_path):
|
||||
from graphify.__main__ import gemini_install
|
||||
(tmp_path / "GEMINI.md").write_text("# My project rules\n")
|
||||
gemini_install(tmp_path)
|
||||
content = (tmp_path / "GEMINI.md").read_text()
|
||||
assert "# My project rules" in content
|
||||
assert "graphify-out/GRAPH_REPORT.md" in content
|
||||
|
||||
def test_gemini_uninstall_removes_section(tmp_path):
|
||||
from graphify.__main__ import gemini_install, gemini_uninstall
|
||||
gemini_install(tmp_path)
|
||||
gemini_uninstall(tmp_path)
|
||||
md = tmp_path / "GEMINI.md"
|
||||
assert not md.exists()
|
||||
|
||||
def test_gemini_uninstall_removes_hook(tmp_path):
|
||||
import json as _json
|
||||
from graphify.__main__ import gemini_install, gemini_uninstall
|
||||
gemini_install(tmp_path)
|
||||
gemini_uninstall(tmp_path)
|
||||
settings_path = tmp_path / ".gemini" / "settings.json"
|
||||
if settings_path.exists():
|
||||
settings = _json.loads(settings_path.read_text())
|
||||
hooks = settings.get("hooks", {}).get("BeforeTool", [])
|
||||
assert not any("graphify" in str(h) for h in hooks)
|
||||
|
||||
def test_gemini_uninstall_noop_if_not_installed(tmp_path):
|
||||
from graphify.__main__ import gemini_uninstall
|
||||
gemini_uninstall(tmp_path) # should not raise
|
||||
+3
-294
@@ -1,11 +1,10 @@
|
||||
"""Tests for language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Go, Julia."""
|
||||
"""Tests for the 8 new language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP."""
|
||||
from __future__ import annotations
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from graphify.extract import (
|
||||
extract_java, extract_c, extract_cpp, extract_ruby,
|
||||
extract_csharp, extract_kotlin, extract_scala, extract_php,
|
||||
extract_swift, extract_go, extract_julia,
|
||||
)
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
@@ -76,11 +75,11 @@ def test_c_emits_calls():
|
||||
r = extract_c(FIXTURES / "sample.c")
|
||||
assert any(e["relation"] == "calls" for e in r["edges"])
|
||||
|
||||
def test_c_calls_are_extracted():
|
||||
def test_c_calls_are_inferred():
|
||||
r = extract_c(FIXTURES / "sample.c")
|
||||
for e in r["edges"]:
|
||||
if e["relation"] == "calls":
|
||||
assert e["confidence"] == "EXTRACTED"
|
||||
assert e["confidence"] == "INFERRED"
|
||||
|
||||
|
||||
# ── C++ ───────────────────────────────────────────────────────────────────────
|
||||
@@ -148,21 +147,6 @@ def test_csharp_finds_usings():
|
||||
r = extract_csharp(FIXTURES / "sample.cs")
|
||||
assert "imports" in _relations(r)
|
||||
|
||||
def test_csharp_inherits_edge():
|
||||
r = extract_csharp(FIXTURES / "sample.cs")
|
||||
inherits = [e for e in r["edges"] if e["relation"] == "inherits"]
|
||||
assert len(inherits) >= 1
|
||||
|
||||
def test_csharp_inherits_iprocessor():
|
||||
r = extract_csharp(FIXTURES / "sample.cs")
|
||||
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
found = any(
|
||||
"DataProcessor" in node_by_id.get(e["source"], "") and
|
||||
"IProcessor" in node_by_id.get(e["target"], "")
|
||||
for e in r["edges"] if e["relation"] == "inherits"
|
||||
)
|
||||
assert found, "DataProcessor should have inherits edge to IProcessor"
|
||||
|
||||
|
||||
# ── Kotlin ───────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -233,278 +217,3 @@ def test_php_finds_function():
|
||||
def test_php_finds_imports():
|
||||
r = extract_php(FIXTURES / "sample.php")
|
||||
assert "imports" in _relations(r)
|
||||
|
||||
|
||||
# ── Swift ────────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_swift_no_error():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert "error" not in r
|
||||
|
||||
def test_swift_finds_class():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("DataProcessor" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_protocol():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("Processor" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_struct():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("Config" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_methods():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
labels = _labels(r)
|
||||
assert any("addItem" in l for l in labels)
|
||||
assert any("process" in l for l in labels)
|
||||
|
||||
def test_swift_finds_function():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("createProcessor" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_imports():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert "imports" in _relations(r)
|
||||
|
||||
def test_swift_no_dangling_edges():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
node_ids = {n["id"] for n in r["nodes"]}
|
||||
for e in r["edges"]:
|
||||
assert e["source"] in node_ids
|
||||
|
||||
def test_swift_finds_actor():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("CacheManager" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_enum():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("NetworkError" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_enum_methods():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("describe" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_enum_cases():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
labels = _labels(r)
|
||||
assert any("timeout" in l for l in labels)
|
||||
assert any("connectionFailed" in l for l in labels)
|
||||
|
||||
def test_swift_enum_cases_have_case_of_edge():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
case_edges = [e for e in r["edges"] if e["relation"] == "case_of"]
|
||||
assert len(case_edges) >= 2
|
||||
|
||||
def test_swift_finds_deinit():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("deinit" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_subscript():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("subscript" in l for l in _labels(r))
|
||||
|
||||
def test_swift_extension_methods_attach_to_type():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
method_edges = [e for e in r["edges"] if e["relation"] == "method"]
|
||||
found = False
|
||||
for e in method_edges:
|
||||
src_label = node_by_id.get(e["source"], "")
|
||||
tgt_label = node_by_id.get(e["target"], "")
|
||||
if "Config" in src_label and "isValid" in tgt_label:
|
||||
found = True
|
||||
break
|
||||
assert found, "extension method isValid should attach to Config"
|
||||
|
||||
def test_swift_extension_does_not_duplicate_type_node():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
config_nodes = [n for n in r["nodes"] if n["label"] == "Config"]
|
||||
assert len(config_nodes) == 1, f"Config should appear once, got {len(config_nodes)}"
|
||||
|
||||
def test_swift_conformance_edge():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
inherits_edges = [e for e in r["edges"] if e["relation"] == "inherits"]
|
||||
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
found = False
|
||||
for e in inherits_edges:
|
||||
src_label = node_by_id.get(e["source"], "")
|
||||
tgt_label = node_by_id.get(e["target"], "")
|
||||
if "DataProcessor" in src_label and "Processor" in tgt_label:
|
||||
found = True
|
||||
break
|
||||
assert found, "DataProcessor should have inherits edge to Processor"
|
||||
|
||||
def test_swift_extension_conformance_edge():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
inherits_edges = [e for e in r["edges"] if e["relation"] == "inherits"]
|
||||
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
found = False
|
||||
for e in inherits_edges:
|
||||
src_label = node_by_id.get(e["source"], "")
|
||||
tgt_label = node_by_id.get(e["target"], "")
|
||||
if "DataProcessor" in src_label and "Loggable" in tgt_label:
|
||||
found = True
|
||||
break
|
||||
assert found, "extension should add conformance edge DataProcessor -> Loggable"
|
||||
|
||||
def test_swift_emits_calls():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
calls = _calls(r)
|
||||
assert any("process" in src and "validate" in tgt for src, tgt in calls)
|
||||
|
||||
|
||||
# ── Elixir ────────────────────────────────────────────────────────────────────
|
||||
|
||||
from graphify.extract import extract_elixir
|
||||
|
||||
def test_elixir_finds_module():
|
||||
r = extract_elixir(FIXTURES / "sample.ex")
|
||||
assert "error" not in r
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert any("MyApp.Accounts.User" in l for l in labels)
|
||||
|
||||
def test_elixir_finds_functions():
|
||||
r = extract_elixir(FIXTURES / "sample.ex")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert any("create" in l for l in labels)
|
||||
assert any("find" in l for l in labels)
|
||||
assert any("validate" in l for l in labels)
|
||||
|
||||
def test_elixir_finds_imports():
|
||||
r = extract_elixir(FIXTURES / "sample.ex")
|
||||
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
|
||||
assert len(import_edges) >= 2
|
||||
|
||||
def test_elixir_finds_calls():
|
||||
r = extract_elixir(FIXTURES / "sample.ex")
|
||||
calls = {(e["source"], e["target"]) for e in r["edges"] if e["relation"] == "calls"}
|
||||
labels = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
assert any("create" in labels.get(src, "") and "validate" in labels.get(tgt, "") for src, tgt in calls)
|
||||
|
||||
def test_elixir_method_edges():
|
||||
r = extract_elixir(FIXTURES / "sample.ex")
|
||||
methods = [e for e in r["edges"] if e["relation"] == "method"]
|
||||
assert len(methods) >= 3
|
||||
|
||||
|
||||
# ── Objective-C ──────────────────────────────────────────────────────────────
|
||||
from graphify.extract import extract_objc
|
||||
|
||||
|
||||
def test_objc_finds_interface():
|
||||
r = extract_objc(FIXTURES / "sample.m")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert "Animal" in labels
|
||||
|
||||
|
||||
def test_objc_finds_subclass():
|
||||
r = extract_objc(FIXTURES / "sample.m")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert "Dog" in labels
|
||||
|
||||
|
||||
def test_objc_finds_methods():
|
||||
r = extract_objc(FIXTURES / "sample.m")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert any("speak" in l or "fetch" in l or "initWithName" in l for l in labels)
|
||||
|
||||
|
||||
def test_objc_finds_imports():
|
||||
r = extract_objc(FIXTURES / "sample.m")
|
||||
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
|
||||
assert len(import_edges) >= 1
|
||||
|
||||
|
||||
def test_objc_inherits_edge():
|
||||
r = extract_objc(FIXTURES / "sample.m")
|
||||
inherits = [e for e in r["edges"] if e["relation"] == "inherits"]
|
||||
assert len(inherits) >= 1
|
||||
|
||||
|
||||
def test_objc_no_dangling_edges():
|
||||
r = extract_objc(FIXTURES / "sample.m")
|
||||
node_ids = {n["id"] for n in r["nodes"]}
|
||||
for e in r["edges"]:
|
||||
assert e["source"] in node_ids, f"Dangling source: {e}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Go
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_go_receiver_methods_share_type_node():
|
||||
"""Methods on the same receiver type must share one canonical type node."""
|
||||
r = extract_go(FIXTURES / "sample.go")
|
||||
server_nodes = [n for n in r["nodes"] if n["label"] == "Server"]
|
||||
# Both Start() and Stop() are on *Server — should produce exactly one Server node
|
||||
assert len(server_nodes) == 1
|
||||
|
||||
def test_go_receiver_uses_pkg_scope():
|
||||
"""Type node id should be scoped to directory, not file stem."""
|
||||
r = extract_go(FIXTURES / "sample.go")
|
||||
server_nodes = [n for n in r["nodes"] if n["label"] == "Server"]
|
||||
assert server_nodes
|
||||
# Should NOT contain the file stem "sample" in the type node id
|
||||
assert "sample" not in server_nodes[0]["id"].split(":")[0]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Julia
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_julia_finds_module():
|
||||
r = extract_julia(FIXTURES / "sample.jl")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert "Geometry" in labels
|
||||
|
||||
|
||||
def test_julia_finds_structs():
|
||||
r = extract_julia(FIXTURES / "sample.jl")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert "Point" in labels
|
||||
assert "Circle" in labels
|
||||
|
||||
|
||||
def test_julia_finds_abstract_type():
|
||||
r = extract_julia(FIXTURES / "sample.jl")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert "Shape" in labels
|
||||
|
||||
|
||||
def test_julia_finds_functions():
|
||||
r = extract_julia(FIXTURES / "sample.jl")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert any("area" in l for l in labels)
|
||||
assert any("distance" in l for l in labels)
|
||||
|
||||
|
||||
def test_julia_finds_short_function():
|
||||
r = extract_julia(FIXTURES / "sample.jl")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert any("perimeter" in l for l in labels)
|
||||
|
||||
|
||||
def test_julia_finds_imports():
|
||||
r = extract_julia(FIXTURES / "sample.jl")
|
||||
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
|
||||
assert len(import_edges) >= 1
|
||||
|
||||
|
||||
def test_julia_finds_inherits():
|
||||
r = extract_julia(FIXTURES / "sample.jl")
|
||||
inherits = [e for e in r["edges"] if e["relation"] == "inherits"]
|
||||
assert len(inherits) >= 1
|
||||
|
||||
|
||||
def test_julia_finds_calls():
|
||||
r = extract_julia(FIXTURES / "sample.jl")
|
||||
call_edges = [e for e in r["edges"] if e["relation"] == "calls"]
|
||||
assert len(call_edges) >= 1
|
||||
|
||||
|
||||
def test_julia_no_dangling_edges():
|
||||
r = extract_julia(FIXTURES / "sample.jl")
|
||||
node_ids = {n["id"] for n in r["nodes"]}
|
||||
for e in r["edges"]:
|
||||
assert e["source"] in node_ids, f"Dangling source: {e}"
|
||||
@@ -47,11 +47,11 @@ def test_ts_emits_calls():
|
||||
# .post() calls .get()
|
||||
assert any("post" in src and "get" in tgt for src, tgt in calls)
|
||||
|
||||
def test_ts_calls_are_extracted():
|
||||
def test_ts_calls_are_inferred():
|
||||
r = extract_js(FIXTURES / "sample.ts")
|
||||
for e in r["edges"]:
|
||||
if e["relation"] == "calls":
|
||||
assert e["confidence"] == "EXTRACTED"
|
||||
assert e["confidence"] == "INFERRED"
|
||||
|
||||
def test_ts_no_dangling_edges():
|
||||
r = extract_js(FIXTURES / "sample.ts")
|
||||
@@ -83,9 +83,9 @@ def test_go_emits_calls():
|
||||
# main() calls NewServer and Start
|
||||
assert len(_call_pairs(r)) > 0
|
||||
|
||||
def test_go_has_extracted_calls():
|
||||
def test_go_has_inferred_calls():
|
||||
r = extract_go(FIXTURES / "sample.go")
|
||||
assert "EXTRACTED" in _confidences(r)
|
||||
assert "INFERRED" in _confidences(r)
|
||||
|
||||
def test_go_no_dangling_edges():
|
||||
r = extract_go(FIXTURES / "sample.go")
|
||||
@@ -117,11 +117,11 @@ def test_rust_emits_calls():
|
||||
calls = _call_pairs(r)
|
||||
assert any("build_graph" in src for src, _ in calls)
|
||||
|
||||
def test_rust_calls_are_extracted():
|
||||
def test_rust_calls_are_inferred():
|
||||
r = extract_rust(FIXTURES / "sample.rs")
|
||||
for e in r["edges"]:
|
||||
if e["relation"] == "calls":
|
||||
assert e["confidence"] == "EXTRACTED"
|
||||
assert e["confidence"] == "INFERRED"
|
||||
|
||||
def test_rust_no_dangling_edges():
|
||||
r = extract_rust(FIXTURES / "sample.rs")
|
||||
|
||||
@@ -168,11 +168,9 @@ def test_validate_graph_path_raises_if_file_missing(tmp_path):
|
||||
# sanitize_label
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_sanitize_label_passthrough_html_chars():
|
||||
# sanitize_label does NOT HTML-escape — callers that inject into HTML must
|
||||
# wrap with html.escape() themselves (e.g. the title in to_html())
|
||||
assert sanitize_label("<script>") == "<script>"
|
||||
assert sanitize_label("foo & bar") == "foo & bar"
|
||||
def test_sanitize_label_escapes_html():
|
||||
assert "<script>" in sanitize_label("<script>")
|
||||
assert "&" in sanitize_label("foo & bar")
|
||||
|
||||
def test_sanitize_label_strips_control_chars():
|
||||
result = sanitize_label("hello\x00\x1fworld")
|
||||
|
||||
+4
-1
@@ -138,11 +138,14 @@ def test_subgraph_to_text_edge_included():
|
||||
# --- _load_graph ---
|
||||
|
||||
def test_load_graph_roundtrip(tmp_path):
|
||||
from unittest.mock import patch
|
||||
G = _make_graph()
|
||||
data = json_graph.node_link_data(G, edges="links")
|
||||
p = tmp_path / "graph.json"
|
||||
p.write_text(json.dumps(data))
|
||||
G2 = _load_graph(str(p))
|
||||
# validate_graph_path is tested separately; here we test parse correctness
|
||||
with patch("graphify.serve.validate_graph_path", return_value=p):
|
||||
G2 = _load_graph(str(p))
|
||||
assert G2.number_of_nodes() == G.number_of_nodes()
|
||||
assert G2.number_of_edges() == G.number_of_edges()
|
||||
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
"""Tests for graphify.transcribe — video/audio transcription support."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify.transcribe import (
|
||||
VIDEO_EXTENSIONS,
|
||||
build_whisper_prompt,
|
||||
transcribe,
|
||||
transcribe_all,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# VIDEO_EXTENSIONS
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_video_extensions_set():
|
||||
assert ".mp4" in VIDEO_EXTENSIONS
|
||||
assert ".mp3" in VIDEO_EXTENSIONS
|
||||
assert ".wav" in VIDEO_EXTENSIONS
|
||||
assert ".mov" in VIDEO_EXTENSIONS
|
||||
assert ".py" not in VIDEO_EXTENSIONS
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# build_whisper_prompt
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_build_whisper_prompt_no_nodes():
|
||||
"""Empty god_nodes returns fallback prompt."""
|
||||
prompt = build_whisper_prompt([])
|
||||
assert "punctuation" in prompt.lower() or len(prompt) > 0
|
||||
|
||||
|
||||
def test_build_whisper_prompt_env_override(monkeypatch):
|
||||
"""GRAPHIFY_WHISPER_PROMPT env var short-circuits LLM call."""
|
||||
monkeypatch.setenv("GRAPHIFY_WHISPER_PROMPT", "Custom domain hint.")
|
||||
prompt = build_whisper_prompt([{"label": "Python"}, {"label": "FastAPI"}])
|
||||
assert prompt == "Custom domain hint."
|
||||
|
||||
|
||||
def test_build_whisper_prompt_returns_topic_string():
|
||||
"""Returns a topic-based prompt from god node labels — no LLM call."""
|
||||
god_nodes = [{"label": "neural networks"}, {"label": "transformers"}, {"label": "attention"}]
|
||||
with patch.dict(os.environ, {}, clear=False):
|
||||
os.environ.pop("GRAPHIFY_WHISPER_PROMPT", None)
|
||||
prompt = build_whisper_prompt(god_nodes)
|
||||
assert "neural networks" in prompt.lower() or "transformers" in prompt.lower()
|
||||
assert "punctuation" in prompt.lower()
|
||||
|
||||
|
||||
def test_build_whisper_prompt_nodes_without_labels():
|
||||
"""Nodes missing 'label' keys are safely skipped."""
|
||||
god_nodes = [{"id": "1"}, {"id": "2", "label": ""}]
|
||||
prompt = build_whisper_prompt(god_nodes)
|
||||
assert len(prompt) > 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# transcribe
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_transcribe_uses_cache(tmp_path):
|
||||
"""If transcript already exists, transcribe() returns cached path without running Whisper."""
|
||||
video = tmp_path / "lecture.mp4"
|
||||
video.write_bytes(b"fake")
|
||||
out_dir = tmp_path / "transcripts"
|
||||
out_dir.mkdir()
|
||||
cached = out_dir / "lecture.txt"
|
||||
cached.write_text("Cached transcript content.")
|
||||
|
||||
result = transcribe(video, output_dir=out_dir)
|
||||
assert result == cached
|
||||
|
||||
|
||||
def test_transcribe_force_reruns(tmp_path):
|
||||
"""force=True re-transcribes even when cache exists."""
|
||||
video = tmp_path / "talk.mp4"
|
||||
video.write_bytes(b"fake")
|
||||
out_dir = tmp_path / "transcripts"
|
||||
out_dir.mkdir()
|
||||
(out_dir / "talk.txt").write_text("Old transcript.")
|
||||
|
||||
fake_segment = MagicMock()
|
||||
fake_segment.text = "New transcript segment."
|
||||
fake_info = MagicMock()
|
||||
fake_info.language = "en"
|
||||
|
||||
fake_model = MagicMock()
|
||||
fake_model.transcribe.return_value = ([fake_segment], fake_info)
|
||||
|
||||
with patch("graphify.transcribe._get_whisper", return_value=lambda *a, **kw: fake_model):
|
||||
result = transcribe(video, output_dir=out_dir, force=True)
|
||||
|
||||
assert result.read_text() == "New transcript segment."
|
||||
|
||||
|
||||
def test_transcribe_missing_faster_whisper(tmp_path):
|
||||
"""ImportError propagates when faster_whisper is not installed."""
|
||||
video = tmp_path / "clip.mp4"
|
||||
video.write_bytes(b"fake")
|
||||
|
||||
with patch("graphify.transcribe._get_whisper", side_effect=ImportError("faster-whisper not installed")):
|
||||
with pytest.raises(ImportError):
|
||||
transcribe(video, output_dir=tmp_path / "out")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# transcribe_all
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_transcribe_all_empty():
|
||||
"""Empty input returns empty list without error."""
|
||||
assert transcribe_all([]) == []
|
||||
|
||||
|
||||
def test_transcribe_all_uses_cache(tmp_path):
|
||||
"""transcribe_all() returns cached paths for already-transcribed files."""
|
||||
video = tmp_path / "lecture.mp4"
|
||||
video.write_bytes(b"fake")
|
||||
out_dir = tmp_path / "transcripts"
|
||||
out_dir.mkdir()
|
||||
cached = out_dir / "lecture.txt"
|
||||
cached.write_text("Cached.")
|
||||
|
||||
results = transcribe_all([str(video)], output_dir=out_dir)
|
||||
assert len(results) == 1
|
||||
assert str(cached) in results[0]
|
||||
|
||||
|
||||
def test_transcribe_all_skips_failed(tmp_path):
|
||||
"""transcribe_all() warns and skips files that fail to transcribe."""
|
||||
video = tmp_path / "broken.mp4"
|
||||
video.write_bytes(b"fake")
|
||||
|
||||
def raise_import(*args, **kwargs):
|
||||
raise ImportError("faster_whisper not installed")
|
||||
|
||||
with patch("graphify.transcribe.transcribe", side_effect=RuntimeError("boom")):
|
||||
results = transcribe_all([str(video)], output_dir=tmp_path / "out")
|
||||
|
||||
assert results == []
|
||||
+25
-24
@@ -1,6 +1,6 @@
|
||||
# Reproducible Example
|
||||
|
||||
A small document pipeline — parser, validator, processor, storage, API — with architecture notes and research notes. Seven files, two languages, clear call relationships between modules.
|
||||
A small document pipeline (parser, validator, processor, storage, API) with architecture notes and research notes. Six files, two languages, clear call relationships between modules.
|
||||
|
||||
Run graphify on it and you get a knowledge graph showing how the modules connect, which functions call which, and how the architecture notes relate to the code.
|
||||
|
||||
@@ -8,49 +8,50 @@ Run graphify on it and you get a knowledge graph showing how the modules connect
|
||||
|
||||
```
|
||||
raw/
|
||||
├── parser.py — reads files, detects format, kicks off the pipeline
|
||||
├── validator.py — schema checks, calls processor for text normalization
|
||||
├── processor.py — keyword extraction, cross-reference detection
|
||||
├── storage.py — persists everything, maintains the index
|
||||
├── api.py — HTTP handlers that orchestrate the above four modules
|
||||
├── architecture.md — design decisions and module responsibilities
|
||||
└── notes.md — open questions and tradeoffs
|
||||
├── parser.py reads files, detects format, kicks off the pipeline
|
||||
├── validator.py schema checks, calls processor for text normalization
|
||||
├── processor.py keyword extraction, cross-reference detection
|
||||
├── storage.py persists everything, maintains the index
|
||||
├── api.py HTTP handlers that orchestrate the above four modules
|
||||
├── architecture.md design decisions and module responsibilities
|
||||
└── notes.md open questions and tradeoffs, written informally
|
||||
```
|
||||
|
||||
## How to run
|
||||
## How to run it
|
||||
|
||||
```bash
|
||||
pip install graphifyy
|
||||
|
||||
graphify install # Claude Code
|
||||
graphify install --platform codex # Codex
|
||||
graphify install --platform opencode # OpenCode
|
||||
graphify install --platform claw # OpenClaw
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
Then open your AI coding assistant in this directory and type:
|
||||
Then open Claude Code in this directory and type:
|
||||
|
||||
```
|
||||
/graphify ./raw
|
||||
```
|
||||
|
||||
No PDF or image extraction — runs entirely on AST and markdown with no token cost for semantic extraction.
|
||||
Takes under a minute. No PDF or image extraction, so it runs entirely on AST and markdown parsing with no token cost for semantic extraction.
|
||||
|
||||
## What to expect
|
||||
|
||||
- `api.py` as a hub node connected to all four modules
|
||||
- `storage.py` as the highest-degree god node (everything reads and writes through it)
|
||||
- `parser.py` calling `validator.py` and `storage.py`
|
||||
- `architecture.md` and `notes.md` linked to the code modules they discuss
|
||||
- 2 communities: the four Python modules together, the two markdown files together (or api.py in its own cluster given high connectivity)
|
||||
The graph should show:
|
||||
|
||||
- api.py as a hub node connected to all four modules
|
||||
- parser.py calling validator.py and storage.py
|
||||
- validator.py calling processor.py for normalize_text
|
||||
- processor.py calling storage.py for load_index and save_processed
|
||||
- architecture.md and notes.md linked to the code modules they discuss
|
||||
|
||||
The community detection will likely cluster the four Python modules together and the two markdown files together, or split api.py into its own cluster given its high connectivity.
|
||||
|
||||
God nodes will be storage.py (everything reads and writes through it) and api.py (connects to everything at the top level).
|
||||
|
||||
## After it runs
|
||||
|
||||
Ask questions from your AI coding assistant:
|
||||
Ask questions in Claude Code and it answers from the graph:
|
||||
|
||||
- "what calls storage directly?"
|
||||
- "what is the shortest path between parser and processor?"
|
||||
- "which module has the most connections?"
|
||||
- "what does the architecture doc say about the storage design?"
|
||||
|
||||
The graph lives in `graphify-out/` and persists across sessions.
|
||||
The graph lives in graphify-out/ and persists across sessions.
|
||||
+24
-23
@@ -1,43 +1,44 @@
|
||||
# httpx Corpus Benchmark
|
||||
# httpx Corpus Benchmark — How to Reproduce
|
||||
|
||||
A synthetic 6-file Python codebase modeled after httpx's architecture. Tests graphify on a realistic library with clean layering: exceptions → models → auth/transport → client.
|
||||
A synthetic 6-file Python codebase modeled after httpx's architecture. Tests graphify
|
||||
on a realistic library codebase with clean layering: exceptions → models → auth/transport → client.
|
||||
|
||||
## Corpus (6 files)
|
||||
|
||||
All input files are in `raw/`:
|
||||
|
||||
```
|
||||
raw/
|
||||
├── exceptions.py — HTTPError hierarchy
|
||||
├── models.py — URL, Headers, Cookies, Request, Response
|
||||
├── auth.py — BasicAuth, BearerAuth, DigestAuth, NetRCAuth
|
||||
├── utils.py — header normalization, query params, content-type parsing
|
||||
├── transport.py — ConnectionPool, HTTPTransport, AsyncHTTPTransport, MockTransport
|
||||
└── client.py — Timeout, Limits, BaseClient, Client, AsyncClient
|
||||
├── exceptions.py — full HTTPError hierarchy (RequestError, TransportError, HTTPStatusError, etc.)
|
||||
├── models.py — URL, Headers, Cookies, Request, Response with raise_for_status
|
||||
├── auth.py — BasicAuth, BearerAuth, DigestAuth (challenge-response), NetRCAuth
|
||||
├── utils.py — header normalization, query param flattening, content-type parsing
|
||||
├── transport.py — ConnectionPool, HTTPTransport, AsyncHTTPTransport, MockTransport, ProxyTransport
|
||||
└── client.py — Timeout, Limits, BaseClient, Client (sync), AsyncClient
|
||||
```
|
||||
|
||||
## How to run
|
||||
|
||||
```bash
|
||||
pip install graphifyy
|
||||
|
||||
graphify install # Claude Code
|
||||
graphify install --platform codex # Codex
|
||||
graphify install --platform opencode # OpenCode
|
||||
graphify install --platform claw # OpenClaw
|
||||
```
|
||||
|
||||
Then open your AI coding assistant in this directory and type:
|
||||
|
||||
```
|
||||
pip install graphifyy && graphify install
|
||||
/graphify ./raw
|
||||
```
|
||||
|
||||
Or from the CLI directly:
|
||||
|
||||
```bash
|
||||
pip install graphifyy
|
||||
graphify ./raw
|
||||
```
|
||||
|
||||
## What to expect
|
||||
|
||||
- 144 nodes, 330 edges, 6 communities
|
||||
- God nodes: `Client`, `AsyncClient`, `Response`, `Request`, `BaseClient`, `HTTPTransport`
|
||||
- Surprising connection: `DigestAuth` linked to `Response` — auth.py reads Response to parse WWW-Authenticate headers
|
||||
- Token reduction: ~1x — 6 files fits in a context window, so there is no compression win here
|
||||
- Surprising connections: `DigestAuth` ↔ `Response` (auth.py reads Response to parse WWW-Authenticate)
|
||||
- **~1x token reduction** — 6 files fits in a context window, so there's no compression win here
|
||||
|
||||
The graph value on a small corpus is structural, not compressive: you can see the full dependency graph, identify god nodes, and understand architecture at a glance. Token reduction scales with corpus size — at 52 files (Karpathy benchmark) graphify achieves 71.5x.
|
||||
The graph value on a small corpus is structural, not compressive: you can see the full dependency graph, identify god nodes, and understand architecture at a glance. For token reduction to matter you need 20+ files. At 52 files (Karpathy repos benchmark) graphify achieves 71.5x.
|
||||
|
||||
Run `graphify benchmark worked/httpx/graph.json` to verify the numbers. Actual output is in this folder: `GRAPH_REPORT.md` and `graph.json`. Full eval: `review.md`.
|
||||
Run `graphify benchmark worked/httpx/graph.json` to verify the numbers yourself.
|
||||
Actual output is already in this folder: `GRAPH_REPORT.md` (human-readable) and `graph.json` (full graph data).
|
||||
@@ -1,6 +1,6 @@
|
||||
# Karpathy Repos Benchmark
|
||||
# Karpathy Repos Benchmark — How to Reproduce
|
||||
|
||||
This is the corpus that produced the **71.5x token reduction** benchmark.
|
||||
This is the corpus that produced the 71.5x token reduction benchmark.
|
||||
|
||||
## Corpus (52 files)
|
||||
|
||||
@@ -33,9 +33,9 @@ Put all files into a single folder called `raw/`:
|
||||
|
||||
```
|
||||
raw/
|
||||
├── nanoGPT/
|
||||
├── minGPT/
|
||||
├── micrograd/
|
||||
├── nanoGPT/ (cloned repo)
|
||||
├── minGPT/ (cloned repo)
|
||||
├── micrograd/ (cloned repo)
|
||||
├── attention.pdf
|
||||
├── flashattention.pdf
|
||||
├── flashattention2.pdf
|
||||
@@ -46,20 +46,10 @@ raw/
|
||||
└── moon_mlp.png
|
||||
```
|
||||
|
||||
Install and set up the skill for your platform:
|
||||
|
||||
```bash
|
||||
pip install graphifyy
|
||||
|
||||
graphify install # Claude Code
|
||||
graphify install --platform codex # Codex
|
||||
graphify install --platform opencode # OpenCode
|
||||
graphify install --platform claw # OpenClaw
|
||||
```
|
||||
|
||||
Then open your AI coding assistant in this directory and type:
|
||||
Then in Claude Code:
|
||||
|
||||
```
|
||||
pip install graphifyy && graphify install
|
||||
/graphify ./raw
|
||||
```
|
||||
|
||||
@@ -68,6 +58,6 @@ Then open your AI coding assistant in this directory and type:
|
||||
- ~285 nodes, ~340 edges, ~17 meaningful communities
|
||||
- God nodes: `Value` (micrograd), `GPT` (nanoGPT), `Training Script`, `Layer`
|
||||
- Surprising connections: nanoGPT Block and minGPT Block linked across repos, FlashAttention paper bridging into CausalSelfAttention in both repos
|
||||
- Token reduction: 71.5x vs reading all 52 files directly
|
||||
- Token reduction: 71.5x vs reading all 52 files cold
|
||||
|
||||
Actual output is in this folder: `GRAPH_REPORT.md` and `graph.json`. Full eval with scores: `review.md`.
|
||||
Full eval with scores and analysis: `review.md`
|
||||
@@ -1,43 +1,45 @@
|
||||
# Mixed Corpus Benchmark
|
||||
# Mixed Corpus Benchmark — How to Reproduce
|
||||
|
||||
A small mixed-input corpus: Python source files, a markdown paper with arXiv citations, and one image. Tests graphify on different file types in a single run.
|
||||
A small but realistic mixed-input corpus: Python source files, a markdown paper with
|
||||
arXiv citations, and one image. Tests graphify's ability to handle different file types
|
||||
in a single run.
|
||||
|
||||
## Corpus (5 files)
|
||||
|
||||
All input files are in `raw/`:
|
||||
|
||||
```
|
||||
raw/
|
||||
├── analyze.py — graph analysis module (god_nodes, surprising_connections)
|
||||
├── build.py — graph builder (build_from_json, NetworkX wrapper)
|
||||
├── cluster.py — Leiden community detection (cluster, score_all)
|
||||
├── attention_notes.md — Transformer paper notes (Vaswani et al., 2017) with arXiv citation
|
||||
├── analyze.py — graphify's graph analysis module (god_nodes, surprising_connections, etc.)
|
||||
├── build.py — graphify's graph builder (build_from_json, networkx wrapper)
|
||||
├── cluster.py — graphify's Leiden community detection (cluster, score_all)
|
||||
├── attention_notes.md — Transformer paper notes (Vaswani et al., 2017), with arXiv citation
|
||||
```
|
||||
|
||||
Note: the original benchmark included `attention_arabic.png` (an Arabic-language figure from the Attention paper). PNG files are not stored in this repo. To reproduce with the image, save any diagram from the Attention Is All You Need paper as `raw/attention_arabic.png`.
|
||||
Note: the original benchmark included `attention_arabic.png` (an Arabic-language figure from the
|
||||
Attention paper). PNG files are not stored in this repo. To reproduce with the image, save any
|
||||
diagram or figure from the Attention Is All You Need paper as `raw/attention_arabic.png`.
|
||||
|
||||
## How to run
|
||||
|
||||
```bash
|
||||
pip install graphifyy
|
||||
|
||||
graphify install # Claude Code
|
||||
graphify install --platform codex # Codex
|
||||
graphify install --platform opencode # OpenCode
|
||||
graphify install --platform claw # OpenClaw
|
||||
```
|
||||
|
||||
Then open your AI coding assistant in this directory and type:
|
||||
|
||||
```
|
||||
pip install graphifyy && graphify install
|
||||
/graphify ./raw
|
||||
```
|
||||
|
||||
Or from the CLI directly:
|
||||
|
||||
```bash
|
||||
pip install graphifyy
|
||||
graphify ./raw
|
||||
```
|
||||
|
||||
## What to expect
|
||||
|
||||
- ~20 nodes, ~19 edges from AST alone (3 Python modules)
|
||||
- 3 communities: Graph Analysis, Clustering and Scoring, Graph Building
|
||||
- 3 communities: Graph Analysis, Clustering & Scoring, Graph Building
|
||||
- God nodes: `analyze.py`, `cluster.py`, `build.py`
|
||||
- `attention_notes.md` classified as `paper` (arXiv heuristic fires on `1706.03762`)
|
||||
- If you include the image: 1 extra node describing the figure content via vision
|
||||
- Token reduction: 5.4x
|
||||
|
||||
Actual output is in this folder: `GRAPH_REPORT.md` and `graph.json`. Full eval: `review.md`.
|
||||
Full eval with scores and analysis: `review.md`
|
||||
Reference in new issue
Block a user