Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1184e7d4d5 | ||
|
|
d3c7f950d5 | ||
|
|
5f02b3dfe1 | ||
|
|
5164d972ed | ||
|
|
6dc07e5f99 | ||
|
|
ccdd465a08 | ||
|
|
90fac738e2 | ||
|
|
83c2f4245c | ||
|
|
b37f187767 | ||
|
|
6fe4c01bb8 | ||
|
|
a7fc2493f0 | ||
|
|
494f519bf4 | ||
|
|
d23ae1774d | ||
|
|
e6fefa8a2c | ||
|
|
0f11f6a32d | ||
|
|
e8b8e2039d | ||
|
|
e4bc87a284 | ||
|
|
0a31c0862b | ||
|
|
2a8b6c16ad | ||
|
|
014758f61d | ||
|
|
5617a7d285 | ||
|
|
154919bb64 | ||
|
|
3baf316044 | ||
|
|
0fee55726d | ||
|
|
c488808842 | ||
|
|
546fc0b346 | ||
|
|
5ae2be8ca7 | ||
|
|
fd2cc8d8a7 | ||
|
|
ef06d7d8d9 | ||
|
|
93b8ec3cde | ||
|
|
e98c1b6297 | ||
|
|
a4ae70892a | ||
|
|
a1be5abb24 | ||
|
|
0061b36c29 | ||
|
|
c88528dfa3 | ||
|
|
a7f8cab1a9 | ||
|
|
fa702bd69f | ||
|
|
1cd52f191e | ||
|
|
d7a54d7e14 | ||
|
|
8708333484 | ||
|
|
a7d1969f02 | ||
|
|
258eff3e9f | ||
|
|
a7f910667d | ||
|
|
cf7f42d3e7 | ||
|
|
24bcd6d448 |
No files matched your search
@@ -2,9 +2,9 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["v1", "v2", "v3", "main"]
|
||||
branches: ["v1", "v2", "main"]
|
||||
pull_request:
|
||||
branches: ["v1", "v2", "v3", "main"]
|
||||
branches: ["v1", "v2", "main"]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
|
||||
@@ -15,7 +15,3 @@ build/
|
||||
.graphify/
|
||||
graphify-out/
|
||||
.graphify_*.json
|
||||
.graphify_python
|
||||
.claude/
|
||||
skills/
|
||||
docs/superpowers/
|
||||
@@ -1,28 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
|
||||
|
||||
## 0.3.0 (2026-04-06)
|
||||
|
||||
- Add: multi-platform support — Codex (`skill-codex.md`), OpenCode (`skill-opencode.md`), OpenClaw (`skill-claw.md`)
|
||||
- Add: `graphify install --platform <codex|opencode|claw>` routes skill to correct config directory
|
||||
- Add: `graphify codex install` / `opencode install` / `claw install` — writes AGENTS.md for always-on graph-first behaviour
|
||||
- Add: `graphify claude uninstall` / `codex uninstall` / `opencode uninstall` / `claw uninstall`
|
||||
- Add: MIT license
|
||||
- Fix: `build()` was silently dropping hyperedges when merging multiple extractions
|
||||
- Refactor: `extract.py` 2527 → 1588 lines — replaced 12 copy-pasted language extractors with `LanguageConfig` dataclass + `_extract_generic()`
|
||||
- Docs: clustering is graph-topology-based (no embeddings) — explained in README
|
||||
- Docs: all missing flags documented (`--cluster-only`, `--no-viz`, `--neo4j-push`, `query --dfs`, `query --budget`, `add --author`, `add --contributor`)
|
||||
|
||||
## 0.2.2 (2026-04-06)
|
||||
|
||||
- Add: `graphify claude install` — writes graphify section to local CLAUDE.md + PreToolUse hook in `.claude/settings.json`
|
||||
- Add: `graphify claude uninstall` — removes section and hook
|
||||
- Add: `graphify hook install` — installs post-commit and post-checkout git hooks (platform-agnostic)
|
||||
- Add: `graphify hook uninstall` / `hook status`
|
||||
- Add: `graphify benchmark` CLI command
|
||||
- Fix: node deduplication documented at all three layers
|
||||
|
||||
## 0.1.8 (2026-04-05)
|
||||
|
||||
- Fix: follow-up questions now check for wiki first (graphify-out/wiki/index.md) before falling back to graph.json
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Safi Shamsi
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,11 +1,9 @@
|
||||
# graphify
|
||||
|
||||
[English](README.md) | [简体中文](README.zh-CN.md)
|
||||
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://pypi.org/project/graphifyy/)
|
||||
|
||||
**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.
|
||||
**A Claude Code skill.** Type `/graphify` in Claude Code - it reads your files, builds a knowledge graph, and gives you back structure you didn't know was there. Understand a codebase faster. Find the "why" behind architectural decisions.
|
||||
|
||||
Fully multimodal. Drop in code, PDFs, markdown, screenshots, diagrams, whiteboard photos, even images in other languages - graphify uses Claude vision to extract concepts and relationships from all of it and connects them into one graph.
|
||||
|
||||
@@ -23,29 +21,15 @@ graphify-out/
|
||||
└── cache/ SHA256 cache - re-runs only process changed files
|
||||
```
|
||||
|
||||
Add a `.graphifyignore` file to exclude folders you don't want in the graph:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
Same syntax as `.gitignore`. Patterns match against file paths relative to the folder you run graphify on.
|
||||
|
||||
## How it works
|
||||
|
||||
graphify runs in two passes. First, a deterministic AST pass extracts structure from code files (classes, functions, imports, call graphs, docstrings, rationale comments) with no LLM needed. Second, Claude subagents run in parallel over docs, papers, and images to extract concepts, relationships, and design rationale. The results are merged into a NetworkX graph, clustered with Leiden community detection, and exported as interactive HTML, queryable JSON, and a plain-language audit report.
|
||||
|
||||
**Clustering is graph-topology-based — no embeddings.** Leiden finds communities by edge density. The semantic similarity edges that Claude extracts (`semantically_similar_to`, marked INFERRED) are already in the graph, so they influence community detection directly. The graph structure is the similarity signal — no separate embedding step or vector database needed.
|
||||
|
||||
Every relationship is tagged `EXTRACTED` (found directly in source), `INFERRED` (reasonable inference, with a confidence score), or `AMBIGUOUS` (flagged for review). You always know what was found vs guessed.
|
||||
|
||||
## Install
|
||||
|
||||
**Requires:** 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:** [Claude Code](https://claude.ai/code) and Python 3.10+
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
@@ -53,56 +37,36 @@ pip install graphifyy && graphify install
|
||||
|
||||
> The PyPI package is temporarily named `graphifyy` while the `graphify` name is being reclaimed. The CLI and skill command are still `graphify`.
|
||||
|
||||
### Platform support
|
||||
|
||||
| Platform | Install command |
|
||||
|----------|----------------|
|
||||
| Claude Code | `graphify install` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
|
||||
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw uses sequential extraction (parallel agent support is still early on that platform).
|
||||
|
||||
Then open your AI coding assistant and type:
|
||||
Then open Claude Code in any directory and type:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
### Make your assistant always use the graph (recommended)
|
||||
### Make Claude always use the graph (recommended)
|
||||
|
||||
After building a graph, run this once in your project:
|
||||
|
||||
| Platform | Command |
|
||||
|----------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
| Factory Droid | `graphify droid install` |
|
||||
```bash
|
||||
graphify claude 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.
|
||||
This does two things:
|
||||
|
||||
**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.
|
||||
1. **CLAUDE.md rules** - tells Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and to rebuild the graph after editing code files.
|
||||
|
||||
Uninstall with the matching uninstall command (e.g. `graphify claude uninstall`).
|
||||
2. **PreToolUse hook** (`settings.json`) - fires automatically before every Glob and Grep call. If a knowledge graph exists, Claude sees: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ This means Claude navigates via the graph instead of grepping through every file - faster answers, fewer wasted tool calls, and responses grounded in the actual structure of your codebase rather than keyword matches.
|
||||
|
||||
**Always-on vs explicit trigger — what's the difference?**
|
||||
Without this, Claude will grep raw files by default even when a graph exists. With it, the graph becomes the first thing Claude reaches for.
|
||||
|
||||
The always-on hook surfaces `GRAPH_REPORT.md` — a one-page summary of god nodes, communities, and surprising connections. Your assistant reads this before searching files, so it navigates by structure instead of keyword matching. That covers most everyday questions.
|
||||
|
||||
`/graphify query`, `/graphify path`, and `/graphify explain` go deeper: they traverse the raw `graph.json` hop by hop, trace exact paths between nodes, and surface edge-level detail (relation type, confidence score, source location). Use them when you want a specific question answered from the graph rather than a general orientation.
|
||||
|
||||
Think of it this way: the always-on hook gives your assistant a map. The `/graphify` commands let it navigate the map precisely.
|
||||
Uninstall with `graphify claude uninstall`.
|
||||
|
||||
<details>
|
||||
<summary>Manual install (curl)</summary>
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/graphify
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v2/graphify/skill.md \
|
||||
> ~/.claude/skills/graphify/SKILL.md
|
||||
```
|
||||
|
||||
@@ -122,18 +86,12 @@ When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"`
|
||||
/graphify ./raw # run on a specific folder
|
||||
/graphify ./raw --mode deep # more aggressive INFERRED edge extraction
|
||||
/graphify ./raw --update # re-extract only changed files, merge into existing graph
|
||||
/graphify ./raw --cluster-only # rerun clustering on existing graph, no re-extraction
|
||||
/graphify ./raw --no-viz # skip HTML, just produce report + JSON
|
||||
/graphify ./raw --obsidian # also generate Obsidian vault (opt-in)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper, save, update graph
|
||||
/graphify add https://x.com/karpathy/status/... # fetch a tweet
|
||||
/graphify add https://... --author "Name" # tag the original author
|
||||
/graphify add https://... --contributor "Name" # tag who added it to the corpus
|
||||
|
||||
/graphify query "what connects attention to the optimizer?"
|
||||
/graphify query "what connects attention to the optimizer?" --dfs # trace a specific path
|
||||
/graphify query "what connects attention to the optimizer?" --budget 1500 # cap at N tokens
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
@@ -142,28 +100,17 @@ When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"`
|
||||
/graphify ./raw --svg # export graph.svg
|
||||
/graphify ./raw --graphml # export graph.graphml (Gephi, yEd)
|
||||
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
|
||||
/graphify ./raw --neo4j-push bolt://localhost:7687 # push directly to a running Neo4j instance
|
||||
/graphify ./raw --mcp # start MCP stdio server
|
||||
|
||||
# git hooks - platform-agnostic, rebuild graph on commit and branch switch
|
||||
graphify hook install
|
||||
graphify hook uninstall
|
||||
graphify hook status
|
||||
|
||||
# always-on assistant instructions - platform-specific
|
||||
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
|
||||
graphify claude uninstall
|
||||
graphify codex install # AGENTS.md (Codex)
|
||||
graphify opencode install # AGENTS.md (OpenCode)
|
||||
graphify claw install # AGENTS.md (OpenClaw)
|
||||
graphify droid install # AGENTS.md (Factory Droid)
|
||||
graphify hook install # git hooks - rebuilds graph on commit and branch switch
|
||||
graphify claude install # always-on: CLAUDE.md + PreToolUse hook for this project
|
||||
```
|
||||
|
||||
Works with any mix of file types:
|
||||
|
||||
| Type | Extensions | Extraction |
|
||||
|------|-----------|------------|
|
||||
| Code | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1` | AST via tree-sitter + call-graph + docstring/comment rationale |
|
||||
| Code | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php` | AST via tree-sitter + call-graph + docstring/comment rationale |
|
||||
| Docs | `.md .txt .rst` | Concepts + relationships + design rationale via Claude |
|
||||
| Papers | `.pdf` | Citation mining + concept extraction |
|
||||
| Images | `.png .jpg .webp .gif` | Claude vision - screenshots, diagrams, any language |
|
||||
@@ -184,11 +131,11 @@ Works with any mix of file types:
|
||||
|
||||
**Hyperedges** - group relationships connecting 3+ nodes that pairwise edges can't express. All classes implementing a shared protocol, all functions in an auth flow, all concepts from a paper section forming one idea.
|
||||
|
||||
**Token benchmark** - printed automatically after every run. On a mixed corpus (Karpathy repos + papers + images): **71.5x** fewer tokens per query vs reading raw files. The first run extracts and builds the graph (this costs tokens). Every subsequent query reads the compact graph instead of raw files — that's where the savings compound. The SHA256 cache means re-runs only re-process changed files.
|
||||
**Token benchmark** - printed automatically after every run. On a mixed corpus (Karpathy repos + papers + images): **71.5x** fewer tokens per query vs reading raw files.
|
||||
|
||||
**Auto-sync** (`--watch`) - run in a background terminal and the graph updates itself as your codebase changes. Code file saves trigger an instant rebuild (AST only, no LLM). Doc/image changes notify you to run `--update` for the LLM re-pass.
|
||||
|
||||
**Git hooks** (`graphify hook install`) - installs post-commit and post-checkout hooks. Graph rebuilds automatically after every commit and every branch switch. If a rebuild fails, the hook exits with a non-zero code so git surfaces the error instead of silently continuing. No background process needed.
|
||||
**Git hooks** (`graphify hook install`) - installs post-commit and post-checkout hooks. Graph rebuilds automatically after every commit and every branch switch. No background process needed.
|
||||
|
||||
**Wiki** (`--wiki`) - Wikipedia-style markdown articles per community and god node, with an `index.md` entry point. Point any agent at `index.md` and it can navigate the knowledge base by reading files instead of parsing JSON.
|
||||
|
||||
@@ -204,11 +151,11 @@ Token reduction scales with corpus size. 6 files fits in a context window anyway
|
||||
|
||||
## Privacy
|
||||
|
||||
graphify sends file contents to your AI coding assistant's underlying model API for semantic extraction of docs, papers, and images — Anthropic (Claude Code), OpenAI (Codex), or whichever provider your platform uses. Code files are processed locally via tree-sitter AST — no file contents leave your machine for code. No telemetry, usage tracking, or analytics of any kind. The only network calls are to your platform's model API during extraction, using your own API key.
|
||||
graphify sends file contents to the Claude API (Anthropic) for semantic extraction of docs, papers, and images. Code files are processed locally via tree-sitter AST — no file contents leave your machine for code. No telemetry, usage tracking, or analytics of any kind. The only network calls are to Anthropic's API during extraction, using your own API key via Claude Code.
|
||||
|
||||
## Tech stack
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantic extraction via Claude (Claude Code), GPT-4 (Codex), or whichever model your platform runs. No Neo4j required, no server, runs entirely locally.
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + Claude + vis.js. No Neo4j required, no server, runs entirely locally.
|
||||
|
||||
<details>
|
||||
<summary>Contributing</summary>
|
||||
|
||||
-211
@@ -1,211 +0,0 @@
|
||||
# graphify
|
||||
|
||||
[English](README.md) | [简体中文](README.zh-CN.md)
|
||||
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://pypi.org/project/graphifyy/)
|
||||
|
||||
**一个面向 AI 编码助手的技能。** 在 Claude Code、Codex、OpenCode 或 OpenClaw 中输入 `/graphify`,它会读取你的文件、构建知识图谱,并把原本不明显的结构关系还给你。更快理解代码库,找到架构决策背后的“为什么”。
|
||||
|
||||
完全多模态。你可以直接丢进去代码、PDF、Markdown、截图、流程图、白板照片,甚至其他语言的图片 —— graphify 会用 Claude vision 从这些内容中提取概念和关系,并把它们连接到同一张图里。
|
||||
|
||||
> Andrej Karpathy 会维护一个 `/raw` 文件夹,把论文、推文、截图和笔记都丢进去。graphify 就是在解决这类问题 —— 相比直接读取原始文件,每次查询的 token 消耗可降低 **71.5 倍**,结果还能跨会话持久保存,并且会明确区分哪些内容是实际发现的,哪些只是合理推断。
|
||||
|
||||
```
|
||||
/graphify . # 可用于任意目录:代码库、笔记、论文都可以
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html 可交互图谱:可点节点、搜索、按社区过滤
|
||||
├── GRAPH_REPORT.md God nodes、意外连接、建议提问
|
||||
├── graph.json 持久化图谱:数周后仍可查询,无需重新读原始文件
|
||||
└── cache/ SHA256 缓存:重复运行时只处理变更过的文件
|
||||
```
|
||||
|
||||
## 工作原理
|
||||
|
||||
graphify 分两轮执行。第一轮是确定性的 AST 提取,对代码文件做结构分析(类、函数、导入、调用图、docstring、解释性注释),这一轮不需要 LLM。第二轮会并行调用 Claude 子代理处理文档、论文和图片,从中提取概念、关系和设计动机。最后把两边结果合并到一个 NetworkX 图里,用 Leiden 社区发现算法做聚类,并导出成可交互 HTML、可查询 JSON,以及一份人类可读的审计报告。
|
||||
|
||||
**聚类是基于图拓扑完成的,不依赖 embeddings。** Leiden 按边密度发现社区。Claude 抽取出的语义相似边(`semantically_similar_to`,标记为 `INFERRED`)本来就存在于图中,所以会直接影响社区划分。图结构本身就是相似性信号,不需要额外的 embedding 步骤,也不需要向量数据库。
|
||||
|
||||
每条关系都会被标记为 `EXTRACTED`(直接在源材料中找到)、`INFERRED`(合理推断,并附带置信度分数)或 `AMBIGUOUS`(有歧义,需要复核)。所以你始终知道哪些是实际发现的,哪些是模型猜出来的。
|
||||
|
||||
## 安装
|
||||
|
||||
**要求:** Python 3.10+,并且使用以下平台之一:[Claude Code](https://claude.ai/code)、[Codex](https://openai.com/codex)、[OpenCode](https://opencode.ai) 或 [OpenClaw](https://openclaw.ai)
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> PyPI 包当前暂时叫 `graphifyy`,因为 `graphify` 这个名字还在回收中。CLI 命令和 skill 命令仍然都是 `graphify`。
|
||||
|
||||
### 平台支持
|
||||
|
||||
| 平台 | 安装命令 |
|
||||
|------|----------|
|
||||
| Claude Code | `graphify install` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
|
||||
Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `multi_agent = true`,这样才能并行提取。OpenClaw 目前的并行 agent 支持还比较早期,所以使用顺序提取。
|
||||
|
||||
然后打开你的 AI 编码助手,输入:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
### 让助手始终优先使用图谱(推荐)
|
||||
|
||||
图构建完成后,在项目里运行一次:
|
||||
|
||||
| 平台 | 命令 |
|
||||
|------|------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
|
||||
**Claude Code** 会做两件事:
|
||||
1. 在 `CLAUDE.md` 中写入一段规则,告诉 Claude 在回答架构问题前先读 `graphify-out/GRAPH_REPORT.md`
|
||||
2. 安装一个 **PreToolUse hook**(写入 `settings.json`),在每次 `Glob` 和 `Grep` 前触发
|
||||
|
||||
如果知识图谱存在,Claude 会先看到:_"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ —— 这样 Claude 会优先按图谱导航,而不是一上来就 grep 整个项目。
|
||||
|
||||
**Codex、OpenCode、OpenClaw** 会把同样的规则写进项目根目录的 `AGENTS.md`。这些平台没有 PreToolUse hook,所以 `AGENTS.md` 是它们的常驻机制。
|
||||
|
||||
卸载时使用对应平台的 uninstall 命令即可(例如 `graphify claude uninstall`)。
|
||||
|
||||
**常驻模式和显式触发有什么区别?**
|
||||
|
||||
常驻 hook 会优先暴露 `GRAPH_REPORT.md` —— 这是一页式总结,包含 god nodes、社区结构和意外连接。你的助手在搜索文件前会先读它,因此会按结构导航,而不是按关键字乱搜。这已经能覆盖大部分日常问题。
|
||||
|
||||
`/graphify query`、`/graphify path` 和 `/graphify explain` 会更深入:它们会逐跳遍历底层 `graph.json`,追踪节点之间的精确路径,并展示边级别细节(关系类型、置信度、源位置)。当你想从图谱里精确回答某个问题,而不仅仅是获得整体感知时,就该用这些命令。
|
||||
|
||||
可以这样理解:常驻 hook 是先给助手一张地图,`/graphify` 这几个命令则是让它沿着地图精确导航。
|
||||
|
||||
<details>
|
||||
<summary>手动安装(curl)</summary>
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/graphify
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
|
||||
> ~/.claude/skills/graphify/SKILL.md
|
||||
```
|
||||
|
||||
把下面内容加到 `~/.claude/CLAUDE.md`:
|
||||
|
||||
```
|
||||
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## 用法
|
||||
|
||||
```
|
||||
/graphify # 对当前目录运行
|
||||
/graphify ./raw # 对指定目录运行
|
||||
/graphify ./raw --mode deep # 更激进地抽取 INFERRED 边
|
||||
/graphify ./raw --update # 只重新提取变更文件,并合并到已有图谱
|
||||
/graphify ./raw --cluster-only # 只重新聚类已有图谱,不重新提取
|
||||
/graphify ./raw --no-viz # 跳过 HTML,只生成 report + JSON
|
||||
/graphify ./raw --obsidian # 额外生成 Obsidian vault(可选)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # 拉取论文、保存并更新图谱
|
||||
/graphify add https://x.com/karpathy/status/... # 拉取推文
|
||||
/graphify add https://... --author "Name" # 标记原作者
|
||||
/graphify add https://... --contributor "Name" # 标记是谁把它加入语料库的
|
||||
|
||||
/graphify query "what connects attention to the optimizer?"
|
||||
/graphify query "what connects attention to the optimizer?" --dfs # 追踪一条具体路径
|
||||
/graphify query "what connects attention to the optimizer?" --budget 1500 # 把预算限制在 N tokens
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
/graphify ./raw --watch # 文件变更时自动同步图谱(代码:立即更新;文档:提醒你)
|
||||
/graphify ./raw --wiki # 构建可供 agent 抓取的 wiki(index.md + 每个 community 一篇文章)
|
||||
/graphify ./raw --svg # 导出 graph.svg
|
||||
/graphify ./raw --graphml # 导出 graph.graphml(Gephi、yEd)
|
||||
/graphify ./raw --neo4j # 生成给 Neo4j 用的 cypher.txt
|
||||
/graphify ./raw --neo4j-push bolt://localhost:7687 # 直接推送到运行中的 Neo4j
|
||||
/graphify ./raw --mcp # 启动 MCP stdio server
|
||||
|
||||
# git hooks - 跨平台,在 commit 和切分支后重建图谱
|
||||
graphify hook install
|
||||
graphify hook uninstall
|
||||
graphify hook status
|
||||
|
||||
# 常驻助手规则 - 按平台区分
|
||||
graphify claude install # CLAUDE.md + PreToolUse hook(Claude Code)
|
||||
graphify claude uninstall
|
||||
graphify codex install # AGENTS.md(Codex)
|
||||
graphify opencode install # AGENTS.md(OpenCode)
|
||||
graphify claw install # AGENTS.md(OpenClaw)
|
||||
```
|
||||
|
||||
支持混合文件类型:
|
||||
|
||||
| 类型 | 扩展名 | 提取方式 |
|
||||
|------|--------|----------|
|
||||
| 代码 | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php` | tree-sitter AST + 调用图 + docstring / 注释中的 rationale |
|
||||
| 文档 | `.md .txt .rst` | 通过 Claude 提取概念、关系和设计动机 |
|
||||
| 论文 | `.pdf` | 引文挖掘 + 概念提取 |
|
||||
| 图片 | `.png .jpg .webp .gif` | Claude vision —— 截图、图表、任意语言都可以 |
|
||||
|
||||
## 你会得到什么
|
||||
|
||||
**God nodes** —— 度最高的概念节点(整个系统最容易汇聚到的地方)
|
||||
|
||||
**意外连接** —— 按综合得分排序。代码-论文之间的边会比代码-代码边权重更高。每条结果都会附带一段人话解释。
|
||||
|
||||
**建议提问** —— 图谱特别擅长回答的 4 到 5 个问题。
|
||||
|
||||
**“为什么”** —— docstring、行内注释(`# NOTE:`、`# IMPORTANT:`、`# HACK:`、`# WHY:`)以及文档里的设计动机都会被抽取成 `rationale_for` 节点。不只是知道代码“做了什么”,还能知道“为什么要这么写”。
|
||||
|
||||
**置信度分数** —— 每条 `INFERRED` 边都有 `confidence_score`(0.0-1.0)。你不只知道哪些是猜出来的,还知道模型对这个猜测有多有把握。`EXTRACTED` 边恒为 1.0。
|
||||
|
||||
**语义相似边** —— 跨文件的概念连接,即使结构上没有直接依赖也能建立关联。比如两个函数做的是同一类问题但彼此没有调用,或者某个代码类和某篇论文里的算法概念本质相同。
|
||||
|
||||
**超边(Hyperedges)** —— 用来表达 3 个以上节点的群组关系,这是普通两两边表达不出来的。比如:一组类共同实现一个协议、认证链路里的一组函数、同一篇论文某一节里的多个概念共同组成一个想法。
|
||||
|
||||
**Token 基准** —— 每次运行后都会自动打印。对混合语料(Karpathy 的仓库 + 论文 + 图片),每次查询的 token 消耗可以比直接读原文件少 **71.5 倍**。第一次运行需要先提取并建图,这一步会花 token;后续查询直接读取压缩后的图谱,节省会越来越明显。SHA256 缓存保证重复运行时只重新处理变更文件。
|
||||
|
||||
**自动同步**(`--watch`)—— 在后台终端里跑着,代码库一变化,图谱就会跟着更新。代码文件保存会立刻触发重建(只走 AST,不用 LLM);文档/图片变更则会提醒你跑 `--update` 进行 LLM 再提取。
|
||||
|
||||
**Git hooks**(`graphify hook install`)—— 安装 `post-commit` 和 `post-checkout` hook。每次 commit 后、每次切分支后都会自动重建图谱,不需要额外开一个后台进程。
|
||||
|
||||
**Wiki**(`--wiki`)—— 为每个 community 和 god node 生成类似维基百科的 Markdown 文章,并提供 `index.md` 作为入口。任何 agent 只要读 `index.md`,就能通过普通文件导航整个知识库,而不必直接解析 JSON。
|
||||
|
||||
## Worked examples
|
||||
|
||||
| 语料 | 文件数 | 压缩比 | 输出 |
|
||||
|------|--------|--------|------|
|
||||
| Karpathy 的仓库 + 5 篇论文 + 4 张图片 | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
|
||||
| graphify 源码 + Transformer 论文 | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
|
||||
| httpx(合成 Python 库) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
|
||||
|
||||
Token 压缩效果会随着语料规模增大而更明显。6 个文件本来就塞得进上下文窗口,所以 graphify 在这种场景里的价值更多是结构清晰度,而不是 token 压缩。到了 52 个文件(代码 + 论文 + 图片)这种规模,就能做到 71x+。每个 `worked/` 目录里都带了原始输入和真实输出(`GRAPH_REPORT.md`、`graph.json`),你可以自己跑一遍核对数字。
|
||||
|
||||
## 隐私
|
||||
|
||||
graphify 会把文档、论文和图片的内容发送给你所用 AI 编码助手背后的模型 API 来做语义提取 —— 可能是 Anthropic(Claude Code)、OpenAI(Codex),或者你当前平台使用的其他提供方。代码文件则完全在本地通过 tree-sitter AST 处理,不会把代码内容发出去。项目本身没有任何遥测、使用跟踪或分析。唯一的网络请求就是语义提取阶段调用你平台自己的模型 API,使用的也是你自己的 API key。
|
||||
|
||||
## 技术栈
|
||||
|
||||
NetworkX + Leiden(graspologic)+ tree-sitter + vis.js。语义提取由 Claude(Claude Code)、GPT-4(Codex)或你当前平台所运行的模型完成。不需要 Neo4j,不需要 server,整体是纯本地运行。
|
||||
|
||||
<details>
|
||||
<summary>贡献</summary>
|
||||
|
||||
**Worked examples** 是最能建立信任的贡献方式。对一个真实语料跑 `/graphify`,把输出保存到 `worked/{slug}/`,再写一份诚实的 `review.md`,评价图谱哪些地方做得对、哪些地方做得不对,然后提交 PR。
|
||||
|
||||
**提取 bug** —— 提 issue 时请附上输入文件、对应的缓存项(`graphify-out/cache/`)以及它漏提取或瞎编了什么。
|
||||
|
||||
模块职责和新增语言的方法见 [ARCHITECTURE.md](ARCHITECTURE.md)。
|
||||
|
||||
</details>
|
||||
+4
-4
@@ -4,8 +4,8 @@
|
||||
|
||||
| Version | Supported |
|
||||
|---------|-----------|
|
||||
| 0.3.x | Yes |
|
||||
| < 0.3 | No |
|
||||
| 0.1.x | Yes |
|
||||
| < 0.1 | No |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
@@ -28,13 +28,13 @@ graphify is a **local development tool**. It runs as a Claude Code skill and opt
|
||||
|
||||
| Vector | Mitigation |
|
||||
|--------|-----------|
|
||||
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes, blocks private/loopback/link-local IPs, and blocks cloud metadata endpoints. Redirect targets are re-validated. All fetch paths including tweet oEmbed go through `safe_fetch()`. |
|
||||
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes. Redirect targets are re-validated by `_NoFileRedirectHandler` - a redirect to `file://` is blocked. |
|
||||
| Oversized downloads | `safe_fetch()` streams responses and aborts at 50 MB. `safe_fetch_text()` aborts at 10 MB. |
|
||||
| Non-2xx HTTP responses | `safe_fetch()` raises `HTTPError` on non-2xx status codes - error pages are not silently treated as content. |
|
||||
| Path traversal in MCP server | `security.validate_graph_path()` resolves paths and requires them to be inside `graphify-out/`. Also requires the `graphify-out/` directory to exist. |
|
||||
| XSS in graph HTML output | `security.sanitize_label()` strips control characters, caps at 256 chars, and HTML-escapes all node labels and edge titles before pyvis embeds them. |
|
||||
| Prompt injection via node labels | `sanitize_label()` also applied to MCP text output - node labels from user-controlled source files cannot break the text format returned to agents. |
|
||||
| YAML frontmatter injection | `_yaml_str()` escapes backslashes, double quotes, and newlines before embedding user-controlled strings (webpage titles, query questions) in YAML frontmatter. |
|
||||
| YAML frontmatter injection | Newlines stripped from user-provided strings before embedding in YAML frontmatter (e.g. in `save_query_result()`). |
|
||||
| Encoding crashes on source files | All tree-sitter byte slices decoded with `errors="replace"` - non-UTF-8 source files degrade gracefully instead of crashing extraction. |
|
||||
| Symlink traversal | `os.walk(..., followlinks=False)` is explicit throughout `detect.py`. |
|
||||
| Corrupted graph.json | `_load_graph()` in `serve.py` wraps `json.JSONDecodeError` and prints a clear recovery message instead of crashing. |
|
||||
|
||||
+28
-154
@@ -29,71 +29,39 @@ _SKILL_REGISTRATION = (
|
||||
)
|
||||
|
||||
|
||||
_PLATFORM_CONFIG: dict[str, dict] = {
|
||||
"claude": {
|
||||
"skill_file": "skill.md",
|
||||
"skill_dst": Path(".claude") / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": True,
|
||||
},
|
||||
"codex": {
|
||||
"skill_file": "skill-codex.md",
|
||||
"skill_dst": Path(".agents") / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": False,
|
||||
},
|
||||
"opencode": {
|
||||
"skill_file": "skill-opencode.md",
|
||||
"skill_dst": Path(".config") / "opencode" / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": False,
|
||||
},
|
||||
"claw": {
|
||||
"skill_file": "skill-claw.md",
|
||||
"skill_dst": Path(".claw") / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": False,
|
||||
},
|
||||
"droid": {
|
||||
"skill_file": "skill-droid.md",
|
||||
"skill_dst": Path(".factory") / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": False,
|
||||
},
|
||||
}
|
||||
def _bundled_skill() -> Path:
|
||||
"""Path to the skill.md bundled with this package."""
|
||||
return Path(__file__).parent / "skill.md"
|
||||
|
||||
|
||||
def install(platform: str = "claude") -> None:
|
||||
if platform not in _PLATFORM_CONFIG:
|
||||
print(
|
||||
f"error: unknown platform '{platform}'. Choose from: {', '.join(_PLATFORM_CONFIG)}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
cfg = _PLATFORM_CONFIG[platform]
|
||||
skill_src = Path(__file__).parent / cfg["skill_file"]
|
||||
def install() -> None:
|
||||
skill_src = _bundled_skill()
|
||||
if not skill_src.exists():
|
||||
print(f"error: {cfg['skill_file']} not found in package - reinstall graphify", file=sys.stderr)
|
||||
print("error: skill.md not found in package - reinstall graphify", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
skill_dst = Path.home() / cfg["skill_dst"]
|
||||
# Copy skill to ~/.claude/skills/graphify/SKILL.md
|
||||
skill_dst = Path.home() / ".claude" / "skills" / "graphify" / "SKILL.md"
|
||||
skill_dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy(skill_src, skill_dst)
|
||||
print(f" skill installed → {skill_dst}")
|
||||
|
||||
if cfg["claude_md"]:
|
||||
# Register in ~/.claude/CLAUDE.md (Claude Code only)
|
||||
claude_md = Path.home() / ".claude" / "CLAUDE.md"
|
||||
if claude_md.exists():
|
||||
content = claude_md.read_text()
|
||||
if "graphify" in content:
|
||||
print(f" CLAUDE.md → already registered (no change)")
|
||||
else:
|
||||
claude_md.write_text(content.rstrip() + _SKILL_REGISTRATION)
|
||||
print(f" CLAUDE.md → skill registered in {claude_md}")
|
||||
# Register in ~/.claude/CLAUDE.md
|
||||
claude_md = Path.home() / ".claude" / "CLAUDE.md"
|
||||
if claude_md.exists():
|
||||
content = claude_md.read_text()
|
||||
if "graphify" in content:
|
||||
print(f" CLAUDE.md → already registered (no change)")
|
||||
else:
|
||||
claude_md.parent.mkdir(parents=True, exist_ok=True)
|
||||
claude_md.write_text(_SKILL_REGISTRATION.lstrip())
|
||||
print(f" CLAUDE.md → created at {claude_md}")
|
||||
claude_md.write_text(content.rstrip() + _SKILL_REGISTRATION)
|
||||
print(f" CLAUDE.md → skill registered in {claude_md}")
|
||||
else:
|
||||
claude_md.parent.mkdir(parents=True, exist_ok=True)
|
||||
claude_md.write_text(_SKILL_REGISTRATION.lstrip())
|
||||
print(f" CLAUDE.md → created at {claude_md}")
|
||||
|
||||
print()
|
||||
print("Done. Open your AI coding assistant and type:")
|
||||
print("Done. Open Claude Code in any directory and type:")
|
||||
print()
|
||||
print(" /graphify .")
|
||||
print()
|
||||
@@ -112,71 +80,6 @@ Rules:
|
||||
|
||||
_CLAUDE_MD_MARKER = "## graphify"
|
||||
|
||||
# AGENTS.md section for Codex, OpenCode, and OpenClaw.
|
||||
# All three platforms read AGENTS.md in the project root for persistent instructions.
|
||||
_AGENTS_MD_SECTION = """\
|
||||
## graphify
|
||||
|
||||
This project has a graphify knowledge graph at graphify-out/.
|
||||
|
||||
Rules:
|
||||
- Before answering architecture or codebase questions, read graphify-out/GRAPH_REPORT.md for god nodes and community structure
|
||||
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
|
||||
- After modifying code files in this session, run `python3 -c "from graphify.watch import _rebuild_code; from pathlib import Path; _rebuild_code(Path('.'))"` to keep the graph current
|
||||
"""
|
||||
|
||||
_AGENTS_MD_MARKER = "## graphify"
|
||||
|
||||
|
||||
def _agents_install(project_dir: Path, platform: str) -> None:
|
||||
"""Write the graphify section to the local AGENTS.md (Codex/OpenCode/OpenClaw)."""
|
||||
target = (project_dir or Path(".")) / "AGENTS.md"
|
||||
|
||||
if target.exists():
|
||||
content = target.read_text()
|
||||
if _AGENTS_MD_MARKER in content:
|
||||
print(f"graphify already configured in AGENTS.md")
|
||||
return
|
||||
new_content = content.rstrip() + "\n\n" + _AGENTS_MD_SECTION
|
||||
else:
|
||||
new_content = _AGENTS_MD_SECTION
|
||||
|
||||
target.write_text(new_content)
|
||||
print(f"graphify section written to {target.resolve()}")
|
||||
print()
|
||||
print(f"{platform.capitalize()} will now check the knowledge graph before answering")
|
||||
print("codebase questions and rebuild it after code changes.")
|
||||
print()
|
||||
print("Note: unlike Claude Code, there is no PreToolUse hook equivalent for")
|
||||
print(f"{platform.capitalize()} — the AGENTS.md rules are the always-on mechanism.")
|
||||
|
||||
|
||||
def _agents_uninstall(project_dir: Path) -> None:
|
||||
"""Remove the graphify section from the local AGENTS.md."""
|
||||
target = (project_dir or Path(".")) / "AGENTS.md"
|
||||
|
||||
if not target.exists():
|
||||
print("No AGENTS.md found in current directory - nothing to do")
|
||||
return
|
||||
|
||||
content = target.read_text()
|
||||
if _AGENTS_MD_MARKER not in content:
|
||||
print("graphify section not found in AGENTS.md - nothing to do")
|
||||
return
|
||||
|
||||
cleaned = re.sub(
|
||||
r"\n*## graphify\n.*?(?=\n## |\Z)",
|
||||
"",
|
||||
content,
|
||||
flags=re.DOTALL,
|
||||
).rstrip()
|
||||
if cleaned:
|
||||
target.write_text(cleaned + "\n")
|
||||
print(f"graphify section removed from {target.resolve()}")
|
||||
else:
|
||||
target.unlink()
|
||||
print(f"AGENTS.md was empty after removal - deleted {target.resolve()}")
|
||||
|
||||
|
||||
def claude_install(project_dir: Path | None = None) -> None:
|
||||
"""Write the graphify section to the local CLAUDE.md."""
|
||||
@@ -281,39 +184,19 @@ def main() -> None:
|
||||
print("Usage: graphify <command>")
|
||||
print()
|
||||
print("Commands:")
|
||||
print(" install [--platform P] copy skill to platform config dir (claude|codex|opencode|claw|droid)")
|
||||
print(" install copy skill to ~/.claude/skills/ and register in CLAUDE.md")
|
||||
print(" benchmark [graph.json] measure token reduction vs naive full-corpus approach")
|
||||
print(" hook install install post-commit/post-checkout git hooks (all platforms)")
|
||||
print(" hook uninstall remove git hooks")
|
||||
print(" hook status check if git hooks are installed")
|
||||
print(" claude install write graphify section to CLAUDE.md + PreToolUse hook (Claude Code)")
|
||||
print(" claude uninstall remove graphify section from CLAUDE.md + PreToolUse hook")
|
||||
print(" codex install write graphify section to AGENTS.md (Codex)")
|
||||
print(" codex uninstall remove graphify section from AGENTS.md")
|
||||
print(" opencode install write graphify section to AGENTS.md (OpenCode)")
|
||||
print(" opencode uninstall remove graphify section from AGENTS.md")
|
||||
print(" claw install write graphify section to AGENTS.md (OpenClaw)")
|
||||
print(" claw uninstall remove graphify section from AGENTS.md")
|
||||
print(" droid install write graphify section to AGENTS.md (Factory Droid)")
|
||||
print(" droid uninstall remove graphify section from AGENTS.md")
|
||||
print(" hook install install post-commit git hook (auto-rebuilds graph on commit)")
|
||||
print(" hook uninstall remove post-commit git hook")
|
||||
print(" hook status check if hook is installed")
|
||||
print(" claude install write graphify section to local CLAUDE.md")
|
||||
print(" claude uninstall remove graphify section from local CLAUDE.md")
|
||||
print()
|
||||
return
|
||||
|
||||
cmd = sys.argv[1]
|
||||
if cmd == "install":
|
||||
platform = "claude"
|
||||
args = sys.argv[2:]
|
||||
i = 0
|
||||
while i < len(args):
|
||||
if args[i].startswith("--platform="):
|
||||
platform = args[i].split("=", 1)[1]
|
||||
i += 1
|
||||
elif args[i] == "--platform" and i + 1 < len(args):
|
||||
platform = args[i + 1]
|
||||
i += 2
|
||||
else:
|
||||
i += 1
|
||||
install(platform=platform)
|
||||
install()
|
||||
elif cmd == "claude":
|
||||
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
if subcmd == "install":
|
||||
@@ -323,15 +206,6 @@ def main() -> None:
|
||||
else:
|
||||
print("Usage: graphify claude [install|uninstall]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
elif cmd in ("codex", "opencode", "claw", "droid"):
|
||||
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
if subcmd == "install":
|
||||
_agents_install(Path("."), cmd)
|
||||
elif subcmd == "uninstall":
|
||||
_agents_uninstall(Path("."))
|
||||
else:
|
||||
print(f"Usage: graphify {cmd} [install|uninstall]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
elif cmd == "hook":
|
||||
from graphify.hooks import install as hook_install, uninstall as hook_uninstall, status as hook_status
|
||||
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
|
||||
+5
-9
@@ -16,16 +16,12 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
|
||||
These are synthetic nodes created by the AST extractor and should be excluded
|
||||
from god nodes, surprising connections, and knowledge gap reporting.
|
||||
"""
|
||||
attrs = G.nodes[node_id]
|
||||
label = attrs.get("label", "")
|
||||
label = G.nodes[node_id].get("label", "")
|
||||
if not label:
|
||||
return False
|
||||
# File-level hub: label matches the actual source filename (not just any label ending in .py)
|
||||
source_file = attrs.get("source_file", "")
|
||||
if source_file:
|
||||
from pathlib import Path as _Path
|
||||
if label == _Path(source_file).name:
|
||||
return True
|
||||
# File-level hub: label is a filename with a code extension
|
||||
if label.split(".")[-1] in ("py", "ts", "js", "go", "rs", "java", "rb", "cpp", "c", "h"):
|
||||
return True
|
||||
# Method stub: AST extractor labels methods as '.method_name()'
|
||||
if label.startswith(".") and label.endswith("()"):
|
||||
return True
|
||||
@@ -472,7 +468,7 @@ def graph_diff(G_old: nx.Graph, G_new: nx.Graph) -> dict:
|
||||
]
|
||||
|
||||
def edge_key(G: nx.Graph, u: str, v: str, data: dict) -> tuple:
|
||||
return (min(u, v), max(u, v), data.get("relation", ""))
|
||||
return (u, v, data.get("relation", ""))
|
||||
|
||||
old_edge_keys = {
|
||||
edge_key(G_old, u, v, d)
|
||||
|
||||
+2
-30
@@ -1,25 +1,4 @@
|
||||
# assemble node+edge dicts into a NetworkX graph, preserving edge direction
|
||||
#
|
||||
# Node deduplication — three layers:
|
||||
#
|
||||
# 1. Within a file (AST): each extractor tracks a `seen_ids` set. A node ID is
|
||||
# emitted at most once per file, so duplicate class/function definitions in
|
||||
# the same source file are collapsed to the first occurrence.
|
||||
#
|
||||
# 2. Between files (build): NetworkX G.add_node() is idempotent — calling it
|
||||
# twice with the same ID overwrites the attributes with the second call's
|
||||
# values. Nodes are added in extraction order (AST first, then semantic),
|
||||
# so if the same entity is extracted by both passes the semantic node
|
||||
# silently overwrites the AST node. This is intentional: semantic nodes
|
||||
# carry richer labels and cross-file context, while AST nodes have precise
|
||||
# source_location. If you need to change the priority, reorder extractions
|
||||
# passed to build().
|
||||
#
|
||||
# 3. Semantic merge (skill): before calling build(), the skill merges cached
|
||||
# and new semantic results using an explicit `seen` set keyed on node["id"],
|
||||
# so duplicates across cache hits and new extractions are resolved there
|
||||
# before any graph construction happens.
|
||||
#
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
import networkx as nx
|
||||
@@ -53,18 +32,11 @@ def build_from_json(extraction: dict) -> nx.Graph:
|
||||
|
||||
|
||||
def build(extractions: list[dict]) -> nx.Graph:
|
||||
"""Merge multiple extraction results into one graph.
|
||||
|
||||
Extractions are merged in order. For nodes with the same ID, the last
|
||||
extraction's attributes win (NetworkX add_node overwrites). Pass AST
|
||||
results before semantic results so semantic labels take precedence, or
|
||||
reverse the order if you prefer AST source_location precision to win.
|
||||
"""
|
||||
combined: dict = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
"""Merge multiple extraction results into one graph."""
|
||||
combined: dict = {"nodes": [], "edges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
for ext in extractions:
|
||||
combined["nodes"].extend(ext.get("nodes", []))
|
||||
combined["edges"].extend(ext.get("edges", []))
|
||||
combined["hyperedges"].extend(ext.get("hyperedges", []))
|
||||
combined["input_tokens"] += ext.get("input_tokens", 0)
|
||||
combined["output_tokens"] += ext.get("output_tokens", 0)
|
||||
return build_from_json(combined)
|
||||
+3
-15
@@ -3,18 +3,12 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def file_hash(path: Path) -> str:
|
||||
"""SHA256 of file contents + resolved path. Prevents cache collisions on identical content."""
|
||||
p = Path(path)
|
||||
h = hashlib.sha256()
|
||||
h.update(p.read_bytes())
|
||||
h.update(b"\x00")
|
||||
h.update(str(p.resolve()).encode())
|
||||
return h.hexdigest()
|
||||
"""SHA256 of file contents, hex digest."""
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def cache_dir(root: Path = Path(".")) -> Path:
|
||||
@@ -52,13 +46,7 @@ def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
|
||||
"""
|
||||
h = file_hash(path)
|
||||
entry = cache_dir(root) / f"{h}.json"
|
||||
tmp = entry.with_suffix(".tmp")
|
||||
try:
|
||||
tmp.write_text(json.dumps(result))
|
||||
os.replace(tmp, entry)
|
||||
except Exception:
|
||||
tmp.unlink(missing_ok=True)
|
||||
raise
|
||||
entry.write_text(json.dumps(result))
|
||||
|
||||
|
||||
def cached_files(root: Path = Path(".")) -> set[str]:
|
||||
|
||||
+2
-64
@@ -1,6 +1,5 @@
|
||||
# file discovery, type classification, and corpus health checks
|
||||
from __future__ import annotations
|
||||
import fnmatch
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -17,7 +16,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'}
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.tsx', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php'}
|
||||
DOC_EXTENSIONS = {'.md', '.txt', '.rst'}
|
||||
PAPER_EXTENSIONS = {'.pdf'}
|
||||
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
|
||||
@@ -135,56 +134,6 @@ def _is_noise_dir(part: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _load_graphifyignore(root: Path) -> list[str]:
|
||||
"""Read .graphifyignore from root and return a list of patterns.
|
||||
|
||||
Lines starting with # are comments. Blank lines are ignored.
|
||||
Patterns follow gitignore semantics: glob matched against the path
|
||||
relative to root. A leading slash anchors to root. A trailing slash
|
||||
matches directories only (we match both dir and file for simplicity).
|
||||
"""
|
||||
ignore_file = root / ".graphifyignore"
|
||||
if not ignore_file.exists():
|
||||
return []
|
||||
patterns = []
|
||||
for line in ignore_file.read_text(errors="ignore").splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#"):
|
||||
patterns.append(line)
|
||||
return patterns
|
||||
|
||||
|
||||
def _is_ignored(path: Path, root: Path, patterns: list[str]) -> bool:
|
||||
"""Return True if path matches any .graphifyignore pattern."""
|
||||
if not patterns:
|
||||
return False
|
||||
try:
|
||||
rel = str(path.relative_to(root))
|
||||
except ValueError:
|
||||
return False
|
||||
rel = rel.replace(os.sep, "/")
|
||||
parts = rel.split("/")
|
||||
for pattern in patterns:
|
||||
# Normalize: strip leading/trailing slashes for matching purposes
|
||||
p = pattern.strip("/")
|
||||
if not p:
|
||||
continue
|
||||
# Match against full relative path
|
||||
if fnmatch.fnmatch(rel, p):
|
||||
return True
|
||||
# Match against filename alone
|
||||
if fnmatch.fnmatch(path.name, p):
|
||||
return True
|
||||
# Match against any path segment or prefix
|
||||
# e.g. "vendor" or "vendor/" should match "vendor/lib.py"
|
||||
for i, part in enumerate(parts):
|
||||
if fnmatch.fnmatch(part, p):
|
||||
return True
|
||||
if fnmatch.fnmatch("/".join(parts[:i + 1]), p):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def detect(root: Path) -> dict:
|
||||
files: dict[FileType, list[str]] = {
|
||||
FileType.CODE: [],
|
||||
@@ -195,7 +144,6 @@ def detect(root: Path) -> dict:
|
||||
total_words = 0
|
||||
|
||||
skipped_sensitive: list[str] = []
|
||||
ignore_patterns = _load_graphifyignore(root)
|
||||
|
||||
# Always include graphify-out/memory/ - query results filed back into the graph
|
||||
memory_dir = root / "graphify-out" / "memory"
|
||||
@@ -214,9 +162,7 @@ def detect(root: Path) -> dict:
|
||||
# Prune noise dirs in-place so os.walk never descends into them
|
||||
dirnames[:] = [
|
||||
d for d in dirnames
|
||||
if not d.startswith(".")
|
||||
and not _is_noise_dir(d)
|
||||
and not _is_ignored(dp / d, root, ignore_patterns)
|
||||
if not d.startswith(".") and not _is_noise_dir(d)
|
||||
]
|
||||
for fname in filenames:
|
||||
p = dp / fname
|
||||
@@ -232,8 +178,6 @@ def detect(root: Path) -> dict:
|
||||
# but catch hidden files at the root level
|
||||
if p.name.startswith("."):
|
||||
continue
|
||||
if _is_ignored(p, root, ignore_patterns):
|
||||
continue
|
||||
if _is_sensitive(p):
|
||||
skipped_sensitive.append(str(p))
|
||||
continue
|
||||
@@ -266,7 +210,6 @@ def detect(root: Path) -> dict:
|
||||
"needs_graph": needs_graph,
|
||||
"warning": warning,
|
||||
"skipped_sensitive": skipped_sensitive,
|
||||
"graphifyignore_patterns": len(ignore_patterns),
|
||||
}
|
||||
|
||||
|
||||
@@ -323,14 +266,9 @@ def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
|
||||
else:
|
||||
unchanged_files[ftype].append(f)
|
||||
|
||||
# Files in manifest that no longer exist - their cached nodes are now ghost nodes
|
||||
current_files = {f for flist in full["files"].values() for f in flist}
|
||||
deleted_files = [f for f in manifest if f not in current_files]
|
||||
|
||||
new_total = sum(len(v) for v in new_files.values())
|
||||
full["incremental"] = True
|
||||
full["new_files"] = new_files
|
||||
full["unchanged_files"] = unchanged_files
|
||||
full["new_total"] = new_total
|
||||
full["deleted_files"] = deleted_files
|
||||
return full
|
||||
+13
-22
@@ -8,7 +8,6 @@ from pathlib import Path
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
from graphify.security import sanitize_label
|
||||
from graphify.analyze import _node_community_map
|
||||
|
||||
COMMUNITY_COLORS = [
|
||||
"#4E79A7", "#F28E2B", "#E15759", "#76B7B2", "#59A14F",
|
||||
@@ -18,6 +17,11 @@ COMMUNITY_COLORS = [
|
||||
MAX_NODES_FOR_VIZ = 5_000
|
||||
|
||||
|
||||
def _node_community_map(communities: dict[int, list[str]]) -> dict[str, int]:
|
||||
"""Invert communities dict: node_id -> community_id."""
|
||||
return {n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
|
||||
|
||||
def _html_styles() -> str:
|
||||
return """<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
@@ -271,26 +275,18 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) ->
|
||||
json.dump(data, f, indent=2)
|
||||
|
||||
|
||||
def _cypher_escape(s: str) -> str:
|
||||
"""Escape a string for safe embedding in a Cypher single-quoted literal."""
|
||||
return s.replace("\\", "\\\\").replace("'", "\\'")
|
||||
|
||||
|
||||
def to_cypher(G: nx.Graph, output_path: str) -> None:
|
||||
lines = ["// Neo4j Cypher import - generated by /graphify", ""]
|
||||
for node_id, data in G.nodes(data=True):
|
||||
label = _cypher_escape(data.get("label", node_id))
|
||||
node_id_esc = _cypher_escape(node_id)
|
||||
ftype = re.sub(r"[^A-Za-z0-9_]", "", data.get("file_type", "unknown").capitalize()) or "Entity"
|
||||
lines.append(f"MERGE (n:{ftype} {{id: '{node_id_esc}', label: '{label}'}});")
|
||||
label = data.get("label", node_id).replace("'", "\\'")
|
||||
ftype = data.get("file_type", "unknown").capitalize()
|
||||
lines.append(f"MERGE (n:{ftype} {{id: '{node_id}', label: '{label}'}});")
|
||||
lines.append("")
|
||||
for u, v, data in G.edges(data=True):
|
||||
rel = re.sub(r"[^A-Za-z0-9_]", "_", data.get("relation", "RELATES_TO").upper())
|
||||
conf = _cypher_escape(data.get("confidence", "EXTRACTED"))
|
||||
u_esc = _cypher_escape(u)
|
||||
v_esc = _cypher_escape(v)
|
||||
rel = data.get("relation", "RELATES_TO").upper().replace(" ", "_").replace("-", "_")
|
||||
conf = data.get("confidence", "EXTRACTED")
|
||||
lines.append(
|
||||
f"MATCH (a {{id: '{u_esc}'}}), (b {{id: '{v_esc}'}}) "
|
||||
f"MATCH (a {{id: '{u}'}}), (b {{id: '{v}'}}) "
|
||||
f"MERGE (a)-[:{rel} {{confidence: '{conf}'}}]->(b);"
|
||||
)
|
||||
with open(output_path, "w") as f:
|
||||
@@ -337,7 +333,7 @@ def to_html(
|
||||
"font": {"size": font_size, "color": "#ffffff"},
|
||||
"title": f"{label}",
|
||||
"community": cid,
|
||||
"community_name": sanitize_label((community_labels or {}).get(cid, f"Community {cid}")),
|
||||
"community_name": (community_labels or {}).get(cid, f"Community {cid}"),
|
||||
"source_file": sanitize_label(data.get("source_file", "")),
|
||||
"file_type": data.get("file_type", ""),
|
||||
"degree": deg,
|
||||
@@ -836,11 +832,6 @@ def push_to_neo4j(
|
||||
def _safe_rel(relation: str) -> str:
|
||||
return re.sub(r"[^A-Z0-9_]", "_", relation.upper().replace(" ", "_").replace("-", "_")) or "RELATED_TO"
|
||||
|
||||
def _safe_label(label: str) -> str:
|
||||
"""Sanitize a Neo4j node label to prevent Cypher injection."""
|
||||
sanitized = re.sub(r"[^A-Za-z0-9_]", "", label)
|
||||
return sanitized if sanitized else "Entity"
|
||||
|
||||
driver = GraphDatabase.driver(uri, auth=(user, password))
|
||||
nodes_pushed = 0
|
||||
edges_pushed = 0
|
||||
@@ -852,7 +843,7 @@ def push_to_neo4j(
|
||||
cid = node_community.get(node_id)
|
||||
if cid is not None:
|
||||
props["community"] = cid
|
||||
ftype = _safe_label(data.get("file_type", "Entity").capitalize())
|
||||
ftype = data.get("file_type", "Entity").capitalize()
|
||||
session.run(
|
||||
f"MERGE (n:{ftype} {{id: $id}}) SET n += $props",
|
||||
id=node_id,
|
||||
|
||||
+1758
-1278
File diff suppressed because it is too large.
Load diff
+16
-25
@@ -1,15 +1,13 @@
|
||||
# git hook integration - install/uninstall graphify post-commit and post-checkout hooks
|
||||
from __future__ import annotations
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
_HOOK_MARKER = "# graphify-hook-start"
|
||||
_HOOK_MARKER_END = "# graphify-hook-end"
|
||||
_CHECKOUT_MARKER = "# graphify-checkout-hook-start"
|
||||
_CHECKOUT_MARKER_END = "# graphify-checkout-hook-end"
|
||||
_HOOK_MARKER = "# graphify-hook"
|
||||
_CHECKOUT_MARKER = "# graphify-checkout-hook"
|
||||
|
||||
_HOOK_SCRIPT = """\
|
||||
# graphify-hook-start
|
||||
#!/bin/bash
|
||||
# graphify-hook
|
||||
# Auto-rebuilds the knowledge graph after each commit (code files only, no LLM needed).
|
||||
# Installed by: graphify hook install
|
||||
|
||||
@@ -42,14 +40,14 @@ try:
|
||||
_rebuild_code(Path('.'))
|
||||
except Exception as exc:
|
||||
print(f'[graphify hook] Rebuild failed: {exc}')
|
||||
sys.exit(1)
|
||||
sys.exit(0)
|
||||
"
|
||||
# graphify-hook-end
|
||||
"""
|
||||
|
||||
|
||||
_CHECKOUT_SCRIPT = """\
|
||||
# graphify-checkout-hook-start
|
||||
#!/bin/bash
|
||||
# graphify-checkout-hook
|
||||
# Auto-rebuilds the knowledge graph (code only) when switching branches.
|
||||
# Installed by: graphify hook install
|
||||
|
||||
@@ -71,14 +69,11 @@ echo "[graphify] Branch switched - rebuilding knowledge graph (code files)..."
|
||||
python3 -c "
|
||||
from graphify.watch import _rebuild_code
|
||||
from pathlib import Path
|
||||
import sys
|
||||
try:
|
||||
_rebuild_code(Path('.'))
|
||||
except Exception as exc:
|
||||
print(f'[graphify] Rebuild failed: {exc}')
|
||||
sys.exit(1)
|
||||
"
|
||||
# graphify-checkout-hook-end
|
||||
"""
|
||||
|
||||
|
||||
@@ -100,29 +95,25 @@ def _install_hook(hooks_dir: Path, name: str, script: str, marker: str) -> str:
|
||||
return f"already installed at {hook_path}"
|
||||
hook_path.write_text(content.rstrip() + "\n\n" + script)
|
||||
return f"appended to existing {name} hook at {hook_path}"
|
||||
hook_path.write_text("#!/bin/bash\n" + script)
|
||||
hook_path.write_text(script)
|
||||
hook_path.chmod(0o755)
|
||||
return f"installed at {hook_path}"
|
||||
|
||||
|
||||
def _uninstall_hook(hooks_dir: Path, name: str, marker: str, marker_end: str) -> str:
|
||||
"""Remove graphify section from a git hook using start/end markers."""
|
||||
def _uninstall_hook(hooks_dir: Path, name: str, marker: str) -> str:
|
||||
"""Remove graphify section from a git hook."""
|
||||
hook_path = hooks_dir / name
|
||||
if not hook_path.exists():
|
||||
return f"no {name} hook found - nothing to remove."
|
||||
content = hook_path.read_text()
|
||||
if marker not in content:
|
||||
return f"graphify hook not found in {name} - nothing to remove."
|
||||
new_content = re.sub(
|
||||
rf"{re.escape(marker)}.*?{re.escape(marker_end)}\n?",
|
||||
"",
|
||||
content,
|
||||
flags=re.DOTALL,
|
||||
).strip()
|
||||
if not new_content or new_content == "#!/bin/bash":
|
||||
before = content.split(marker)[0].rstrip()
|
||||
non_empty = [l for l in before.splitlines() if l.strip() and not l.startswith("#!")]
|
||||
if not non_empty:
|
||||
hook_path.unlink()
|
||||
return f"removed {name} hook at {hook_path}"
|
||||
hook_path.write_text(new_content + "\n")
|
||||
hook_path.write_text(before + "\n")
|
||||
return f"graphify removed from {name} at {hook_path} (other hook content preserved)"
|
||||
|
||||
|
||||
@@ -148,8 +139,8 @@ def uninstall(path: Path = Path(".")) -> str:
|
||||
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
|
||||
|
||||
hooks_dir = root / ".git" / "hooks"
|
||||
commit_msg = _uninstall_hook(hooks_dir, "post-commit", _HOOK_MARKER, _HOOK_MARKER_END)
|
||||
checkout_msg = _uninstall_hook(hooks_dir, "post-checkout", _CHECKOUT_MARKER, _CHECKOUT_MARKER_END)
|
||||
commit_msg = _uninstall_hook(hooks_dir, "post-commit", _HOOK_MARKER)
|
||||
checkout_msg = _uninstall_hook(hooks_dir, "post-checkout", _CHECKOUT_MARKER)
|
||||
|
||||
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
|
||||
|
||||
|
||||
+5
-8
@@ -10,11 +10,6 @@ from pathlib import Path
|
||||
from graphify.security import safe_fetch, safe_fetch_text, validate_url
|
||||
|
||||
|
||||
def _yaml_str(s: str) -> str:
|
||||
"""Escape a string for embedding in a YAML double-quoted scalar."""
|
||||
return s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
|
||||
|
||||
|
||||
def _safe_filename(url: str, suffix: str) -> str:
|
||||
"""Turn a URL into a safe filename."""
|
||||
parsed = urllib.parse.urlparse(url)
|
||||
@@ -72,7 +67,9 @@ def _fetch_tweet(url: str, author: str | None, contributor: str | None) -> tuple
|
||||
oembed_url = url.replace("x.com", "twitter.com")
|
||||
oembed_api = f"https://publish.twitter.com/oembed?url={urllib.parse.quote(oembed_url)}&omit_script=true"
|
||||
try:
|
||||
data = json.loads(safe_fetch_text(oembed_api))
|
||||
req = urllib.request.Request(oembed_api, headers={"User-Agent": "graphify/1.0"})
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
data = json.loads(resp.read())
|
||||
tweet_text = re.sub(r"<[^>]+>", "", data.get("html", "")).strip()
|
||||
tweet_author = data.get("author_name", "unknown")
|
||||
except Exception:
|
||||
@@ -111,7 +108,7 @@ def _fetch_webpage(url: str, author: str | None, contributor: str | None) -> tup
|
||||
content = f"""---
|
||||
source_url: {url}
|
||||
type: webpage
|
||||
title: "{_yaml_str(title)}"
|
||||
title: "{title}"
|
||||
captured_at: {now}
|
||||
contributor: {contributor or author or 'unknown'}
|
||||
---
|
||||
@@ -253,7 +250,7 @@ def save_query_result(
|
||||
"---",
|
||||
f'type: "{query_type}"',
|
||||
f'date: "{now.isoformat()}"',
|
||||
f'question: "{_yaml_str(question)}"',
|
||||
f'question: "{re.sub(chr(10) + chr(13), " ", question).replace(chr(34), chr(39))}"',
|
||||
'contributor: "graphify"',
|
||||
]
|
||||
if source_nodes:
|
||||
|
||||
+2
-34
@@ -8,28 +8,20 @@ import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
import ipaddress
|
||||
import socket
|
||||
|
||||
_ALLOWED_SCHEMES = {"http", "https"}
|
||||
_MAX_FETCH_BYTES = 52_428_800 # 50 MB hard cap for binary downloads
|
||||
_MAX_TEXT_BYTES = 10_485_760 # 10 MB hard cap for HTML / text
|
||||
|
||||
# AWS metadata, link-local, and common cloud metadata endpoints
|
||||
_BLOCKED_HOSTS = {"metadata.google.internal", "metadata.google.com"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# URL validation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def validate_url(url: str) -> str:
|
||||
"""Raise ValueError if *url* is not http or https, or targets a private/internal IP.
|
||||
"""Raise ValueError if *url* is not http or https.
|
||||
|
||||
Blocks file://, ftp://, data:, and any other scheme that could be used
|
||||
for SSRF or local file access. Also blocks requests to private/reserved
|
||||
IP ranges (127.x, 10.x, 169.254.x, etc.) and cloud metadata endpoints
|
||||
to prevent SSRF in cloud environments.
|
||||
for SSRF or local file access.
|
||||
"""
|
||||
parsed = urllib.parse.urlparse(url)
|
||||
if parsed.scheme.lower() not in _ALLOWED_SCHEMES:
|
||||
@@ -37,30 +29,6 @@ def validate_url(url: str) -> str:
|
||||
f"Blocked URL scheme '{parsed.scheme}' - only http and https are allowed. "
|
||||
f"Got: {url!r}"
|
||||
)
|
||||
|
||||
hostname = parsed.hostname
|
||||
if hostname:
|
||||
# Block known cloud metadata hostnames
|
||||
if hostname.lower() in _BLOCKED_HOSTS:
|
||||
raise ValueError(
|
||||
f"Blocked cloud metadata endpoint '{hostname}'. "
|
||||
f"Got: {url!r}"
|
||||
)
|
||||
|
||||
# Resolve hostname and block private/reserved IP ranges
|
||||
try:
|
||||
infos = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM)
|
||||
for info in infos:
|
||||
addr = info[4][0]
|
||||
ip = ipaddress.ip_address(addr)
|
||||
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local:
|
||||
raise ValueError(
|
||||
f"Blocked private/internal IP {addr} (resolved from '{hostname}'). "
|
||||
f"Got: {url!r}"
|
||||
)
|
||||
except socket.gaierror:
|
||||
pass # DNS failure will surface later during fetch
|
||||
|
||||
return url
|
||||
|
||||
|
||||
|
||||
+2
-2
@@ -75,8 +75,8 @@ def _dfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], lis
|
||||
|
||||
|
||||
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000) -> str:
|
||||
"""Render subgraph as text, cutting at token_budget (approx 3 chars/token)."""
|
||||
char_budget = token_budget * 3
|
||||
"""Render subgraph as text, cutting at token_budget (approx 4 chars/token)."""
|
||||
char_budget = token_budget * 4
|
||||
lines = []
|
||||
for nid in sorted(nodes, key=lambda n: G.degree(n), reverse=True):
|
||||
d = G.nodes[nid]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -702,7 +702,7 @@ import json
|
||||
from pathlib import Path
|
||||
|
||||
result = json.loads(open('.graphify_incremental.json').read()) if Path('.graphify_incremental.json').exists() else {}
|
||||
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc'}
|
||||
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts'}
|
||||
new_files = result.get('new_files', {})
|
||||
all_changed = [f for files in new_files.values() for f in files]
|
||||
code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
|
||||
|
||||
+4
-3
@@ -50,7 +50,7 @@ def _rebuild_code(watch_path: Path) -> bool:
|
||||
detection = {
|
||||
"files": {"code": [str(f) for f in code_files], "document": [], "paper": [], "image": []},
|
||||
"total_files": len(code_files),
|
||||
"total_words": 0, # not needed during watch rebuild
|
||||
"total_words": sum(len(f.read_text(errors="ignore").split()) for f in code_files),
|
||||
}
|
||||
|
||||
G = build_from_json(result)
|
||||
@@ -118,7 +118,7 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
|
||||
|
||||
last_trigger: float = 0.0
|
||||
pending: bool = False
|
||||
changed: set[Path] = set()
|
||||
changed: list[Path] = []
|
||||
|
||||
class Handler(FileSystemEventHandler):
|
||||
def on_any_event(self, event):
|
||||
@@ -134,7 +134,8 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
|
||||
return
|
||||
last_trigger = time.monotonic()
|
||||
pending = True
|
||||
changed.add(path)
|
||||
if path not in changed:
|
||||
changed.append(path)
|
||||
|
||||
handler = Handler()
|
||||
observer = Observer()
|
||||
|
||||
+5
-9
@@ -4,11 +4,11 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "graphifyy"
|
||||
version = "0.3.2"
|
||||
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, OpenClaw) - turn any folder of code, docs, papers, or images into a queryable knowledge graph"
|
||||
version = "0.2.2"
|
||||
description = "Claude Code skill - turn any folder of code, docs, papers, images, or tweets into a queryable knowledge graph"
|
||||
readme = "README.md"
|
||||
license = { file = "LICENSE" }
|
||||
keywords = ["claude", "claude-code", "codex", "opencode", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
|
||||
license = { text = "MIT" }
|
||||
keywords = ["claude", "claude-code", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"networkx",
|
||||
@@ -26,10 +26,6 @@ dependencies = [
|
||||
"tree-sitter-kotlin",
|
||||
"tree-sitter-scala",
|
||||
"tree-sitter-php",
|
||||
"tree-sitter-swift",
|
||||
"tree-sitter-lua",
|
||||
"tree-sitter-zig",
|
||||
"tree-sitter-powershell",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
@@ -53,4 +49,4 @@ where = ["."]
|
||||
include = ["graphify*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-claw.md"]
|
||||
graphify = ["skill.md"]
|
||||
@@ -58,26 +58,15 @@ Follow these steps in order. Do not skip steps.
|
||||
### Step 1 - Ensure graphify is installed
|
||||
|
||||
```bash
|
||||
# Detect the correct Python interpreter (handles pipx, venv, system installs)
|
||||
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
|
||||
if [ -n "$GRAPHIFY_BIN" ]; then
|
||||
PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
|
||||
else
|
||||
PYTHON="python3"
|
||||
fi
|
||||
$PYTHON -c "import graphify" 2>/dev/null || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
# Write interpreter path for all subsequent steps
|
||||
$PYTHON -c "import sys; open('.graphify_python', 'w').write(sys.executable)"
|
||||
python3 -c "import graphify" 2>/dev/null || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
|
||||
**In every subsequent bash block, replace `python3` with `$(cat .graphify_python)` to use the correct interpreter.**
|
||||
|
||||
### Step 2 - Detect files
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
@@ -117,7 +106,7 @@ Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is determin
|
||||
For any code files detected, run AST extraction in parallel with Part B subagents:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.extract import collect_files, extract
|
||||
from pathlib import Path
|
||||
@@ -155,7 +144,7 @@ Before dispatching subagents, print a timing estimate:
|
||||
Before dispatching any subagents, check which files already have cached extraction results:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from graphify.cache import check_semantic_cache
|
||||
from pathlib import Path
|
||||
@@ -163,10 +152,10 @@ from pathlib import Path
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
all_files = [f for files in detect['files'].values() for f in files]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
|
||||
cached_nodes, cached_edges, uncached = check_semantic_cache(all_files)
|
||||
|
||||
if cached_nodes or cached_edges or cached_hyperedges:
|
||||
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
|
||||
if cached_nodes or cached_edges:
|
||||
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges}))
|
||||
Path('.graphify_uncached.txt').write_text('\n'.join(uncached))
|
||||
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
|
||||
"
|
||||
@@ -178,21 +167,19 @@ Only dispatch subagents for files listed in `.graphify_uncached.txt`. If all fil
|
||||
|
||||
Load files from `.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context).
|
||||
|
||||
**Step B2 - Dispatch ALL subagents in a single message (OpenCode)**
|
||||
**Step B2 - Dispatch ALL subagents in a single message**
|
||||
|
||||
> **OpenCode platform:** Uses `@mention` dispatch instead of the Agent tool. All mentions in a single message run in parallel.
|
||||
|
||||
Dispatch one `@mention` per chunk — ALL in the same response:
|
||||
Call the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.
|
||||
|
||||
Concrete example for 3 chunks:
|
||||
```
|
||||
@agent Chunk CHUNK_NUM of TOTAL_CHUNKS: [extraction prompt below with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE substituted]
|
||||
|
||||
@agent Chunk 2 of TOTAL_CHUNKS: [next chunk]
|
||||
[Agent tool call 1: files 1-15]
|
||||
[Agent tool call 2: files 16-30]
|
||||
[Agent tool call 3: files 31-45]
|
||||
```
|
||||
All three in one message. Not three separate messages.
|
||||
|
||||
Wait for all agents to return. Parse each response as JSON. Accumulate nodes/edges/hyperedges across all results and write to `.graphify_semantic_new.json`.
|
||||
|
||||
The extraction prompt each agent receives (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE):
|
||||
Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE):
|
||||
|
||||
```
|
||||
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
|
||||
@@ -208,7 +195,7 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
@@ -235,16 +222,15 @@ Use sparingly — only when the group relationship adds information beyond the p
|
||||
If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author,
|
||||
contributor onto every node from that file.
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
confidence_score rules:
|
||||
- EXTRACTED edges: confidence_score must be 1.0
|
||||
- INFERRED edges: score 0.4-0.9 based on how certain you are.
|
||||
Strong structural inference (e.g. two classes clearly share data): 0.8-0.9.
|
||||
Reasonable but not certain: 0.6-0.7. Weak inference: 0.4-0.5.
|
||||
- AMBIGUOUS edges: score 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
```
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
@@ -257,29 +243,28 @@ If more than half the chunks failed, stop and tell the user.
|
||||
|
||||
Save new results to cache:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from graphify.cache import save_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[]}
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []))
|
||||
print(f'Cached {saved} files')
|
||||
"
|
||||
```
|
||||
|
||||
Merge cached + new results into `.graphify_semantic.json`:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
cached = json.loads(Path('.graphify_cached.json').read_text()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
cached = json.loads(Path('.graphify_cached.json').read_text()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[]}
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[]}
|
||||
|
||||
all_nodes = cached['nodes'] + new.get('nodes', [])
|
||||
all_edges = cached['edges'] + new.get('edges', [])
|
||||
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
|
||||
seen = set()
|
||||
deduped = []
|
||||
for n in all_nodes:
|
||||
@@ -290,7 +275,6 @@ for n in all_nodes:
|
||||
merged = {
|
||||
'nodes': deduped,
|
||||
'edges': all_edges,
|
||||
'hyperedges': all_hyperedges,
|
||||
'input_tokens': new.get('input_tokens', 0),
|
||||
'output_tokens': new.get('output_tokens', 0),
|
||||
}
|
||||
@@ -303,7 +287,7 @@ Clean up temp files: `rm -f .graphify_cached.json .graphify_uncached.txt .graphi
|
||||
#### Part C - Merge AST + semantic into final extraction
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from pathlib import Path
|
||||
|
||||
@@ -319,11 +303,9 @@ for n in sem['nodes']:
|
||||
seen.add(n['id'])
|
||||
|
||||
merged_edges = ast['edges'] + sem['edges']
|
||||
merged_hyperedges = sem.get('hyperedges', [])
|
||||
merged = {
|
||||
'nodes': merged_nodes,
|
||||
'edges': merged_edges,
|
||||
'hyperedges': merged_hyperedges,
|
||||
'input_tokens': sem.get('input_tokens', 0),
|
||||
'output_tokens': sem.get('output_tokens', 0),
|
||||
}
|
||||
@@ -338,7 +320,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
@@ -391,7 +373,7 @@ Read `.graphify_analysis.json`. For each community key, look at its node labels
|
||||
Then regenerate the report and save the labels for the visualizer:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import score_all
|
||||
@@ -424,14 +406,12 @@ print('Report updated with community labels')
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
### Step 6 - Generate Obsidian vault (default) + optional HTML
|
||||
|
||||
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
|
||||
|
||||
If `--obsidian` was given:
|
||||
**Always generate the Obsidian vault and HTML** - they are the primary visualizations. Skip both if `--no-viz` (report + JSON only).
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_obsidian, to_canvas
|
||||
@@ -459,10 +439,10 @@ print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries
|
||||
"
|
||||
```
|
||||
|
||||
Generate the HTML graph (always, unless `--no-viz`):
|
||||
Also generate the HTML graph (always, unless `--no-viz`):
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_html
|
||||
@@ -489,7 +469,7 @@ else:
|
||||
**If `--neo4j`** - generate a Cypher file for manual import:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_cypher
|
||||
@@ -504,7 +484,7 @@ print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt'
|
||||
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster
|
||||
@@ -526,7 +506,7 @@ Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default
|
||||
### Step 7b - SVG export (only if --svg flag)
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_svg
|
||||
@@ -548,7 +528,7 @@ print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
|
||||
### Step 7c - GraphML export (only if --graphml flag)
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_graphml
|
||||
@@ -590,7 +570,7 @@ To configure in Claude Desktop, add to `claude_desktop_config.json`:
|
||||
If `total_words` from `.graphify_detect.json` is greater than 5,000, run:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from graphify.benchmark import run_benchmark, print_benchmark
|
||||
from pathlib import Path
|
||||
@@ -608,7 +588,7 @@ Print the output directly in chat. If `total_words <= 5000`, skip silently - the
|
||||
### Step 9 - Save manifest, update cost tracker, clean up, and report
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
@@ -642,18 +622,26 @@ 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
|
||||
```
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
Tell the user:
|
||||
```
|
||||
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
|
||||
Graph complete. Outputs are in a hidden folder called graphify-out/ inside the directory you ran this on.
|
||||
|
||||
graph.html - interactive graph, open in browser
|
||||
GRAPH_REPORT.md - audit report
|
||||
graph.json - raw graph data
|
||||
obsidian/ - Obsidian vault (only if --obsidian was given)
|
||||
The folder is hidden (dot prefix) so it won't show in Finder or a normal ls.
|
||||
To see it:
|
||||
Mac/Linux: ls -la graphify-out/
|
||||
VS Code: the Explorer panel shows hidden files by default
|
||||
Finder: Cmd+Shift+. to toggle hidden files
|
||||
|
||||
What's inside:
|
||||
graphify-out/obsidian/ - open this folder as a vault in Obsidian (File > Open Vault)
|
||||
graphify-out/GRAPH_REPORT.md - full audit report, also readable here in Claude
|
||||
graphify-out/graph.json - persistent graph, query it later with /graphify query "..."
|
||||
|
||||
Full path: PATH_TO_DIR/graphify-out/
|
||||
```
|
||||
|
||||
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
|
||||
@@ -680,7 +668,7 @@ The graph is the map. Your job after the pipeline is to be the guide.
|
||||
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.detect import detect_incremental, save_manifest
|
||||
from pathlib import Path
|
||||
@@ -699,7 +687,7 @@ print(f'{new_total} new/changed file(s) to re-extract.')
|
||||
If new files exist, first check whether all changed files are code files:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
@@ -719,7 +707,7 @@ If `code_only` is False (any changed file is a doc/paper/image): run the full St
|
||||
Then:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_json
|
||||
@@ -746,7 +734,7 @@ Then run Steps 4–8 on the merged graph as normal.
|
||||
After Step 4, show the graph diff:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json
|
||||
from graphify.analyze import graph_diff
|
||||
from graphify.build import build_from_json
|
||||
@@ -780,7 +768,7 @@ Clean up after: `rm -f .graphify_old.json`
|
||||
Skip Steps 1–3. Load the existing graph from `graphify-out/graph.json` and re-run clustering:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections
|
||||
@@ -833,7 +821,7 @@ Two traversal modes - choose based on the question:
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -851,7 +839,7 @@ Load `graphify-out/graph.json`, then:
|
||||
5. If the graph lacks enough information, say so - do not hallucinate edges.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
@@ -942,7 +930,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 "
|
||||
python3 -c "
|
||||
from graphify.ingest import save_query_result
|
||||
from pathlib import Path
|
||||
save_query_result(
|
||||
@@ -966,7 +954,7 @@ Find the shortest path between two named concepts in the graph.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -976,7 +964,7 @@ if not Path('graphify-out/graph.json').exists():
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
@@ -1028,7 +1016,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 "
|
||||
python3 -c "
|
||||
from graphify.ingest import save_query_result
|
||||
from pathlib import Path
|
||||
save_query_result(
|
||||
@@ -1050,7 +1038,7 @@ Give a plain-language explanation of a single node - everything connected to it.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -1060,7 +1048,7 @@ if not Path('graphify-out/graph.json').exists():
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
@@ -1105,7 +1093,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 "
|
||||
python3 -c "
|
||||
from graphify.ingest import save_query_result
|
||||
from pathlib import Path
|
||||
save_query_result(
|
||||
@@ -1126,7 +1114,7 @@ print('Explanation saved to graphify-out/memory/')
|
||||
Fetch a URL and add it to the corpus, then update the graph.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
python3 -c "
|
||||
import sys
|
||||
from graphify.ingest import ingest
|
||||
from pathlib import Path
|
||||
Vendored
-32
@@ -1,32 +0,0 @@
|
||||
using namespace System.IO
|
||||
using module MyModule
|
||||
|
||||
function Get-Data {
|
||||
param(
|
||||
[string]$Name,
|
||||
[int]$Count = 10
|
||||
)
|
||||
$result = Process-Items -Name $Name -Count $Count
|
||||
return $result
|
||||
}
|
||||
|
||||
function Process-Items {
|
||||
param([string]$Name, [int]$Count)
|
||||
Write-Output "Processing $Count items for $Name"
|
||||
}
|
||||
|
||||
class DataProcessor {
|
||||
[string]$Source
|
||||
|
||||
DataProcessor([string]$source) {
|
||||
$this.Source = $source
|
||||
}
|
||||
|
||||
[string] Transform([string]$input) {
|
||||
return $input.ToUpper()
|
||||
}
|
||||
|
||||
[void] Save([string]$path) {
|
||||
Set-Content -Path $path -Value $this.Source
|
||||
}
|
||||
}
|
||||
Vendored
-73
@@ -1,73 +0,0 @@
|
||||
import Foundation
|
||||
import UIKit
|
||||
|
||||
protocol Processor {
|
||||
func process() -> [String]
|
||||
}
|
||||
|
||||
protocol Loggable {
|
||||
func log()
|
||||
}
|
||||
|
||||
class DataProcessor: Processor {
|
||||
private var items: [String] = []
|
||||
|
||||
init() {}
|
||||
|
||||
deinit {}
|
||||
|
||||
func addItem(_ item: String) {
|
||||
items.append(item)
|
||||
}
|
||||
|
||||
func process() -> [String] {
|
||||
return validate(items)
|
||||
}
|
||||
|
||||
private func validate(_ data: [String]) -> [String] {
|
||||
return data.filter { !$0.isEmpty }
|
||||
}
|
||||
}
|
||||
|
||||
struct Config {
|
||||
let baseUrl: String
|
||||
let timeout: Int
|
||||
|
||||
subscript(key: String) -> String? {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
enum NetworkError {
|
||||
case timeout
|
||||
case connectionFailed
|
||||
case unauthorized
|
||||
|
||||
func describe() -> String {
|
||||
return "error"
|
||||
}
|
||||
}
|
||||
|
||||
actor CacheManager {
|
||||
private var store: [String: String] = [:]
|
||||
|
||||
func get(_ key: String) -> String? {
|
||||
return store[key]
|
||||
}
|
||||
}
|
||||
|
||||
extension DataProcessor: Loggable {
|
||||
func log() {
|
||||
print("logging")
|
||||
}
|
||||
}
|
||||
|
||||
extension Config {
|
||||
func isValid() -> Bool {
|
||||
return !baseUrl.isEmpty
|
||||
}
|
||||
}
|
||||
|
||||
func createProcessor() -> DataProcessor {
|
||||
return DataProcessor()
|
||||
}
|
||||
Vendored
-37
@@ -1,37 +0,0 @@
|
||||
const std = @import("std");
|
||||
const mem = @import("std").mem;
|
||||
|
||||
const Point = struct {
|
||||
x: f64,
|
||||
y: f64,
|
||||
|
||||
pub fn distance(self: Point, other: Point) f64 {
|
||||
const dx = self.x - other.x;
|
||||
const dy = self.y - other.dy;
|
||||
return std.math.sqrt(dx * dx + dy * dy);
|
||||
}
|
||||
};
|
||||
|
||||
const Color = enum {
|
||||
red,
|
||||
green,
|
||||
blue,
|
||||
};
|
||||
|
||||
const Shape = union(enum) {
|
||||
circle: f64,
|
||||
rect: Point,
|
||||
};
|
||||
|
||||
pub fn add(a: i32, b: i32) i32 {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
pub fn multiply(a: i32, b: i32) i32 {
|
||||
return a * b;
|
||||
}
|
||||
|
||||
pub fn main() void {
|
||||
const result = add(1, 2);
|
||||
_ = multiply(result, 3);
|
||||
}
|
||||
+1
-35
@@ -1,5 +1,5 @@
|
||||
from pathlib import Path
|
||||
from graphify.detect import classify_file, count_words, detect, FileType, _looks_like_paper, _is_ignored, _load_graphifyignore
|
||||
from graphify.detect import classify_file, count_words, detect, FileType, _looks_like_paper
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
@@ -69,37 +69,3 @@ def test_classify_attention_paper():
|
||||
if paper_path.exists():
|
||||
result = classify_file(paper_path)
|
||||
assert result == FileType.PAPER
|
||||
|
||||
|
||||
def test_graphifyignore_excludes_file(tmp_path):
|
||||
"""Files matching .graphifyignore patterns are excluded from detect()."""
|
||||
(tmp_path / ".graphifyignore").write_text("vendor/\n*.generated.py\n")
|
||||
vendor = tmp_path / "vendor"
|
||||
vendor.mkdir()
|
||||
(vendor / "lib.py").write_text("x = 1")
|
||||
(tmp_path / "main.py").write_text("print('hi')")
|
||||
(tmp_path / "schema.generated.py").write_text("x = 1")
|
||||
|
||||
result = detect(tmp_path)
|
||||
file_list = result["files"]["code"]
|
||||
assert any("main.py" in f for f in file_list)
|
||||
assert not any("vendor" in f for f in file_list)
|
||||
assert not any("generated" in f for f in file_list)
|
||||
assert result["graphifyignore_patterns"] == 2
|
||||
|
||||
|
||||
def test_graphifyignore_missing_is_fine(tmp_path):
|
||||
"""No .graphifyignore is not an error."""
|
||||
(tmp_path / "main.py").write_text("x = 1")
|
||||
result = detect(tmp_path)
|
||||
assert result["graphifyignore_patterns"] == 0
|
||||
|
||||
|
||||
def test_graphifyignore_comments_ignored(tmp_path):
|
||||
"""Comment lines in .graphifyignore are not treated as patterns."""
|
||||
(tmp_path / ".graphifyignore").write_text("# this is a comment\n\nmain.py\n")
|
||||
(tmp_path / "main.py").write_text("x = 1")
|
||||
(tmp_path / "other.py").write_text("x = 2")
|
||||
result = detect(tmp_path)
|
||||
assert not any("main.py" in f for f in result["files"]["code"])
|
||||
assert any("other.py" in f for f in result["files"]["code"])
|
||||
@@ -60,8 +60,7 @@ def test_collect_files_from_dir():
|
||||
files = collect_files(FIXTURES)
|
||||
supported = {".py", ".js", ".ts", ".tsx", ".go", ".rs",
|
||||
".java", ".c", ".cpp", ".cc", ".cxx", ".rb",
|
||||
".cs", ".kt", ".kts", ".scala", ".php", ".h", ".hpp",
|
||||
".swift", ".lua", ".toc", ".zig", ".ps1"}
|
||||
".cs", ".kt", ".kts", ".scala", ".php", ".h", ".hpp"}
|
||||
assert all(f.suffix in supported for f in files)
|
||||
assert len(files) > 0
|
||||
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
"""Tests for graphify install --platform routing."""
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
import pytest
|
||||
|
||||
|
||||
PLATFORMS = {
|
||||
"claude": (".claude/skills/graphify/SKILL.md",),
|
||||
"codex": (".agents/skills/graphify/SKILL.md",),
|
||||
"opencode": (".config/opencode/skills/graphify/SKILL.md",),
|
||||
"claw": (".claw/skills/graphify/SKILL.md",),
|
||||
}
|
||||
|
||||
|
||||
def _install(tmp_path, platform):
|
||||
from graphify.__main__ import install
|
||||
with patch("graphify.__main__.Path.home", return_value=tmp_path):
|
||||
install(platform=platform)
|
||||
|
||||
|
||||
def test_install_default_claude(tmp_path):
|
||||
_install(tmp_path, "claude")
|
||||
assert (tmp_path / ".claude" / "skills" / "graphify" / "SKILL.md").exists()
|
||||
|
||||
|
||||
def test_install_codex(tmp_path):
|
||||
_install(tmp_path, "codex")
|
||||
assert (tmp_path / ".agents" / "skills" / "graphify" / "SKILL.md").exists()
|
||||
|
||||
|
||||
def test_install_opencode(tmp_path):
|
||||
_install(tmp_path, "opencode")
|
||||
assert (tmp_path / ".config" / "opencode" / "skills" / "graphify" / "SKILL.md").exists()
|
||||
|
||||
|
||||
def test_install_claw(tmp_path):
|
||||
_install(tmp_path, "claw")
|
||||
assert (tmp_path / ".claw" / "skills" / "graphify" / "SKILL.md").exists()
|
||||
|
||||
|
||||
def test_install_unknown_platform_exits(tmp_path):
|
||||
with pytest.raises(SystemExit):
|
||||
_install(tmp_path, "unknown")
|
||||
|
||||
|
||||
def test_codex_skill_contains_spawn_agent():
|
||||
"""Codex skill file must reference spawn_agent."""
|
||||
import graphify
|
||||
skill = (Path(graphify.__file__).parent / "skill-codex.md").read_text()
|
||||
assert "spawn_agent" in skill
|
||||
|
||||
|
||||
def test_opencode_skill_contains_mention():
|
||||
"""OpenCode skill file must reference @mention."""
|
||||
import graphify
|
||||
skill = (Path(graphify.__file__).parent / "skill-opencode.md").read_text()
|
||||
assert "@mention" in skill
|
||||
|
||||
|
||||
def test_claw_skill_is_sequential():
|
||||
"""OpenClaw skill file must describe sequential extraction."""
|
||||
import graphify
|
||||
skill = (Path(graphify.__file__).parent / "skill-claw.md").read_text()
|
||||
assert "sequential" in skill.lower()
|
||||
assert "spawn_agent" not in skill
|
||||
assert "@mention" not in skill
|
||||
|
||||
|
||||
def test_all_skill_files_exist_in_package():
|
||||
"""All four platform skill files must be present in the installed package."""
|
||||
import graphify
|
||||
pkg = Path(graphify.__file__).parent
|
||||
for name in ("skill.md", "skill-codex.md", "skill-opencode.md", "skill-claw.md"):
|
||||
assert (pkg / name).exists(), f"Missing: {name}"
|
||||
|
||||
|
||||
def test_claude_install_registers_claude_md(tmp_path):
|
||||
"""Claude platform install writes CLAUDE.md; others do not."""
|
||||
_install(tmp_path, "claude")
|
||||
assert (tmp_path / ".claude" / "CLAUDE.md").exists()
|
||||
|
||||
|
||||
def test_codex_install_does_not_write_claude_md(tmp_path):
|
||||
_install(tmp_path, "codex")
|
||||
assert not (tmp_path / ".claude" / "CLAUDE.md").exists()
|
||||
|
||||
|
||||
# --- always-on AGENTS.md install/uninstall tests ---
|
||||
|
||||
def _agents_install(tmp_path, platform):
|
||||
from graphify.__main__ import _agents_install as _install_fn
|
||||
_install_fn(tmp_path, platform)
|
||||
|
||||
|
||||
def _agents_uninstall(tmp_path):
|
||||
from graphify.__main__ import _agents_uninstall as _uninstall_fn
|
||||
_uninstall_fn(tmp_path)
|
||||
|
||||
|
||||
def test_codex_agents_install_writes_agents_md(tmp_path):
|
||||
_agents_install(tmp_path, "codex")
|
||||
agents_md = tmp_path / "AGENTS.md"
|
||||
assert agents_md.exists()
|
||||
assert "graphify" in agents_md.read_text()
|
||||
assert "GRAPH_REPORT.md" in agents_md.read_text()
|
||||
|
||||
|
||||
def test_opencode_agents_install_writes_agents_md(tmp_path):
|
||||
_agents_install(tmp_path, "opencode")
|
||||
assert (tmp_path / "AGENTS.md").exists()
|
||||
|
||||
|
||||
def test_claw_agents_install_writes_agents_md(tmp_path):
|
||||
_agents_install(tmp_path, "claw")
|
||||
assert (tmp_path / "AGENTS.md").exists()
|
||||
|
||||
|
||||
def test_agents_install_idempotent(tmp_path):
|
||||
"""Installing twice does not duplicate the section."""
|
||||
_agents_install(tmp_path, "codex")
|
||||
_agents_install(tmp_path, "codex")
|
||||
content = (tmp_path / "AGENTS.md").read_text()
|
||||
assert content.count("## graphify") == 1
|
||||
|
||||
|
||||
def test_agents_install_appends_to_existing(tmp_path):
|
||||
"""Installs into an existing AGENTS.md without overwriting other content."""
|
||||
agents_md = tmp_path / "AGENTS.md"
|
||||
agents_md.write_text("# Existing rules\n\nDo not break things.\n")
|
||||
_agents_install(tmp_path, "codex")
|
||||
content = agents_md.read_text()
|
||||
assert "Do not break things." in content
|
||||
assert "## graphify" in content
|
||||
|
||||
|
||||
def test_agents_uninstall_removes_section(tmp_path):
|
||||
_agents_install(tmp_path, "codex")
|
||||
_agents_uninstall(tmp_path)
|
||||
agents_md = tmp_path / "AGENTS.md"
|
||||
# File deleted when it only contained graphify section
|
||||
assert not agents_md.exists()
|
||||
|
||||
|
||||
def test_agents_uninstall_preserves_other_content(tmp_path):
|
||||
"""Uninstall keeps pre-existing content."""
|
||||
agents_md = tmp_path / "AGENTS.md"
|
||||
agents_md.write_text("# Existing rules\n\nDo not break things.\n")
|
||||
_agents_install(tmp_path, "codex")
|
||||
_agents_uninstall(tmp_path)
|
||||
assert agents_md.exists()
|
||||
content = agents_md.read_text()
|
||||
assert "Do not break things." in content
|
||||
assert "## graphify" not in content
|
||||
|
||||
|
||||
def test_agents_uninstall_no_op_when_not_installed(tmp_path, capsys):
|
||||
_agents_uninstall(tmp_path)
|
||||
out = capsys.readouterr().out
|
||||
assert "nothing to do" in out
|
||||
+1
-121
@@ -1,11 +1,10 @@
|
||||
"""Tests for language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift."""
|
||||
"""Tests for the 8 new language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP."""
|
||||
from __future__ import annotations
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from graphify.extract import (
|
||||
extract_java, extract_c, extract_cpp, extract_ruby,
|
||||
extract_csharp, extract_kotlin, extract_scala, extract_php,
|
||||
extract_swift,
|
||||
)
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
@@ -218,122 +217,3 @@ def test_php_finds_function():
|
||||
def test_php_finds_imports():
|
||||
r = extract_php(FIXTURES / "sample.php")
|
||||
assert "imports" in _relations(r)
|
||||
|
||||
|
||||
# ── Swift ────────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_swift_no_error():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert "error" not in r
|
||||
|
||||
def test_swift_finds_class():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("DataProcessor" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_protocol():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("Processor" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_struct():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("Config" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_methods():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
labels = _labels(r)
|
||||
assert any("addItem" in l for l in labels)
|
||||
assert any("process" in l for l in labels)
|
||||
|
||||
def test_swift_finds_function():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("createProcessor" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_imports():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert "imports" in _relations(r)
|
||||
|
||||
def test_swift_no_dangling_edges():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
node_ids = {n["id"] for n in r["nodes"]}
|
||||
for e in r["edges"]:
|
||||
assert e["source"] in node_ids
|
||||
|
||||
def test_swift_finds_actor():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("CacheManager" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_enum():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("NetworkError" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_enum_methods():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("describe" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_enum_cases():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
labels = _labels(r)
|
||||
assert any("timeout" in l for l in labels)
|
||||
assert any("connectionFailed" in l for l in labels)
|
||||
|
||||
def test_swift_enum_cases_have_case_of_edge():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
case_edges = [e for e in r["edges"] if e["relation"] == "case_of"]
|
||||
assert len(case_edges) >= 2
|
||||
|
||||
def test_swift_finds_deinit():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("deinit" in l for l in _labels(r))
|
||||
|
||||
def test_swift_finds_subscript():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert any("subscript" in l for l in _labels(r))
|
||||
|
||||
def test_swift_extension_methods_attach_to_type():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
method_edges = [e for e in r["edges"] if e["relation"] == "method"]
|
||||
found = False
|
||||
for e in method_edges:
|
||||
src_label = node_by_id.get(e["source"], "")
|
||||
tgt_label = node_by_id.get(e["target"], "")
|
||||
if "Config" in src_label and "isValid" in tgt_label:
|
||||
found = True
|
||||
break
|
||||
assert found, "extension method isValid should attach to Config"
|
||||
|
||||
def test_swift_extension_does_not_duplicate_type_node():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
config_nodes = [n for n in r["nodes"] if n["label"] == "Config"]
|
||||
assert len(config_nodes) == 1, f"Config should appear once, got {len(config_nodes)}"
|
||||
|
||||
def test_swift_conformance_edge():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
inherits_edges = [e for e in r["edges"] if e["relation"] == "inherits"]
|
||||
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
found = False
|
||||
for e in inherits_edges:
|
||||
src_label = node_by_id.get(e["source"], "")
|
||||
tgt_label = node_by_id.get(e["target"], "")
|
||||
if "DataProcessor" in src_label and "Processor" in tgt_label:
|
||||
found = True
|
||||
break
|
||||
assert found, "DataProcessor should have inherits edge to Processor"
|
||||
|
||||
def test_swift_extension_conformance_edge():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
inherits_edges = [e for e in r["edges"] if e["relation"] == "inherits"]
|
||||
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
found = False
|
||||
for e in inherits_edges:
|
||||
src_label = node_by_id.get(e["source"], "")
|
||||
tgt_label = node_by_id.get(e["target"], "")
|
||||
if "DataProcessor" in src_label and "Loggable" in tgt_label:
|
||||
found = True
|
||||
break
|
||||
assert found, "extension should add conformance edge DataProcessor -> Loggable"
|
||||
|
||||
def test_swift_emits_calls():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
calls = _calls(r)
|
||||
assert any("process" in src and "validate" in tgt for src, tgt in calls)
|
||||
+25
-24
@@ -1,6 +1,6 @@
|
||||
# Reproducible Example
|
||||
|
||||
A small document pipeline — parser, validator, processor, storage, API — with architecture notes and research notes. Seven files, two languages, clear call relationships between modules.
|
||||
A small document pipeline (parser, validator, processor, storage, API) with architecture notes and research notes. Six files, two languages, clear call relationships between modules.
|
||||
|
||||
Run graphify on it and you get a knowledge graph showing how the modules connect, which functions call which, and how the architecture notes relate to the code.
|
||||
|
||||
@@ -8,49 +8,50 @@ Run graphify on it and you get a knowledge graph showing how the modules connect
|
||||
|
||||
```
|
||||
raw/
|
||||
├── parser.py — reads files, detects format, kicks off the pipeline
|
||||
├── validator.py — schema checks, calls processor for text normalization
|
||||
├── processor.py — keyword extraction, cross-reference detection
|
||||
├── storage.py — persists everything, maintains the index
|
||||
├── api.py — HTTP handlers that orchestrate the above four modules
|
||||
├── architecture.md — design decisions and module responsibilities
|
||||
└── notes.md — open questions and tradeoffs
|
||||
├── parser.py reads files, detects format, kicks off the pipeline
|
||||
├── validator.py schema checks, calls processor for text normalization
|
||||
├── processor.py keyword extraction, cross-reference detection
|
||||
├── storage.py persists everything, maintains the index
|
||||
├── api.py HTTP handlers that orchestrate the above four modules
|
||||
├── architecture.md design decisions and module responsibilities
|
||||
└── notes.md open questions and tradeoffs, written informally
|
||||
```
|
||||
|
||||
## How to run
|
||||
## How to run it
|
||||
|
||||
```bash
|
||||
pip install graphifyy
|
||||
|
||||
graphify install # Claude Code
|
||||
graphify install --platform codex # Codex
|
||||
graphify install --platform opencode # OpenCode
|
||||
graphify install --platform claw # OpenClaw
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
Then open your AI coding assistant in this directory and type:
|
||||
Then open Claude Code in this directory and type:
|
||||
|
||||
```
|
||||
/graphify ./raw
|
||||
```
|
||||
|
||||
No PDF or image extraction — runs entirely on AST and markdown with no token cost for semantic extraction.
|
||||
Takes under a minute. No PDF or image extraction, so it runs entirely on AST and markdown parsing with no token cost for semantic extraction.
|
||||
|
||||
## What to expect
|
||||
|
||||
- `api.py` as a hub node connected to all four modules
|
||||
- `storage.py` as the highest-degree god node (everything reads and writes through it)
|
||||
- `parser.py` calling `validator.py` and `storage.py`
|
||||
- `architecture.md` and `notes.md` linked to the code modules they discuss
|
||||
- 2 communities: the four Python modules together, the two markdown files together (or api.py in its own cluster given high connectivity)
|
||||
The graph should show:
|
||||
|
||||
- api.py as a hub node connected to all four modules
|
||||
- parser.py calling validator.py and storage.py
|
||||
- validator.py calling processor.py for normalize_text
|
||||
- processor.py calling storage.py for load_index and save_processed
|
||||
- architecture.md and notes.md linked to the code modules they discuss
|
||||
|
||||
The community detection will likely cluster the four Python modules together and the two markdown files together, or split api.py into its own cluster given its high connectivity.
|
||||
|
||||
God nodes will be storage.py (everything reads and writes through it) and api.py (connects to everything at the top level).
|
||||
|
||||
## After it runs
|
||||
|
||||
Ask questions from your AI coding assistant:
|
||||
Ask questions in Claude Code and it answers from the graph:
|
||||
|
||||
- "what calls storage directly?"
|
||||
- "what is the shortest path between parser and processor?"
|
||||
- "which module has the most connections?"
|
||||
- "what does the architecture doc say about the storage design?"
|
||||
|
||||
The graph lives in `graphify-out/` and persists across sessions.
|
||||
The graph lives in graphify-out/ and persists across sessions.
|
||||
+24
-23
@@ -1,43 +1,44 @@
|
||||
# httpx Corpus Benchmark
|
||||
# httpx Corpus Benchmark — How to Reproduce
|
||||
|
||||
A synthetic 6-file Python codebase modeled after httpx's architecture. Tests graphify on a realistic library with clean layering: exceptions → models → auth/transport → client.
|
||||
A synthetic 6-file Python codebase modeled after httpx's architecture. Tests graphify
|
||||
on a realistic library codebase with clean layering: exceptions → models → auth/transport → client.
|
||||
|
||||
## Corpus (6 files)
|
||||
|
||||
All input files are in `raw/`:
|
||||
|
||||
```
|
||||
raw/
|
||||
├── exceptions.py — HTTPError hierarchy
|
||||
├── models.py — URL, Headers, Cookies, Request, Response
|
||||
├── auth.py — BasicAuth, BearerAuth, DigestAuth, NetRCAuth
|
||||
├── utils.py — header normalization, query params, content-type parsing
|
||||
├── transport.py — ConnectionPool, HTTPTransport, AsyncHTTPTransport, MockTransport
|
||||
└── client.py — Timeout, Limits, BaseClient, Client, AsyncClient
|
||||
├── exceptions.py — full HTTPError hierarchy (RequestError, TransportError, HTTPStatusError, etc.)
|
||||
├── models.py — URL, Headers, Cookies, Request, Response with raise_for_status
|
||||
├── auth.py — BasicAuth, BearerAuth, DigestAuth (challenge-response), NetRCAuth
|
||||
├── utils.py — header normalization, query param flattening, content-type parsing
|
||||
├── transport.py — ConnectionPool, HTTPTransport, AsyncHTTPTransport, MockTransport, ProxyTransport
|
||||
└── client.py — Timeout, Limits, BaseClient, Client (sync), AsyncClient
|
||||
```
|
||||
|
||||
## How to run
|
||||
|
||||
```bash
|
||||
pip install graphifyy
|
||||
|
||||
graphify install # Claude Code
|
||||
graphify install --platform codex # Codex
|
||||
graphify install --platform opencode # OpenCode
|
||||
graphify install --platform claw # OpenClaw
|
||||
```
|
||||
|
||||
Then open your AI coding assistant in this directory and type:
|
||||
|
||||
```
|
||||
pip install graphifyy && graphify install
|
||||
/graphify ./raw
|
||||
```
|
||||
|
||||
Or from the CLI directly:
|
||||
|
||||
```bash
|
||||
pip install graphifyy
|
||||
graphify ./raw
|
||||
```
|
||||
|
||||
## What to expect
|
||||
|
||||
- 144 nodes, 330 edges, 6 communities
|
||||
- God nodes: `Client`, `AsyncClient`, `Response`, `Request`, `BaseClient`, `HTTPTransport`
|
||||
- Surprising connection: `DigestAuth` linked to `Response` — auth.py reads Response to parse WWW-Authenticate headers
|
||||
- Token reduction: ~1x — 6 files fits in a context window, so there is no compression win here
|
||||
- Surprising connections: `DigestAuth` ↔ `Response` (auth.py reads Response to parse WWW-Authenticate)
|
||||
- **~1x token reduction** — 6 files fits in a context window, so there's no compression win here
|
||||
|
||||
The graph value on a small corpus is structural, not compressive: you can see the full dependency graph, identify god nodes, and understand architecture at a glance. Token reduction scales with corpus size — at 52 files (Karpathy benchmark) graphify achieves 71.5x.
|
||||
The graph value on a small corpus is structural, not compressive: you can see the full dependency graph, identify god nodes, and understand architecture at a glance. For token reduction to matter you need 20+ files. At 52 files (Karpathy repos benchmark) graphify achieves 71.5x.
|
||||
|
||||
Run `graphify benchmark worked/httpx/graph.json` to verify the numbers. Actual output is in this folder: `GRAPH_REPORT.md` and `graph.json`. Full eval: `review.md`.
|
||||
Run `graphify benchmark worked/httpx/graph.json` to verify the numbers yourself.
|
||||
Actual output is already in this folder: `GRAPH_REPORT.md` (human-readable) and `graph.json` (full graph data).
|
||||
@@ -1,6 +1,6 @@
|
||||
# Karpathy Repos Benchmark
|
||||
# Karpathy Repos Benchmark — How to Reproduce
|
||||
|
||||
This is the corpus that produced the **71.5x token reduction** benchmark.
|
||||
This is the corpus that produced the 71.5x token reduction benchmark.
|
||||
|
||||
## Corpus (52 files)
|
||||
|
||||
@@ -33,9 +33,9 @@ Put all files into a single folder called `raw/`:
|
||||
|
||||
```
|
||||
raw/
|
||||
├── nanoGPT/
|
||||
├── minGPT/
|
||||
├── micrograd/
|
||||
├── nanoGPT/ (cloned repo)
|
||||
├── minGPT/ (cloned repo)
|
||||
├── micrograd/ (cloned repo)
|
||||
├── attention.pdf
|
||||
├── flashattention.pdf
|
||||
├── flashattention2.pdf
|
||||
@@ -46,20 +46,10 @@ raw/
|
||||
└── moon_mlp.png
|
||||
```
|
||||
|
||||
Install and set up the skill for your platform:
|
||||
|
||||
```bash
|
||||
pip install graphifyy
|
||||
|
||||
graphify install # Claude Code
|
||||
graphify install --platform codex # Codex
|
||||
graphify install --platform opencode # OpenCode
|
||||
graphify install --platform claw # OpenClaw
|
||||
```
|
||||
|
||||
Then open your AI coding assistant in this directory and type:
|
||||
Then in Claude Code:
|
||||
|
||||
```
|
||||
pip install graphifyy && graphify install
|
||||
/graphify ./raw
|
||||
```
|
||||
|
||||
@@ -68,6 +58,6 @@ Then open your AI coding assistant in this directory and type:
|
||||
- ~285 nodes, ~340 edges, ~17 meaningful communities
|
||||
- God nodes: `Value` (micrograd), `GPT` (nanoGPT), `Training Script`, `Layer`
|
||||
- Surprising connections: nanoGPT Block and minGPT Block linked across repos, FlashAttention paper bridging into CausalSelfAttention in both repos
|
||||
- Token reduction: 71.5x vs reading all 52 files directly
|
||||
- Token reduction: 71.5x vs reading all 52 files cold
|
||||
|
||||
Actual output is in this folder: `GRAPH_REPORT.md` and `graph.json`. Full eval with scores: `review.md`.
|
||||
Full eval with scores and analysis: `review.md`
|
||||
@@ -1,43 +1,45 @@
|
||||
# Mixed Corpus Benchmark
|
||||
# Mixed Corpus Benchmark — How to Reproduce
|
||||
|
||||
A small mixed-input corpus: Python source files, a markdown paper with arXiv citations, and one image. Tests graphify on different file types in a single run.
|
||||
A small but realistic mixed-input corpus: Python source files, a markdown paper with
|
||||
arXiv citations, and one image. Tests graphify's ability to handle different file types
|
||||
in a single run.
|
||||
|
||||
## Corpus (5 files)
|
||||
|
||||
All input files are in `raw/`:
|
||||
|
||||
```
|
||||
raw/
|
||||
├── analyze.py — graph analysis module (god_nodes, surprising_connections)
|
||||
├── build.py — graph builder (build_from_json, NetworkX wrapper)
|
||||
├── cluster.py — Leiden community detection (cluster, score_all)
|
||||
├── attention_notes.md — Transformer paper notes (Vaswani et al., 2017) with arXiv citation
|
||||
├── analyze.py — graphify's graph analysis module (god_nodes, surprising_connections, etc.)
|
||||
├── build.py — graphify's graph builder (build_from_json, networkx wrapper)
|
||||
├── cluster.py — graphify's Leiden community detection (cluster, score_all)
|
||||
├── attention_notes.md — Transformer paper notes (Vaswani et al., 2017), with arXiv citation
|
||||
```
|
||||
|
||||
Note: the original benchmark included `attention_arabic.png` (an Arabic-language figure from the Attention paper). PNG files are not stored in this repo. To reproduce with the image, save any diagram from the Attention Is All You Need paper as `raw/attention_arabic.png`.
|
||||
Note: the original benchmark included `attention_arabic.png` (an Arabic-language figure from the
|
||||
Attention paper). PNG files are not stored in this repo. To reproduce with the image, save any
|
||||
diagram or figure from the Attention Is All You Need paper as `raw/attention_arabic.png`.
|
||||
|
||||
## How to run
|
||||
|
||||
```bash
|
||||
pip install graphifyy
|
||||
|
||||
graphify install # Claude Code
|
||||
graphify install --platform codex # Codex
|
||||
graphify install --platform opencode # OpenCode
|
||||
graphify install --platform claw # OpenClaw
|
||||
```
|
||||
|
||||
Then open your AI coding assistant in this directory and type:
|
||||
|
||||
```
|
||||
pip install graphifyy && graphify install
|
||||
/graphify ./raw
|
||||
```
|
||||
|
||||
Or from the CLI directly:
|
||||
|
||||
```bash
|
||||
pip install graphifyy
|
||||
graphify ./raw
|
||||
```
|
||||
|
||||
## What to expect
|
||||
|
||||
- ~20 nodes, ~19 edges from AST alone (3 Python modules)
|
||||
- 3 communities: Graph Analysis, Clustering and Scoring, Graph Building
|
||||
- 3 communities: Graph Analysis, Clustering & Scoring, Graph Building
|
||||
- God nodes: `analyze.py`, `cluster.py`, `build.py`
|
||||
- `attention_notes.md` classified as `paper` (arXiv heuristic fires on `1706.03762`)
|
||||
- If you include the image: 1 extra node describing the figure content via vision
|
||||
- Token reduction: 5.4x
|
||||
|
||||
Actual output is in this folder: `GRAPH_REPORT.md` and `graph.json`. Full eval: `review.md`.
|
||||
Full eval with scores and analysis: `review.md`
|
||||
Reference in new issue
Block a user