Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d8cffef47 | ||
|
|
29c639d97d | ||
|
|
11dff7e9b3 | ||
|
|
ec4f6845aa | ||
|
|
1a50f2d12b | ||
|
|
8dbf953016 | ||
|
|
dd8235e0b5 | ||
|
|
23d88c55b0 | ||
|
|
30a66ec1f4 | ||
|
|
0dc125d09a | ||
|
|
6a3b4bb39b | ||
|
|
1cc54b3bbf | ||
|
|
b64c231467 | ||
|
|
f4c3c551e1 | ||
|
|
74e192db00 | ||
|
|
312ba0dd1e | ||
|
|
8a0dd45711 | ||
|
|
785c9f4dd7 |
No files matched your search
@@ -19,3 +19,6 @@ graphify-out/
|
||||
.claude/
|
||||
skills/
|
||||
docs/superpowers/
|
||||
.vscode/
|
||||
openspec/
|
||||
uv.lock
|
||||
@@ -2,6 +2,46 @@
|
||||
|
||||
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
|
||||
|
||||
## 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)
|
||||
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
# 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
@@ -0,0 +1,282 @@
|
||||
# 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,14 +1,14 @@
|
||||
# graphify
|
||||
|
||||
[English](README.md) | [简体中文](README.zh-CN.md)
|
||||
[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)
|
||||
|
||||
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, OpenClaw, or Factory Droid - it reads your files, builds a knowledge graph, and gives you back structure you didn't know was there. Understand a codebase faster. Find the "why" behind architectural decisions.
|
||||
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, 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.
|
||||
|
||||
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. 19 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).
|
||||
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. 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).
|
||||
|
||||
> 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.
|
||||
|
||||
@@ -46,7 +46,7 @@ Every relationship is tagged `EXTRACTED` (found directly in source), `INFERRED`
|
||||
|
||||
## Install
|
||||
|
||||
**Requires:** Python 3.10+ and one of: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [OpenClaw](https://openclaw.ai), or [Factory Droid](https://factory.ai)
|
||||
**Requires:** Python 3.10+ and one of: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), or [Trae](https://trae.ai)
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
@@ -64,8 +64,10 @@ pip install graphifyy && graphify install
|
||||
| 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 users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw uses sequential extraction (parallel agent support is still early on that platform).
|
||||
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw uses sequential extraction (parallel agent support is still early on that platform). 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:
|
||||
|
||||
@@ -86,10 +88,14 @@ After building a graph, run this once in your project:
|
||||
| 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** does two things: writes a `CLAUDE.md` section telling Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs a **PreToolUse hook** (`settings.json`) that fires before every Glob and Grep call. If a knowledge graph exists, Claude sees: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ — so Claude navigates via the graph instead of grepping through every file.
|
||||
|
||||
**Codex, OpenCode, OpenClaw, Factory Droid** write the same rules to `AGENTS.md` in your project root. These platforms don't support PreToolUse hooks, so AGENTS.md is the always-on mechanism.
|
||||
**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, OpenClaw, Factory Droid, Trae** write the same rules to `AGENTS.md` in your project root. These platforms don't support PreToolUse hooks, so AGENTS.md is the always-on mechanism.
|
||||
|
||||
Uninstall with the matching uninstall command (e.g. `graphify claude uninstall`).
|
||||
|
||||
@@ -101,6 +107,42 @@ The always-on hook surfaces `GRAPH_REPORT.md` — a one-page summary of god node
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```text
|
||||
Use this graph query output to answer the question. Prefer the graph structure
|
||||
over guessing, and cite the source files when possible.
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```bash
|
||||
python -m graphify.serve graphify-out/graph.json
|
||||
```
|
||||
|
||||
That gives the assistant structured graph access for repeated queries such as
|
||||
`query_graph`, `get_node`, `get_neighbors`, and `shortest_path`.
|
||||
|
||||
<details>
|
||||
<summary>Manual install (curl)</summary>
|
||||
|
||||
@@ -162,6 +204,10 @@ 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
|
||||
|
||||
# query the graph directly from the terminal (no AI assistant needed)
|
||||
graphify query "what connects attention to the optimizer?"
|
||||
@@ -174,7 +220,7 @@ Works with any mix of file types:
|
||||
|
||||
| Type | Extensions | Extraction |
|
||||
|------|-----------|------------|
|
||||
| Code | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm` | AST via tree-sitter + call-graph + docstring/comment rationale |
|
||||
| Code | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl` | 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 |
|
||||
@@ -222,9 +268,13 @@ graphify sends file contents to your AI coding assistant's underlying model API
|
||||
|
||||
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)
|
||||
[](https://starchart.cc/safishamsi/graphify)
|
||||
|
||||
<details>
|
||||
<summary>Contributing</summary>
|
||||
|
||||
+16
-5
@@ -1,11 +1,11 @@
|
||||
# graphify
|
||||
|
||||
[English](README.md) | [简体中文](README.zh-CN.md)
|
||||
[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 中输入 `/graphify`,它会读取你的文件、构建知识图谱,并把原本不明显的结构关系还给你。更快理解代码库,找到架构决策背后的“为什么”。
|
||||
**一个面向 AI 编码助手的技能。** 在 Claude Code、Codex、OpenCode、OpenClaw、Factory Droid 或 Trae 中输入 `/graphify`,它会读取你的文件、构建知识图谱,并把原本不明显的结构关系还给你。更快理解代码库,找到架构决策背后的"为什么"。
|
||||
|
||||
完全多模态。你可以直接丢进去代码、PDF、Markdown、截图、流程图、白板照片,甚至其他语言的图片 —— graphify 会用 Claude vision 从这些内容中提取概念和关系,并把它们连接到同一张图里。
|
||||
|
||||
@@ -33,7 +33,7 @@ graphify 分两轮执行。第一轮是确定性的 AST 提取,对代码文件
|
||||
|
||||
## 安装
|
||||
|
||||
**要求:** Python 3.10+,并且使用以下平台之一:[Claude Code](https://claude.ai/code)、[Codex](https://openai.com/codex)、[OpenCode](https://opencode.ai) 或 [OpenClaw](https://openclaw.ai)
|
||||
**要求:** 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
|
||||
@@ -49,8 +49,11 @@ pip install graphifyy && 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 支持还比较早期,所以使用顺序提取。
|
||||
Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `multi_agent = true`,这样才能并行提取。OpenClaw 目前的并行 agent 支持还比较早期,所以使用顺序提取。Trae 使用 Agent 工具进行并行子代理调度,**不支持** PreToolUse hook,因此 AGENTS.md 是其常驻机制。
|
||||
|
||||
然后打开你的 AI 编码助手,输入:
|
||||
|
||||
@@ -68,6 +71,9 @@ Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `mult
|
||||
| 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`
|
||||
@@ -75,7 +81,7 @@ Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `mult
|
||||
|
||||
如果知识图谱存在,Claude 会先看到:_"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ —— 这样 Claude 会优先按图谱导航,而不是一上来就 grep 整个项目。
|
||||
|
||||
**Codex、OpenCode、OpenClaw** 会把同样的规则写进项目根目录的 `AGENTS.md`。这些平台没有 PreToolUse hook,所以 `AGENTS.md` 是它们的常驻机制。
|
||||
**Codex、OpenCode、OpenClaw、Factory Droid、Trae** 会把同样的规则写进项目根目录的 `AGENTS.md`。这些平台没有 PreToolUse hook,所以 `AGENTS.md` 是它们的常驻机制。
|
||||
|
||||
卸载时使用对应平台的 uninstall 命令即可(例如 `graphify claude uninstall`)。
|
||||
|
||||
@@ -146,6 +152,11 @@ 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
|
||||
```
|
||||
|
||||
支持混合文件类型:
|
||||
|
||||
+48
-5
@@ -72,6 +72,16 @@ _PLATFORM_CONFIG: dict[str, dict] = {
|
||||
"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",
|
||||
@@ -160,7 +170,7 @@ _CODEX_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."}}' """
|
||||
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"
|
||||
),
|
||||
}
|
||||
@@ -373,11 +383,17 @@ def main() -> None:
|
||||
print("Usage: graphify <command>")
|
||||
print()
|
||||
print("Commands:")
|
||||
print(" install [--platform P] copy skill to platform config dir (claude|windows|codex|opencode|claw|droid)")
|
||||
print(" install [--platform P] copy skill to platform config dir (claude|windows|codex|opencode|claw|droid|trae|trae-cn)")
|
||||
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(" 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")
|
||||
@@ -391,7 +407,11 @@ def main() -> None:
|
||||
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(" 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()
|
||||
return
|
||||
|
||||
@@ -421,7 +441,7 @@ def main() -> None:
|
||||
else:
|
||||
print("Usage: graphify claude [install|uninstall]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
elif cmd in ("codex", "opencode", "claw", "droid"):
|
||||
elif cmd in ("codex", "opencode", "claw", "droid", "trae", "trae-cn"):
|
||||
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
if subcmd == "install":
|
||||
_agents_install(Path("."), cmd)
|
||||
@@ -488,7 +508,11 @@ def main() -> None:
|
||||
try:
|
||||
import json as _json
|
||||
import networkx as _nx
|
||||
G = json_graph.node_link_graph(_json.loads(gp.read_text(encoding="utf-8")), edges="links")
|
||||
_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)
|
||||
@@ -500,6 +524,25 @@ def main() -> None:
|
||||
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"
|
||||
|
||||
+5
-8
@@ -109,19 +109,16 @@ def _is_concept_node(G: nx.Graph, node_id: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
_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"}
|
||||
from graphify.detect import CODE_EXTENSIONS, DOC_EXTENSIONS, PAPER_EXTENSIONS, IMAGE_EXTENSIONS
|
||||
|
||||
|
||||
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"
|
||||
|
||||
|
||||
@@ -76,7 +76,10 @@ def run_benchmark(
|
||||
Returns dict with: corpus_tokens, avg_query_tokens, reduction_ratio, per_question
|
||||
"""
|
||||
data = json.loads(Path(graph_path).read_text())
|
||||
G = json_graph.node_link_graph(data, edges="links")
|
||||
try:
|
||||
G = json_graph.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
G = json_graph.node_link_graph(data)
|
||||
|
||||
if corpus_words is None:
|
||||
# Rough estimate: each node label is ~3 words, plus source context
|
||||
|
||||
+35
-22
@@ -1,44 +1,57 @@
|
||||
"""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
|
||||
return leiden(G)
|
||||
# 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
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Fallback: networkx louvain (available since networkx 2.7)
|
||||
# max_level=10 and threshold=1e-4 prevent indefinite hangs on large sparse graphs
|
||||
# while producing equivalent community quality to the defaults on typical corpora
|
||||
communities = nx.community.louvain_communities(G, seed=42, max_level=10, threshold=1e-4)
|
||||
# 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)
|
||||
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
|
||||
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ class FileType(str, Enum):
|
||||
|
||||
_MANIFEST_PATH = "graphify-out/manifest.json"
|
||||
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.tsx', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm'}
|
||||
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'}
|
||||
DOC_EXTENSIONS = {'.md', '.txt', '.rst'}
|
||||
PAPER_EXTENSIONS = {'.pdf'}
|
||||
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
|
||||
|
||||
+22
-3
@@ -183,9 +183,28 @@ 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 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 if (hoveredNodeId === null) {{
|
||||
document.getElementById('info-content').innerHTML = '<span class="empty">Click a node to inspect it</span>';
|
||||
}}
|
||||
}});
|
||||
|
||||
const searchInput = document.getElementById('search');
|
||||
@@ -365,7 +384,7 @@ def to_html(
|
||||
legend_data = []
|
||||
for cid in sorted((community_labels or {}).keys()):
|
||||
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
|
||||
lbl = (community_labels or {}).get(cid, f"Community {cid}")
|
||||
lbl = _html.escape(sanitize_label((community_labels or {}).get(cid, f"Community {cid}")))
|
||||
n = len(communities.get(cid, []))
|
||||
legend_data.append({"cid": cid, "color": color, "label": lbl, "count": n})
|
||||
|
||||
|
||||
+221
-1
@@ -1151,6 +1151,218 @@ def extract_swift(path: Path) -> dict:
|
||||
return _extract_generic(path, _SWIFT_CONFIG)
|
||||
|
||||
|
||||
# ── Julia extractor (custom walk) ────────────────────────────────────────────
|
||||
|
||||
def extract_julia(path: Path) -> dict:
|
||||
"""Extract modules, structs, functions, imports, and calls from a .jl file."""
|
||||
try:
|
||||
import tree_sitter_julia as tsjulia
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree-sitter-julia not installed"}
|
||||
|
||||
try:
|
||||
language = Language(tsjulia.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
function_bodies: list[tuple[str, object]] = []
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0) -> None:
|
||||
edges.append({
|
||||
"source": src,
|
||||
"target": tgt,
|
||||
"relation": relation,
|
||||
"confidence": confidence,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
"weight": weight,
|
||||
})
|
||||
|
||||
file_nid = _make_id(stem)
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
def _func_name_from_signature(sig_node) -> str | None:
|
||||
"""Extract function name from a Julia signature node (call_expression > identifier)."""
|
||||
for child in sig_node.children:
|
||||
if child.type == "call_expression":
|
||||
callee = child.children[0] if child.children else None
|
||||
if callee and callee.type == "identifier":
|
||||
return _read_text(callee, source)
|
||||
return None
|
||||
|
||||
def walk_calls(body_node, func_nid: str) -> None:
|
||||
if body_node is None:
|
||||
return
|
||||
t = body_node.type
|
||||
if t in ("function_definition", "short_function_definition"):
|
||||
return
|
||||
if t == "call_expression" and body_node.children:
|
||||
callee = body_node.children[0]
|
||||
# Direct call: foo(...)
|
||||
if callee.type == "identifier":
|
||||
callee_name = _read_text(callee, source)
|
||||
target_nid = _make_id(stem, callee_name)
|
||||
add_edge(func_nid, target_nid, "calls", body_node.start_point[0] + 1,
|
||||
confidence="EXTRACTED")
|
||||
# Method call: obj.method(...)
|
||||
elif callee.type == "field_expression" and len(callee.children) >= 3:
|
||||
method_node = callee.children[-1]
|
||||
method_name = _read_text(method_node, source)
|
||||
target_nid = _make_id(stem, method_name)
|
||||
add_edge(func_nid, target_nid, "calls", body_node.start_point[0] + 1,
|
||||
confidence="EXTRACTED")
|
||||
for child in body_node.children:
|
||||
walk_calls(child, func_nid)
|
||||
|
||||
def walk(node, scope_nid: str) -> None:
|
||||
t = node.type
|
||||
|
||||
# Module
|
||||
if t == "module_definition":
|
||||
name_node = next((c for c in node.children if c.type == "identifier"), None)
|
||||
if name_node:
|
||||
mod_name = _read_text(name_node, source)
|
||||
mod_nid = _make_id(stem, mod_name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(mod_nid, mod_name, line)
|
||||
add_edge(file_nid, mod_nid, "defines", line)
|
||||
for child in node.children:
|
||||
walk(child, mod_nid)
|
||||
return
|
||||
|
||||
# Struct (struct / mutable struct — both map to struct_definition in tree-sitter-julia)
|
||||
if t == "struct_definition":
|
||||
# type_head may contain: identifier (simple) or binary_expression (Foo <: Bar)
|
||||
type_head = next((c for c in node.children if c.type == "type_head"), None)
|
||||
if type_head:
|
||||
bin_expr = next((c for c in type_head.children if c.type == "binary_expression"), None)
|
||||
if bin_expr:
|
||||
# First identifier is the struct name, last is the supertype
|
||||
identifiers = [c for c in bin_expr.children if c.type == "identifier"]
|
||||
if identifiers:
|
||||
struct_name = _read_text(identifiers[0], source)
|
||||
struct_nid = _make_id(stem, struct_name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(struct_nid, struct_name, line)
|
||||
add_edge(scope_nid, struct_nid, "defines", line)
|
||||
if len(identifiers) >= 2:
|
||||
super_name = _read_text(identifiers[-1], source)
|
||||
add_edge(struct_nid, _make_id(stem, super_name), "inherits",
|
||||
line, confidence="EXTRACTED")
|
||||
else:
|
||||
name_node = next((c for c in type_head.children if c.type == "identifier"), None)
|
||||
if name_node:
|
||||
struct_name = _read_text(name_node, source)
|
||||
struct_nid = _make_id(stem, struct_name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(struct_nid, struct_name, line)
|
||||
add_edge(scope_nid, struct_nid, "defines", line)
|
||||
return
|
||||
|
||||
# Abstract type
|
||||
if t == "abstract_definition":
|
||||
# type_head > identifier
|
||||
type_head = next((c for c in node.children if c.type == "type_head"), None)
|
||||
if type_head:
|
||||
name_node = next((c for c in type_head.children if c.type == "identifier"), None)
|
||||
if name_node:
|
||||
abs_name = _read_text(name_node, source)
|
||||
abs_nid = _make_id(stem, abs_name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(abs_nid, abs_name, line)
|
||||
add_edge(scope_nid, abs_nid, "defines", line)
|
||||
return
|
||||
|
||||
# Function: function foo(...) ... end
|
||||
if t == "function_definition":
|
||||
sig_node = next((c for c in node.children if c.type == "signature"), None)
|
||||
if sig_node:
|
||||
func_name = _func_name_from_signature(sig_node)
|
||||
if func_name:
|
||||
func_nid = _make_id(stem, func_name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(func_nid, f"{func_name}()", line)
|
||||
add_edge(scope_nid, func_nid, "defines", line)
|
||||
function_bodies.append((func_nid, node))
|
||||
return
|
||||
|
||||
# Short function: foo(x) = expr
|
||||
if t == "assignment":
|
||||
lhs = node.children[0] if node.children else None
|
||||
if lhs and lhs.type == "call_expression" and lhs.children:
|
||||
callee = lhs.children[0]
|
||||
if callee.type == "identifier":
|
||||
func_name = _read_text(callee, source)
|
||||
func_nid = _make_id(stem, func_name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(func_nid, f"{func_name}()", line)
|
||||
add_edge(scope_nid, func_nid, "defines", line)
|
||||
# Only walk the RHS (index 2 after lhs and operator) to avoid self-loops
|
||||
rhs = node.children[-1] if len(node.children) >= 3 else None
|
||||
if rhs:
|
||||
function_bodies.append((func_nid, rhs))
|
||||
return
|
||||
|
||||
# Using / Import
|
||||
if t in ("using_statement", "import_statement"):
|
||||
line = node.start_point[0] + 1
|
||||
for child in node.children:
|
||||
if child.type == "identifier":
|
||||
mod_name = _read_text(child, source)
|
||||
imp_nid = _make_id(mod_name)
|
||||
add_node(imp_nid, mod_name, line)
|
||||
add_edge(scope_nid, imp_nid, "imports", line)
|
||||
elif child.type == "selected_import":
|
||||
identifiers = [c for c in child.children if c.type == "identifier"]
|
||||
if identifiers:
|
||||
pkg_name = _read_text(identifiers[0], source)
|
||||
pkg_nid = _make_id(pkg_name)
|
||||
add_node(pkg_nid, pkg_name, line)
|
||||
add_edge(scope_nid, pkg_nid, "imports", line)
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
walk(child, scope_nid)
|
||||
|
||||
walk(root, file_nid)
|
||||
|
||||
for func_nid, body_node in function_bodies:
|
||||
# For function_definition nodes, walk children directly to avoid
|
||||
# the boundary check returning early on the top-level node itself.
|
||||
# Skip the "signature" child — it contains the function's own call_expression
|
||||
# which would create a self-loop.
|
||||
if body_node.type == "function_definition":
|
||||
for child in body_node.children:
|
||||
if child.type != "signature":
|
||||
walk_calls(child, func_nid)
|
||||
else:
|
||||
walk_calls(body_node, func_nid)
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
|
||||
|
||||
# ── Go extractor (custom walk) ────────────────────────────────────────────────
|
||||
|
||||
def extract_go(path: Path) -> dict:
|
||||
@@ -2362,6 +2574,7 @@ def extract(paths: list[Path]) -> dict:
|
||||
_DISPATCH: dict[str, Any] = {
|
||||
".py": extract_python,
|
||||
".js": extract_js,
|
||||
".jsx": extract_js,
|
||||
".ts": extract_js,
|
||||
".tsx": extract_js,
|
||||
".go": extract_go,
|
||||
@@ -2388,9 +2601,14 @@ def extract(paths: list[Path]) -> dict:
|
||||
".exs": extract_elixir,
|
||||
".m": extract_objc,
|
||||
".mm": extract_objc,
|
||||
".jl": extract_julia,
|
||||
}
|
||||
|
||||
for path in paths:
|
||||
total = len(paths)
|
||||
_PROGRESS_INTERVAL = 100
|
||||
for i, path in enumerate(paths):
|
||||
if total >= _PROGRESS_INTERVAL and i % _PROGRESS_INTERVAL == 0 and i > 0:
|
||||
print(f" AST extraction: {i}/{total} files ({i * 100 // total}%)", flush=True)
|
||||
extractor = _DISPATCH.get(path.suffix)
|
||||
if extractor is None:
|
||||
continue
|
||||
@@ -2402,6 +2620,8 @@ def extract(paths: list[Path]) -> dict:
|
||||
if "error" not in result:
|
||||
save_cached(path, result, root)
|
||||
per_file.append(result)
|
||||
if total >= _PROGRESS_INTERVAL:
|
||||
print(f" AST extraction: {total}/{total} files (100%)", flush=True)
|
||||
|
||||
all_nodes: list[dict] = []
|
||||
all_edges: list[dict] = []
|
||||
|
||||
+26
-2
@@ -8,6 +8,28 @@ _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_SCRIPT = """\
|
||||
# graphify-hook-start
|
||||
# Auto-rebuilds the knowledge graph after each commit (code files only, no LLM needed).
|
||||
@@ -18,8 +40,9 @@ if [ -z "$CHANGED" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
""" + _PYTHON_DETECT + """
|
||||
export GRAPHIFY_CHANGED="$CHANGED"
|
||||
python3 -c "
|
||||
$GRAPHIFY_PYTHON -c "
|
||||
import os, sys
|
||||
from pathlib import Path
|
||||
|
||||
@@ -67,8 +90,9 @@ if [ ! -d "graphify-out" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
""" + _PYTHON_DETECT + """
|
||||
echo "[graphify] Branch switched - rebuilding knowledge graph (code files)..."
|
||||
python3 -c "
|
||||
$GRAPHIFY_PYTHON -c "
|
||||
from graphify.watch import _rebuild_code
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
+4
-1
@@ -12,7 +12,10 @@ def _load_graph(graph_path: str) -> nx.Graph:
|
||||
try:
|
||||
safe = validate_graph_path(graph_path)
|
||||
data = json.loads(safe.read_text())
|
||||
return json_graph.node_link_graph(data, edges="links")
|
||||
try:
|
||||
return json_graph.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
return json_graph.node_link_graph(data)
|
||||
except (ValueError, FileNotFoundError) as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
+11
-40
@@ -62,12 +62,16 @@ 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 || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
"$PYTHON" -c "import graphify" 2>/dev/null || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
mkdir -p graphify-out
|
||||
# Write interpreter path for all subsequent steps
|
||||
$PYTHON -c "import sys; open('.graphify_python', 'w').write(sys.executable)"
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
@@ -172,7 +176,7 @@ Only dispatch subagents for files listed in `.graphify_uncached.txt`. If all fil
|
||||
|
||||
**Step B1 - Split into chunks**
|
||||
|
||||
Load files from `.graphify_uncached.txt`.
|
||||
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.
|
||||
|
||||
**Step B2 - Sequential extraction (OpenClaw)**
|
||||
|
||||
@@ -590,7 +594,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_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_python
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -890,18 +894,7 @@ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`,
|
||||
After writing the answer, save it back into the graph so it improves future queries:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
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/')
|
||||
"
|
||||
$(cat .graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -976,18 +969,7 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
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/')
|
||||
"
|
||||
$(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
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1053,18 +1035,7 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
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/')
|
||||
"
|
||||
$(cat .graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
+10
-40
@@ -62,12 +62,15 @@ 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 || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
"$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)"
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
@@ -176,7 +179,7 @@ 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).
|
||||
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.
|
||||
|
||||
**Step B2 - Dispatch ALL subagents in a single message (Codex)**
|
||||
|
||||
@@ -647,7 +650,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_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_python
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -947,18 +950,7 @@ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`,
|
||||
After writing the answer, save it back into the graph so it improves future queries:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
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/')
|
||||
"
|
||||
$(cat .graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -1033,18 +1025,7 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
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/')
|
||||
"
|
||||
$(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
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1110,18 +1091,7 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
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/')
|
||||
"
|
||||
$(cat .graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
+11
-40
@@ -62,12 +62,16 @@ 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 || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
"$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)"
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
@@ -176,7 +180,7 @@ 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).
|
||||
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.
|
||||
|
||||
**Step B2 - Dispatch ALL subagents in a single message (Factory Droid)**
|
||||
|
||||
@@ -643,7 +647,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_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_python
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -943,18 +947,7 @@ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`,
|
||||
After writing the answer, save it back into the graph so it improves future queries:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
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/')
|
||||
"
|
||||
$(cat .graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -1029,18 +1022,7 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
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/')
|
||||
"
|
||||
$(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
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1106,18 +1088,7 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
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/')
|
||||
"
|
||||
$(cat .graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
+11
-40
@@ -62,12 +62,16 @@ 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 || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
"$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)"
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
@@ -176,7 +180,7 @@ 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).
|
||||
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.
|
||||
|
||||
**Step B2 - Dispatch ALL subagents in a single message (OpenCode)**
|
||||
|
||||
@@ -642,7 +646,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_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_python
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -942,18 +946,7 @@ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`,
|
||||
After writing the answer, save it back into the graph so it improves future queries:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
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/')
|
||||
"
|
||||
$(cat .graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -1028,18 +1021,7 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
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/')
|
||||
"
|
||||
$(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
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1105,18 +1087,7 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
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/')
|
||||
"
|
||||
$(cat .graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+17
-37
@@ -637,7 +637,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)')
|
||||
"
|
||||
Remove-Item -ErrorAction SilentlyContinue .graphify_detect.json, .graphify_extract.json, .graphify_ast.json, .graphify_semantic.json, .graphify_analysis.json, .graphify_labels.json, .graphify_python
|
||||
Remove-Item -ErrorAction SilentlyContinue .graphify_detect.json, .graphify_extract.json, .graphify_ast.json, .graphify_semantic.json, .graphify_analysis.json, .graphify_labels.json
|
||||
Remove-Item -ErrorAction SilentlyContinue graphify-out/.needs_update
|
||||
```
|
||||
|
||||
@@ -937,18 +937,7 @@ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`,
|
||||
After writing the answer, save it back into the graph so it improves future queries:
|
||||
|
||||
```powershell
|
||||
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/')
|
||||
"
|
||||
python -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -1023,18 +1012,7 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```powershell
|
||||
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/')
|
||||
"
|
||||
python -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1100,18 +1078,7 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```powershell
|
||||
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/')
|
||||
"
|
||||
python -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1202,6 +1169,19 @@ graphify claude uninstall # remove the section
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### PowerShell 5.1: Vertical scrolling stops working
|
||||
|
||||
If vertical scrolling breaks in PowerShell after running graphify, this is caused by ANSI escape sequences from the `graspologic` library. Graphify v0.3.10+ suppresses this output, but if you still see the issue:
|
||||
|
||||
1. **Upgrade graphify**: `pip install --upgrade graphifyy`
|
||||
2. **Use Windows Terminal** instead of the legacy PowerShell console — Windows Terminal handles ANSI codes correctly
|
||||
3. **Reset your terminal**: close and reopen PowerShell
|
||||
4. **Skip graspologic**: uninstall it (`pip uninstall graspologic`) and graphify will fall back to NetworkX's built-in Louvain algorithm, which produces no ANSI output
|
||||
|
||||
---
|
||||
|
||||
## Honesty Rules
|
||||
|
||||
- Never invent an edge. If unsure, use AMBIGUOUS.
|
||||
|
||||
+29
-41
@@ -64,13 +64,16 @@ 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 || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
# Write interpreter path for all subsequent steps
|
||||
$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 (persists across invocations)
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
@@ -179,7 +182,7 @@ Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt
|
||||
|
||||
**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).
|
||||
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.
|
||||
|
||||
**Step B2 - Dispatch ALL subagents in a single message**
|
||||
|
||||
@@ -647,7 +650,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 graphify-out/.graphify_python
|
||||
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-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -680,6 +683,24 @@ 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.
|
||||
@@ -955,18 +976,7 @@ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`,
|
||||
After writing the answer, save it back into the graph so it improves future queries:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.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/')
|
||||
"
|
||||
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -1041,18 +1051,7 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.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/')
|
||||
"
|
||||
$(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
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1118,18 +1117,7 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.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/')
|
||||
"
|
||||
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
+8
-18
@@ -5,17 +5,10 @@ import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
_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",
|
||||
}
|
||||
from graphify.detect import CODE_EXTENSIONS, DOC_EXTENSIONS, PAPER_EXTENSIONS, IMAGE_EXTENSIONS
|
||||
|
||||
_CODE_EXTENSIONS = {
|
||||
".py", ".ts", ".js", ".go", ".rs", ".java", ".cpp", ".c", ".rb", ".swift", ".kt",
|
||||
".cs", ".scala", ".php", ".cc", ".cxx", ".hpp", ".h", ".kts",
|
||||
}
|
||||
_WATCHED_EXTENSIONS = CODE_EXTENSIONS | DOC_EXTENSIONS | PAPER_EXTENSIONS | IMAGE_EXTENSIONS
|
||||
_CODE_EXTENSIONS = CODE_EXTENSIONS
|
||||
|
||||
|
||||
def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
@@ -24,19 +17,16 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
Returns True on success, False on error.
|
||||
"""
|
||||
try:
|
||||
from graphify.extract import collect_files, extract
|
||||
from graphify.extract import extract
|
||||
from graphify.detect import detect, FileType
|
||||
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
|
||||
|
||||
code_files = collect_files(watch_path, follow_symlinks=follow_symlinks)
|
||||
code_files = [
|
||||
f for f in code_files
|
||||
if "graphify-out" not in f.parts
|
||||
and "__pycache__" not in f.parts
|
||||
]
|
||||
detected = detect(watch_path, follow_symlinks=follow_symlinks)
|
||||
code_files = [Path(f) for f in detected[FileType.CODE]]
|
||||
|
||||
if not code_files:
|
||||
print("[graphify watch] No code files found - nothing to rebuild.")
|
||||
@@ -47,7 +37,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": 0, # not needed during watch rebuild
|
||||
"total_words": detected.get("total_words", 0),
|
||||
}
|
||||
|
||||
G = build_from_json(result)
|
||||
|
||||
+4
-3
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "graphifyy"
|
||||
version = "0.3.14"
|
||||
version = "0.3.18"
|
||||
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, OpenClaw) - turn any folder of code, docs, papers, or images into a queryable knowledge graph"
|
||||
readme = "README.md"
|
||||
license = { file = "LICENSE" }
|
||||
@@ -12,7 +12,7 @@ keywords = ["claude", "claude-code", "codex", "opencode", "knowledge-graph", "ra
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"networkx",
|
||||
"tree-sitter",
|
||||
"tree-sitter>=0.21",
|
||||
"tree-sitter-python",
|
||||
"tree-sitter-javascript",
|
||||
"tree-sitter-typescript",
|
||||
@@ -32,6 +32,7 @@ dependencies = [
|
||||
"tree-sitter-powershell",
|
||||
"tree-sitter-elixir",
|
||||
"tree-sitter-objc",
|
||||
"tree-sitter-julia",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
@@ -56,4 +57,4 @@ where = ["."]
|
||||
include = ["graphify*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-claw.md", "skill-windows.md"]
|
||||
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md"]
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
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
|
||||
@@ -137,6 +137,15 @@ 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,4 +1,5 @@
|
||||
import json
|
||||
import sys
|
||||
import networkx as nx
|
||||
from pathlib import Path
|
||||
from graphify.build import build_from_json
|
||||
@@ -50,3 +51,26 @@ 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}"
|
||||
+26
-2
@@ -9,6 +9,10 @@ PLATFORMS = {
|
||||
"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",),
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +42,26 @@ def test_install_claw(tmp_path):
|
||||
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")
|
||||
@@ -67,10 +91,10 @@ def test_claw_skill_is_sequential():
|
||||
|
||||
|
||||
def test_all_skill_files_exist_in_package():
|
||||
"""All four platform skill files must be present in the installed 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"):
|
||||
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}"
|
||||
|
||||
|
||||
|
||||
+63
-2
@@ -1,11 +1,11 @@
|
||||
"""Tests for language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Go."""
|
||||
"""Tests for language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Go, Julia."""
|
||||
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_swift, extract_go, extract_julia,
|
||||
)
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
@@ -447,3 +447,64 @@ def test_go_receiver_uses_pkg_scope():
|
||||
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}"
|
||||
Reference in new issue
Block a user