Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a785b64c6e | ||
|
|
066e4ba3ef | ||
|
|
b22c3605c4 | ||
|
|
472d9e1e27 | ||
|
|
a74ab7e1b3 | ||
|
|
ba13c7060b | ||
|
|
2d31aa2072 | ||
|
|
58cd072a72 | ||
|
|
5ef4373ed9 | ||
|
|
ce7bfe8ff3 | ||
|
|
9e8db8ba3f | ||
|
|
1184e7d4d5 | ||
|
|
d3c7f950d5 | ||
|
|
5f02b3dfe1 | ||
|
|
5164d972ed | ||
|
|
6dc07e5f99 | ||
|
|
ccdd465a08 | ||
|
|
90fac738e2 | ||
|
|
83c2f4245c | ||
|
|
b37f187767 | ||
|
|
6fe4c01bb8 | ||
|
|
a7fc2493f0 | ||
|
|
494f519bf4 | ||
|
|
d23ae1774d | ||
|
|
e6fefa8a2c | ||
|
|
0f11f6a32d | ||
|
|
e8b8e2039d |
No files matched your search
@@ -2,9 +2,9 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["v1", "main"]
|
||||
branches: ["v1", "v2", "v3", "main"]
|
||||
pull_request:
|
||||
branches: ["v1", "main"]
|
||||
branches: ["v1", "v2", "v3", "main"]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
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,8 +1,11 @@
|
||||
# graphify
|
||||
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://pypi.org/project/graphifyy/)
|
||||
|
||||
**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.
|
||||
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, or OpenClaw - 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.
|
||||
|
||||
> Andrej Karpathy keeps a `/raw` folder where he drops papers, tweets, screenshots, and notes. graphify is the answer to that problem - 71.5x fewer tokens per query vs reading the raw files, persistent across sessions, honest about what it found vs guessed.
|
||||
|
||||
@@ -13,16 +16,22 @@
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interactive graph - click nodes, search, filter by community
|
||||
├── obsidian/ open as Obsidian vault
|
||||
├── wiki/ Wikipedia-style articles for agent navigation (--wiki)
|
||||
├── GRAPH_REPORT.md god nodes, surprising connections, suggested questions
|
||||
├── graph.json persistent graph - query weeks later without re-reading
|
||||
└── cache/ SHA256 cache - re-runs only process changed files
|
||||
```
|
||||
|
||||
## 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:** [Claude Code](https://claude.ai/code) and Python 3.10+
|
||||
**Requires:** Python 3.10+ and one of: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), or [OpenClaw](https://openclaw.ai)
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
@@ -30,18 +39,46 @@ 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`.
|
||||
|
||||
Then open Claude Code in any directory and type:
|
||||
### Platform support
|
||||
|
||||
| Platform | Install command |
|
||||
|----------|----------------|
|
||||
| Claude Code | `graphify install` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
|
||||
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. OpenClaw uses sequential extraction (parallel agent support is still early on that platform).
|
||||
|
||||
Then open your AI coding assistant and type:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
### Make your assistant 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` |
|
||||
|
||||
**Claude Code** does two things: writes a `CLAUDE.md` section telling Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs a **PreToolUse hook** (`settings.json`) that fires before every Glob and Grep call. If a knowledge graph exists, Claude sees: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ — so Claude navigates via the graph instead of grepping through every file.
|
||||
|
||||
**Codex, OpenCode, OpenClaw** write the same rules to `AGENTS.md` in your project root. These platforms don't support PreToolUse hooks, so AGENTS.md is the always-on mechanism.
|
||||
|
||||
Uninstall with the matching uninstall command (e.g. `graphify claude uninstall`).
|
||||
|
||||
<details>
|
||||
<summary>Manual install (curl)</summary>
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/graphify
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v1/skills/graphify/skill.md \
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
|
||||
> ~/.claude/skills/graphify/SKILL.md
|
||||
```
|
||||
|
||||
@@ -61,11 +98,18 @@ 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"
|
||||
|
||||
@@ -74,17 +118,28 @@ 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
|
||||
|
||||
graphify hook install # post-commit git hook - rebuilds graph on every commit automatically
|
||||
# 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)
|
||||
```
|
||||
|
||||
Works with any mix of file types:
|
||||
|
||||
| Type | Extensions | Extraction |
|
||||
|------|-----------|------------|
|
||||
| Code | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php` | AST via tree-sitter + call-graph pass |
|
||||
| Docs | `.md .txt .rst` | Concepts + relationships via Claude |
|
||||
| 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 |
|
||||
|
||||
@@ -96,16 +151,22 @@ Works with any mix of file types:
|
||||
|
||||
**Suggested questions** - 4-5 questions the graph is uniquely positioned to answer
|
||||
|
||||
**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 "why"** - docstrings, inline comments (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), and design rationale from docs are extracted as `rationale_for` nodes. Not just what the code does - why it was written that way.
|
||||
|
||||
**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. Useful for agentic workflows where multiple agents are writing code in parallel - the graph stays current between waves automatically.
|
||||
**Confidence scores** - every INFERRED edge has a `confidence_score` (0.0-1.0). You know not just what was guessed but how confident the model was. EXTRACTED edges are always 1.0.
|
||||
|
||||
**Git commit hook** (`graphify hook install`) - installs a post-commit hook that rebuilds the graph after every commit. No background process needed. Triggers once per commit, works with any editor, safe to add alongside existing hooks.
|
||||
**Semantic similarity edges** - cross-file conceptual links with no structural connection. Two functions solving the same problem without calling each other, a class in code and a concept in a paper describing the same algorithm.
|
||||
|
||||
**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.
|
||||
|
||||
**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. 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.
|
||||
|
||||
Every edge is tagged `EXTRACTED`, `INFERRED`, or `AMBIGUOUS` - you always know what was found vs guessed.
|
||||
|
||||
## Worked examples
|
||||
|
||||
| Corpus | Files | Reduction | Output |
|
||||
@@ -116,6 +177,10 @@ Every edge is tagged `EXTRACTED`, `INFERRED`, or `AMBIGUOUS` - you always know w
|
||||
|
||||
Token reduction scales with corpus size. 6 files fits in a context window anyway, so graph value there is structural clarity, not compression. At 52 files (code + papers + images) you get 71x+. Each `worked/` folder has the raw input files and the actual output (`GRAPH_REPORT.md`, `graph.json`) so you can run it yourself and verify the numbers.
|
||||
|
||||
## 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.
|
||||
|
||||
## Tech stack
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + Claude + vis.js. No Neo4j required, no server, runs entirely locally.
|
||||
|
||||
@@ -0,0 +1,581 @@
|
||||
# v3 Platform Compatibility Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add Codex, OpenCode, and OpenClaw platform support via platform-specific skill files and a `graphify install --platform X` flag.
|
||||
|
||||
**Architecture:** The only section that differs between platforms is Step B2 (semantic extraction subagent dispatch) in skill.md. Three new skill files are created — one per platform — each identical to skill.md except for that one section. The `install()` function in `__main__.py` gains a `--platform` flag that copies the right skill file to the right config directory.
|
||||
|
||||
**Tech Stack:** Python 3.10+, pathlib, shutil, argparse (no new deps)
|
||||
|
||||
---
|
||||
|
||||
## File Map
|
||||
|
||||
| File | Action | Purpose |
|
||||
|------|--------|---------|
|
||||
| `graphify/skill.md` | Read-only | Source of truth — unchanged |
|
||||
| `graphify/skill-codex.md` | Create | Codex variant (spawn_agent + wait) |
|
||||
| `graphify/skill-opencode.md` | Create | OpenCode variant (@mention dispatch) |
|
||||
| `graphify/skill-claw.md` | Create | OpenClaw variant (sequential extraction) |
|
||||
| `graphify/__main__.py` | Modify | Add --platform flag to install() and main() |
|
||||
| `pyproject.toml` | Modify | Add 3 new skill files to package-data |
|
||||
| `tests/test_install.py` | Create | Platform routing tests |
|
||||
| `README.md` | Modify | Platform table + token efficiency clarification |
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Create the v3 branch
|
||||
|
||||
**Files:** none (git only)
|
||||
|
||||
- [ ] **Step 1: Create and switch to v3 branch**
|
||||
|
||||
```bash
|
||||
cd /home/safi/graphify
|
||||
git checkout -b v3
|
||||
```
|
||||
|
||||
Expected: `Switched to a new branch 'v3'`
|
||||
|
||||
- [ ] **Step 2: Verify branch**
|
||||
|
||||
```bash
|
||||
git branch --show-current
|
||||
```
|
||||
|
||||
Expected: `v3`
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Create `skill-codex.md`
|
||||
|
||||
skill-codex.md is identical to skill.md with one change: Step B2 replaces `Agent` tool calls with `spawn_agent` + `wait` + `close_agent` calls.
|
||||
|
||||
**Files:**
|
||||
- Create: `graphify/skill-codex.md`
|
||||
|
||||
- [ ] **Step 1: Copy skill.md as the base**
|
||||
|
||||
```bash
|
||||
cp graphify/skill.md graphify/skill-codex.md
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Open `graphify/skill-codex.md` and replace the Step B2 section**
|
||||
|
||||
Find this block (starts at "**Step B2 - Dispatch ALL subagents in a single message**", ends before "**Step B3**"):
|
||||
|
||||
Replace the entire Step B2 section with:
|
||||
|
||||
```markdown
|
||||
**Step B2 - Dispatch ALL subagents in a single message (Codex)**
|
||||
|
||||
> **Codex platform:** This step uses `spawn_agent` + `wait` + `close_agent` instead of the Agent tool.
|
||||
> Requires `multi_agent = true` in `~/.codex/config.toml`. If you get an error about multi-agent support, ask the user to add that config line and restart Codex.
|
||||
|
||||
Call `spawn_agent` once per chunk — all in the same response so they run in parallel:
|
||||
|
||||
```
|
||||
spawn_agent(agent_type="worker", message="Your task is to perform the following. Follow the instructions below exactly.\n\n<agent-instructions>\nYou are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.\nOutput ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble.\n\nFiles (chunk CHUNK_NUM of TOTAL_CHUNKS):\nFILE_LIST\n\n[copy the extraction rules and JSON schema verbatim from the existing Step B2 content — it's already in the file from the cp step]\n</agent-instructions>\n\nExecute this now. Output ONLY the structured JSON response.")
|
||||
```
|
||||
|
||||
Collect all handles. Then for each handle:
|
||||
```
|
||||
result = wait(handle)
|
||||
close_agent(handle)
|
||||
```
|
||||
|
||||
Parse each result as JSON. Accumulate nodes/edges/hyperedges across all results into `.graphify_semantic_new.json`.
|
||||
|
||||
If `spawn_agent` is not available, tell the user: "Codex multi-agent support is not enabled. Add `multi_agent = true` under `[features]` in `~/.codex/config.toml` and restart Codex."
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify the file looks correct**
|
||||
|
||||
```bash
|
||||
grep -n "spawn_agent\|Step B2\|Step B3" graphify/skill-codex.md | head -20
|
||||
```
|
||||
|
||||
Expected: lines showing spawn_agent in B2 and Step B3 after it.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add graphify/skill-codex.md
|
||||
git commit -m "add skill-codex.md for Codex platform (spawn_agent parallel extraction)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Create `skill-opencode.md`
|
||||
|
||||
**Files:**
|
||||
- Create: `graphify/skill-opencode.md`
|
||||
|
||||
- [ ] **Step 1: Copy skill.md as the base**
|
||||
|
||||
```bash
|
||||
cp graphify/skill.md graphify/skill-opencode.md
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Open `graphify/skill-opencode.md` and replace the Step B2 section**
|
||||
|
||||
Replace the entire Step B2 section with:
|
||||
|
||||
```markdown
|
||||
**Step B2 - Dispatch ALL subagents in a single message (OpenCode)**
|
||||
|
||||
> **OpenCode platform:** This step uses OpenCode's `@mention` dispatch instead of the Agent tool.
|
||||
|
||||
Dispatch all chunks in a single response. Each `@mention` runs in parallel:
|
||||
|
||||
```
|
||||
@agent Chunk CHUNK_NUM of TOTAL_CHUNKS: You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment. Output ONLY valid JSON matching the schema below.
|
||||
|
||||
Files:
|
||||
FILE_LIST
|
||||
|
||||
[copy the extraction rules and JSON schema verbatim from the existing Step B2 content — already in the file from the cp step]
|
||||
```
|
||||
|
||||
One `@mention` block per chunk. All in the same message — this is what makes them parallel.
|
||||
|
||||
Wait for all agents to return. Parse each response as JSON. Accumulate nodes/edges/hyperedges across all results into `.graphify_semantic_new.json`.
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify the file looks correct**
|
||||
|
||||
```bash
|
||||
grep -n "@mention\|Step B2\|Step B3" graphify/skill-opencode.md | head -20
|
||||
```
|
||||
|
||||
Expected: lines showing @mention in B2 and Step B3 after it.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add graphify/skill-opencode.md
|
||||
git commit -m "add skill-opencode.md for OpenCode platform (@mention parallel extraction)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Create `skill-claw.md`
|
||||
|
||||
OpenClaw's agent support is MVP/incomplete so extraction is sequential — the orchestrating LLM reads each file and extracts directly.
|
||||
|
||||
**Files:**
|
||||
- Create: `graphify/skill-claw.md`
|
||||
|
||||
- [ ] **Step 1: Copy skill.md as the base**
|
||||
|
||||
```bash
|
||||
cp graphify/skill.md graphify/skill-claw.md
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Open `graphify/skill-claw.md` and replace the Step B2 section**
|
||||
|
||||
Replace the entire Step B2 section with:
|
||||
|
||||
```markdown
|
||||
**Step B2 - Sequential extraction (OpenClaw)**
|
||||
|
||||
> **OpenClaw platform:** OpenClaw's multi-agent support is still early. Extraction runs sequentially — you read each file yourself and extract directly. This is slower than parallel platforms but reliable.
|
||||
|
||||
Load files from `.graphify_uncached.txt`. For each file, one at a time:
|
||||
|
||||
1. Read the file contents
|
||||
2. Extract nodes, edges, and hyperedges following the same rules and schema as the parallel variant (see schema below)
|
||||
3. Accumulate results into a running JSON object
|
||||
|
||||
Apply all the same extraction rules:
|
||||
- EXTRACTED / INFERRED / AMBIGUOUS confidence with confidence_score on every edge
|
||||
- rationale_for nodes for design decisions and WHY comments
|
||||
- semantically_similar_to edges for cross-file conceptual links (non-obvious only)
|
||||
- hyperedges for groups of 3+ nodes (max 3 per file)
|
||||
- DEEP_MODE: more aggressive INFERRED edges if --mode deep was given
|
||||
|
||||
Schema (same as parallel variant):
|
||||
{"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}
|
||||
|
||||
After processing all files, write the accumulated result to `.graphify_semantic_new.json`.
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Also remove the timing estimate block from Step B**
|
||||
|
||||
In skill-claw.md, find and remove this paragraph (it only applies to parallel dispatch):
|
||||
|
||||
```
|
||||
Before dispatching subagents, print a timing estimate:
|
||||
- Load `total_words` and file counts from `.graphify_detect.json`
|
||||
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
|
||||
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
|
||||
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
|
||||
```
|
||||
|
||||
Replace with:
|
||||
|
||||
```
|
||||
Print: "Semantic extraction: N files (sequential — OpenClaw platform)"
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify**
|
||||
|
||||
```bash
|
||||
grep -n "sequential\|Step B2\|Step B3\|spawn_agent\|@mention" graphify/skill-claw.md | head -20
|
||||
```
|
||||
|
||||
Expected: "sequential" appears in B2, no spawn_agent or @mention.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add graphify/skill-claw.md
|
||||
git commit -m "add skill-claw.md for OpenClaw platform (sequential extraction)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: Update `pyproject.toml` package-data
|
||||
|
||||
**Files:**
|
||||
- Modify: `pyproject.toml`
|
||||
|
||||
- [ ] **Step 1: Update package-data to include the three new skill files**
|
||||
|
||||
In `pyproject.toml`, find:
|
||||
|
||||
```toml
|
||||
[tool.setuptools.package-data]
|
||||
graphify = ["skill.md"]
|
||||
```
|
||||
|
||||
Replace with:
|
||||
|
||||
```toml
|
||||
[tool.setuptools.package-data]
|
||||
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-claw.md"]
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify**
|
||||
|
||||
```bash
|
||||
grep -A2 "package-data" pyproject.toml
|
||||
```
|
||||
|
||||
Expected: all four skill files listed.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add pyproject.toml
|
||||
git commit -m "include platform skill files in package-data"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Add `--platform` flag to install command
|
||||
|
||||
**Files:**
|
||||
- Modify: `graphify/__main__.py`
|
||||
|
||||
- [ ] **Step 1: Write the failing test first**
|
||||
|
||||
Create `tests/test_install.py`:
|
||||
|
||||
```python
|
||||
"""Tests for graphify install --platform routing."""
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
PLATFORMS = {
|
||||
"claude": ("skill.md", ".claude/skills/graphify/SKILL.md"),
|
||||
"codex": ("skill-codex.md", ".agents/skills/graphify/SKILL.md"),
|
||||
"opencode": ("skill-opencode.md", ".config/opencode/skills/graphify/SKILL.md"),
|
||||
"claw": ("skill-claw.md", ".claw/skills/graphify/SKILL.md"),
|
||||
}
|
||||
|
||||
|
||||
def test_install_default_uses_claude_skill(tmp_path):
|
||||
"""install() with no platform copies skill.md to ~/.claude/skills/graphify/SKILL.md"""
|
||||
from graphify.__main__ import install
|
||||
with patch("graphify.__main__.Path.home", return_value=tmp_path):
|
||||
install(platform="claude")
|
||||
dst = tmp_path / ".claude" / "skills" / "graphify" / "SKILL.md"
|
||||
assert dst.exists()
|
||||
|
||||
|
||||
def test_install_codex_copies_correct_file(tmp_path):
|
||||
from graphify.__main__ import install
|
||||
with patch("graphify.__main__.Path.home", return_value=tmp_path):
|
||||
install(platform="codex")
|
||||
dst = tmp_path / ".agents" / "skills" / "graphify" / "SKILL.md"
|
||||
assert dst.exists()
|
||||
|
||||
|
||||
def test_install_opencode_copies_correct_file(tmp_path):
|
||||
from graphify.__main__ import install
|
||||
with patch("graphify.__main__.Path.home", return_value=tmp_path):
|
||||
install(platform="opencode")
|
||||
dst = tmp_path / ".config" / "opencode" / "skills" / "graphify" / "SKILL.md"
|
||||
assert dst.exists()
|
||||
|
||||
|
||||
def test_install_claw_copies_correct_file(tmp_path):
|
||||
from graphify.__main__ import install
|
||||
with patch("graphify.__main__.Path.home", return_value=tmp_path):
|
||||
install(platform="claw")
|
||||
dst = tmp_path / ".claw" / "skills" / "graphify" / "SKILL.md"
|
||||
assert dst.exists()
|
||||
|
||||
|
||||
def test_install_unknown_platform_exits(tmp_path):
|
||||
from graphify.__main__ import install
|
||||
with patch("graphify.__main__.Path.home", return_value=tmp_path):
|
||||
with pytest.raises(SystemExit):
|
||||
install(platform="unknown")
|
||||
|
||||
|
||||
def test_all_skill_files_exist_in_package():
|
||||
"""Verify all platform skill files are present in the installed package."""
|
||||
import graphify
|
||||
pkg_dir = Path(graphify.__file__).parent
|
||||
for src_name, _ in PLATFORMS.values():
|
||||
skill_path = pkg_dir / src_name
|
||||
assert skill_path.exists(), f"Missing skill file: {src_name}"
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test to verify it fails**
|
||||
|
||||
```bash
|
||||
python -m pytest tests/test_install.py -v --tb=short 2>&1 | head -40
|
||||
```
|
||||
|
||||
Expected: FAIL — `install()` doesn't accept a `platform` argument yet.
|
||||
|
||||
- [ ] **Step 3: Update `install()` in `graphify/__main__.py`**
|
||||
|
||||
Replace the current `install()` function and add `_PLATFORM_CONFIG`:
|
||||
|
||||
```python
|
||||
_PLATFORM_CONFIG = {
|
||||
"claude": {
|
||||
"skill_file": "skill.md",
|
||||
"skill_dst": Path(".claude") / "skills" / "graphify" / "SKILL.md",
|
||||
"claude_md": True, # only Claude Code gets CLAUDE.md registration
|
||||
},
|
||||
"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,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
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"]
|
||||
if not skill_src.exists():
|
||||
print(f"error: {cfg['skill_file']} not found in package - reinstall graphify", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
skill_dst = Path.home() / cfg["skill_dst"]
|
||||
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}")
|
||||
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()
|
||||
print(" /graphify .")
|
||||
print()
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Update `main()` to pass `--platform` to `install()`**
|
||||
|
||||
In `main()`, find the `if cmd == "install":` block:
|
||||
|
||||
```python
|
||||
if cmd == "install":
|
||||
install()
|
||||
```
|
||||
|
||||
Replace with:
|
||||
|
||||
```python
|
||||
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)
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Update the help text in `main()`**
|
||||
|
||||
Find:
|
||||
```python
|
||||
print(" install copy skill to ~/.claude/skills/ and register in CLAUDE.md")
|
||||
```
|
||||
|
||||
Replace with:
|
||||
```python
|
||||
print(" install [--platform P] copy skill to platform config dir (claude|codex|opencode|claw)")
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Run tests to verify they pass**
|
||||
|
||||
```bash
|
||||
python -m pytest tests/test_install.py -v --tb=short
|
||||
```
|
||||
|
||||
Expected: all 6 tests PASS.
|
||||
|
||||
- [ ] **Step 7: Run the full test suite to check for regressions**
|
||||
|
||||
```bash
|
||||
python -m pytest tests/ -q --tb=short 2>&1 | tail -20
|
||||
```
|
||||
|
||||
Expected: existing tests still pass.
|
||||
|
||||
- [ ] **Step 8: Commit**
|
||||
|
||||
```bash
|
||||
git add graphify/__main__.py tests/test_install.py
|
||||
git commit -m "add --platform flag to graphify install (codex, opencode, claw)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 7: Update README
|
||||
|
||||
**Files:**
|
||||
- Modify: `README.md`
|
||||
|
||||
- [ ] **Step 1: Add platform support table under the Install section**
|
||||
|
||||
After the `pip install graphifyy && graphify install` code block, add:
|
||||
|
||||
```markdown
|
||||
### Platform support
|
||||
|
||||
| Platform | Install command |
|
||||
|----------|----------------|
|
||||
| Claude Code | `graphify install` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
|
||||
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. OpenClaw uses sequential extraction (parallel agent support is still early on that platform).
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Clarify token efficiency — find the benchmark section**
|
||||
|
||||
Find the line:
|
||||
```
|
||||
**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.
|
||||
```
|
||||
|
||||
Replace with:
|
||||
```
|
||||
**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.
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify README renders correctly**
|
||||
|
||||
```bash
|
||||
grep -n "Platform support\|multi_agent\|first run extracts" README.md
|
||||
```
|
||||
|
||||
Expected: all three lines found.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add README.md
|
||||
git commit -m "add platform support table and clarify token efficiency in README"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 8: Final verification
|
||||
|
||||
- [ ] **Step 1: Run the full test suite**
|
||||
|
||||
```bash
|
||||
python -m pytest tests/ -q --tb=short 2>&1 | tail -20
|
||||
```
|
||||
|
||||
Expected: all tests pass, no regressions.
|
||||
|
||||
- [ ] **Step 2: Verify all four skill files are present in the package**
|
||||
|
||||
```bash
|
||||
ls graphify/skill*.md
|
||||
```
|
||||
|
||||
Expected:
|
||||
```
|
||||
graphify/skill.md
|
||||
graphify/skill-codex.md
|
||||
graphify/skill-opencode.md
|
||||
graphify/skill-claw.md
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Smoke test each install path**
|
||||
|
||||
```bash
|
||||
python -m graphify.__main__ install --platform codex 2>&1 | head -5
|
||||
python -m graphify.__main__ install --platform opencode 2>&1 | head -5
|
||||
python -m graphify.__main__ install --platform claw 2>&1 | head -5
|
||||
python -m graphify.__main__ install --platform unknown 2>&1
|
||||
```
|
||||
|
||||
Expected: first three print "skill installed →", last prints "error: unknown platform".
|
||||
|
||||
- [ ] **Step 4: Push v3 branch**
|
||||
|
||||
```bash
|
||||
git push -u origin v3
|
||||
```
|
||||
@@ -0,0 +1,92 @@
|
||||
# v3 Platform Compatibility Design
|
||||
|
||||
**Date:** 2026-04-06
|
||||
**Status:** Approved
|
||||
|
||||
## Problem
|
||||
|
||||
graphify's `skill.md` uses the Claude Code `Agent` tool for parallel semantic extraction. Users on Codex, OpenCode, and OpenClaw cannot use the skill. v3 adds platform-specific skill files so graphify works natively on all four platforms.
|
||||
|
||||
## Scope
|
||||
|
||||
- Four platform-specific skill files (one already exists)
|
||||
- `graphify install --platform X` routing
|
||||
- README clarifications (token efficiency, platform table)
|
||||
- No always-on project hooks for non-Claude-Code platforms in v3 (deferred to v3.1)
|
||||
|
||||
## What Changes Per Platform
|
||||
|
||||
The semantic extraction step (Step 3B) is the **only** section that differs. AST extraction, merging, clustering, labelling, export, and benchmarking are identical across all platforms and live in the shared Python CLI.
|
||||
|
||||
| Platform | Extraction approach | Rationale |
|
||||
|----------|-------------------|-----------|
|
||||
| Claude Code | Parallel `Agent` tool calls | Current behavior, unchanged |
|
||||
| Codex | Parallel `spawn_agent` + `wait` + `close_agent` | Codex multi-agent API (`multi_agent = true` required) |
|
||||
| OpenCode | Parallel `@mention` dispatches | OpenCode's native subagent system |
|
||||
| OpenClaw | Sequential loop — orchestrator extracts each file itself | OpenClaw agent support is MVP/incomplete; sequential is reliable |
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
graphify/
|
||||
├── skill.md # Claude Code (unchanged)
|
||||
├── skill-codex.md # Codex — parallel via spawn_agent
|
||||
├── skill-opencode.md # OpenCode — parallel via @mention
|
||||
├── skill-claw.md # OpenClaw — sequential extraction
|
||||
```
|
||||
|
||||
All four files ship in the PyPI package via `pyproject.toml` `package-data`.
|
||||
|
||||
## Install Command
|
||||
|
||||
`graphify install` gains a `--platform` flag:
|
||||
|
||||
```
|
||||
graphify install # Claude Code → ~/.claude/skills/graphify/SKILL.md
|
||||
graphify install --platform codex # Codex → ~/.agents/skills/graphify/SKILL.md
|
||||
graphify install --platform opencode # OpenCode → ~/.config/opencode/skills/graphify/SKILL.md
|
||||
graphify install --platform claw # OpenClaw → ~/.claw/skills/graphify/SKILL.md
|
||||
```
|
||||
|
||||
Behaviour:
|
||||
- Creates target directory if it doesn't exist (same as current Claude Code install)
|
||||
- If the platform's root config directory doesn't exist, prints a warning and exits cleanly: `"Codex config directory not found — is Codex installed?"`
|
||||
- `--platform` is optional; default is `claude` (current behaviour preserved)
|
||||
|
||||
## Skill File Content
|
||||
|
||||
Each file follows the same structure as `skill.md`. The extraction step (Step 3B) is rewritten for the platform:
|
||||
|
||||
**Codex (`skill-codex.md`):**
|
||||
- For each uncached file, call `spawn_agent(agent_type="worker", message=<extraction prompt>)`
|
||||
- Collect all agent handles, call `wait()` on each, then `close_agent()`
|
||||
- Requires user to have `multi_agent = true` in `~/.codex/config.toml`; skill notes this requirement
|
||||
|
||||
**OpenCode (`skill-opencode.md`):**
|
||||
- For each uncached file, dispatch via `@mention` with the extraction prompt
|
||||
- Collect results as agents complete
|
||||
|
||||
**OpenClaw (`skill-claw.md`):**
|
||||
- Loop over uncached files sequentially
|
||||
- Orchestrating LLM reads each file and extracts concepts/relationships/edges directly
|
||||
- Slower than parallel platforms but reliable given OpenClaw's MVP agent status
|
||||
- A note in the skill explains why: "OpenClaw's multi-agent support is still early; sequential extraction ensures reliability"
|
||||
|
||||
## README Changes
|
||||
|
||||
1. Add "Platform support" table under the Install section
|
||||
2. Clarify token efficiency: *"First run extracts and builds the graph — subsequent queries read the compact graph instead of raw files. The 71.5x reduction applies per query, and the cache means re-runs only re-process changed files."*
|
||||
3. Note sequential extraction on OpenClaw with brief explanation
|
||||
|
||||
## Not In Scope (v3)
|
||||
|
||||
- `graphify codex install` / `graphify opencode install` (always-on project hooks for non-CC platforms) — deferred to v3.1
|
||||
- Gemini CLI support — not enough information yet
|
||||
- Copilot CLI support — not enough information yet
|
||||
|
||||
## Testing
|
||||
|
||||
- Unit tests in `tests/test_install.py`: verify `--platform X` routes to correct source file and target path
|
||||
- Package data test: assert all four skill files are present in the installed package
|
||||
- No execution tests for platform-specific extraction (requires live platform)
|
||||
- Evals before release: run each platform skill on a real corpus, verify graph output is equivalent
|
||||
+284
-27
@@ -1,10 +1,25 @@
|
||||
"""graphify CLI - `graphify install` sets up the Claude Code skill."""
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_SETTINGS_HOOK = {
|
||||
"matcher": "Glob|Grep",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": (
|
||||
"[ -f graphify-out/graph.json ] && "
|
||||
"echo 'graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md "
|
||||
"for god nodes and community structure before searching raw files.' || true"
|
||||
),
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
_SKILL_REGISTRATION = (
|
||||
"\n# graphify\n"
|
||||
"- **graphify** (`~/.claude/skills/graphify/SKILL.md`) "
|
||||
@@ -14,60 +29,302 @@ _SKILL_REGISTRATION = (
|
||||
)
|
||||
|
||||
|
||||
def _bundled_skill() -> Path:
|
||||
"""Path to the skill.md bundled with this package."""
|
||||
return Path(__file__).parent / "skill.md"
|
||||
_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,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def install() -> None:
|
||||
skill_src = _bundled_skill()
|
||||
if not skill_src.exists():
|
||||
print("error: skill.md not found in package - reinstall graphify", file=sys.stderr)
|
||||
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)
|
||||
|
||||
# Copy skill to ~/.claude/skills/graphify/SKILL.md
|
||||
skill_dst = Path.home() / ".claude" / "skills" / "graphify" / "SKILL.md"
|
||||
cfg = _PLATFORM_CONFIG[platform]
|
||||
skill_src = Path(__file__).parent / cfg["skill_file"]
|
||||
if not skill_src.exists():
|
||||
print(f"error: {cfg['skill_file']} not found in package - reinstall graphify", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
skill_dst = Path.home() / cfg["skill_dst"]
|
||||
skill_dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy(skill_src, skill_dst)
|
||||
print(f" skill installed → {skill_dst}")
|
||||
|
||||
# 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)")
|
||||
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}")
|
||||
else:
|
||||
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}")
|
||||
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 Claude Code in any directory and type:")
|
||||
print("Done. Open your AI coding assistant and type:")
|
||||
print()
|
||||
print(" /graphify .")
|
||||
print()
|
||||
|
||||
|
||||
_CLAUDE_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
|
||||
"""
|
||||
|
||||
_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."""
|
||||
target = (project_dir or Path(".")) / "CLAUDE.md"
|
||||
|
||||
if target.exists():
|
||||
content = target.read_text()
|
||||
if _CLAUDE_MD_MARKER in content:
|
||||
print("graphify already configured in CLAUDE.md")
|
||||
return
|
||||
new_content = content.rstrip() + "\n\n" + _CLAUDE_MD_SECTION
|
||||
else:
|
||||
new_content = _CLAUDE_MD_SECTION
|
||||
|
||||
target.write_text(new_content)
|
||||
print(f"graphify section written to {target.resolve()}")
|
||||
|
||||
# Also write Claude Code PreToolUse hook to .claude/settings.json
|
||||
_install_claude_hook(project_dir or Path("."))
|
||||
|
||||
print()
|
||||
print("Claude Code will now check the knowledge graph before answering")
|
||||
print("codebase questions and rebuild it after code changes.")
|
||||
|
||||
|
||||
def _install_claude_hook(project_dir: Path) -> None:
|
||||
"""Add graphify PreToolUse hook to .claude/settings.json."""
|
||||
settings_path = project_dir / ".claude" / "settings.json"
|
||||
settings_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if settings_path.exists():
|
||||
try:
|
||||
settings = json.loads(settings_path.read_text())
|
||||
except json.JSONDecodeError:
|
||||
settings = {}
|
||||
else:
|
||||
settings = {}
|
||||
|
||||
hooks = settings.setdefault("hooks", {})
|
||||
pre_tool = hooks.setdefault("PreToolUse", [])
|
||||
|
||||
# Check if already installed
|
||||
if any(h.get("matcher") == "Glob|Grep" and "graphify" in str(h) for h in pre_tool):
|
||||
print(f" .claude/settings.json → hook already registered (no change)")
|
||||
return
|
||||
|
||||
pre_tool.append(_SETTINGS_HOOK)
|
||||
settings_path.write_text(json.dumps(settings, indent=2))
|
||||
print(f" .claude/settings.json → PreToolUse hook registered")
|
||||
|
||||
|
||||
def _uninstall_claude_hook(project_dir: Path) -> None:
|
||||
"""Remove graphify PreToolUse hook from .claude/settings.json."""
|
||||
settings_path = project_dir / ".claude" / "settings.json"
|
||||
if not settings_path.exists():
|
||||
return
|
||||
try:
|
||||
settings = json.loads(settings_path.read_text())
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
pre_tool = settings.get("hooks", {}).get("PreToolUse", [])
|
||||
filtered = [h for h in pre_tool if not (h.get("matcher") == "Glob|Grep" and "graphify" in str(h))]
|
||||
if len(filtered) == len(pre_tool):
|
||||
return
|
||||
settings["hooks"]["PreToolUse"] = filtered
|
||||
settings_path.write_text(json.dumps(settings, indent=2))
|
||||
print(f" .claude/settings.json → PreToolUse hook removed")
|
||||
|
||||
|
||||
def claude_uninstall(project_dir: Path | None = None) -> None:
|
||||
"""Remove the graphify section from the local CLAUDE.md."""
|
||||
target = (project_dir or Path(".")) / "CLAUDE.md"
|
||||
|
||||
if not target.exists():
|
||||
print("No CLAUDE.md found in current directory - nothing to do")
|
||||
return
|
||||
|
||||
content = target.read_text()
|
||||
if _CLAUDE_MD_MARKER not in content:
|
||||
print("graphify section not found in CLAUDE.md - nothing to do")
|
||||
return
|
||||
|
||||
# Remove the ## graphify section: from the marker to the next ## heading or EOF
|
||||
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"CLAUDE.md was empty after removal - deleted {target.resolve()}")
|
||||
|
||||
_uninstall_claude_hook(project_dir or Path("."))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
|
||||
print("Usage: graphify <command>")
|
||||
print()
|
||||
print("Commands:")
|
||||
print(" install copy skill to ~/.claude/skills/ and register in CLAUDE.md")
|
||||
print(" install [--platform P] copy skill to platform config dir (claude|codex|opencode|claw)")
|
||||
print(" benchmark [graph.json] measure token reduction vs naive full-corpus approach")
|
||||
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(" 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()
|
||||
return
|
||||
|
||||
cmd = sys.argv[1]
|
||||
if cmd == "install":
|
||||
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)
|
||||
elif cmd == "claude":
|
||||
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
if subcmd == "install":
|
||||
claude_install()
|
||||
elif subcmd == "uninstall":
|
||||
claude_uninstall()
|
||||
else:
|
||||
print("Usage: graphify claude [install|uninstall]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
elif cmd in ("codex", "opencode", "claw"):
|
||||
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 ""
|
||||
|
||||
@@ -166,6 +166,11 @@ def _surprise_score(
|
||||
score += 1
|
||||
reasons.append("bridges separate communities")
|
||||
|
||||
# 4b. Semantic similarity bonus - non-obvious conceptual links score higher
|
||||
if data.get("relation") == "semantically_similar_to":
|
||||
score = int(score * 1.5)
|
||||
reasons.append("semantically similar concepts with no structural link")
|
||||
|
||||
# 5. Peripheral→hub: a low-degree node connecting to a high-degree one
|
||||
deg_u = G.degree(u)
|
||||
deg_v = G.degree(v)
|
||||
|
||||
+33
-2
@@ -1,4 +1,25 @@
|
||||
# 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
|
||||
@@ -25,15 +46,25 @@ def build_from_json(extraction: dict) -> nx.Graph:
|
||||
attrs["_src"] = src
|
||||
attrs["_tgt"] = tgt
|
||||
G.add_edge(src, tgt, **attrs)
|
||||
hyperedges = extraction.get("hyperedges", [])
|
||||
if hyperedges:
|
||||
G.graph["hyperedges"] = hyperedges
|
||||
return G
|
||||
|
||||
|
||||
def build(extractions: list[dict]) -> nx.Graph:
|
||||
"""Merge multiple extraction results into one graph."""
|
||||
combined: dict = {"nodes": [], "edges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
"""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}
|
||||
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)
|
||||
+11
-4
@@ -65,14 +65,15 @@ def clear_cache(root: Path = Path(".")) -> None:
|
||||
def check_semantic_cache(
|
||||
files: list[str],
|
||||
root: Path = Path("."),
|
||||
) -> tuple[list[dict], list[dict], list[str]]:
|
||||
) -> tuple[list[dict], list[dict], list[dict], list[str]]:
|
||||
"""Check semantic extraction cache for a list of absolute file paths.
|
||||
|
||||
Returns (cached_nodes, cached_edges, uncached_files).
|
||||
Returns (cached_nodes, cached_edges, cached_hyperedges, uncached_files).
|
||||
Uncached files need Claude extraction; cached files are merged directly.
|
||||
"""
|
||||
cached_nodes: list[dict] = []
|
||||
cached_edges: list[dict] = []
|
||||
cached_hyperedges: list[dict] = []
|
||||
uncached: list[str] = []
|
||||
|
||||
for fpath in files:
|
||||
@@ -80,15 +81,17 @@ def check_semantic_cache(
|
||||
if result is not None:
|
||||
cached_nodes.extend(result.get("nodes", []))
|
||||
cached_edges.extend(result.get("edges", []))
|
||||
cached_hyperedges.extend(result.get("hyperedges", []))
|
||||
else:
|
||||
uncached.append(fpath)
|
||||
|
||||
return cached_nodes, cached_edges, uncached
|
||||
return cached_nodes, cached_edges, cached_hyperedges, uncached
|
||||
|
||||
|
||||
def save_semantic_cache(
|
||||
nodes: list[dict],
|
||||
edges: list[dict],
|
||||
hyperedges: list[dict] | None = None,
|
||||
root: Path = Path("."),
|
||||
) -> int:
|
||||
"""Save semantic extraction results to cache, keyed by source_file.
|
||||
@@ -98,7 +101,7 @@ def save_semantic_cache(
|
||||
"""
|
||||
from collections import defaultdict
|
||||
|
||||
by_file: dict[str, dict] = defaultdict(lambda: {"nodes": [], "edges": []})
|
||||
by_file: dict[str, dict] = defaultdict(lambda: {"nodes": [], "edges": [], "hyperedges": []})
|
||||
for n in nodes:
|
||||
src = n.get("source_file", "")
|
||||
if src:
|
||||
@@ -107,6 +110,10 @@ def save_semantic_cache(
|
||||
src = e.get("source_file", "")
|
||||
if src:
|
||||
by_file[src]["edges"].append(e)
|
||||
for h in (hyperedges or []):
|
||||
src = h.get("source_file", "")
|
||||
if src:
|
||||
by_file[src]["hyperedges"].append(h)
|
||||
|
||||
saved = 0
|
||||
for fpath, result in by_file.items():
|
||||
|
||||
+20
-7
@@ -1,8 +1,25 @@
|
||||
"""Leiden community detection on NetworkX graphs. Splits oversized communities. Returns cohesion scores."""
|
||||
"""Community detection on NetworkX graphs. Uses Leiden (graspologic) if available, falls back to Louvain (networkx). Splits oversized communities. Returns cohesion scores."""
|
||||
from __future__ import annotations
|
||||
import networkx as nx
|
||||
|
||||
|
||||
def _partition(G: nx.Graph) -> dict[str, int]:
|
||||
"""Run community detection. Returns {node_id: community_id}.
|
||||
|
||||
Tries Leiden (graspologic) first — best quality.
|
||||
Falls back to Louvain (built into networkx) if graspologic is not installed.
|
||||
"""
|
||||
try:
|
||||
from graspologic.partition import leiden
|
||||
return leiden(G)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Fallback: networkx louvain (available since networkx 2.7)
|
||||
communities = nx.community.louvain_communities(G, seed=42)
|
||||
return {node: cid for cid, nodes in enumerate(communities) for node in nodes}
|
||||
|
||||
|
||||
def build_graph(nodes: list[dict], edges: list[dict]) -> nx.Graph:
|
||||
"""Build a NetworkX graph from graphify node/edge dicts.
|
||||
|
||||
@@ -36,8 +53,6 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
|
||||
if G.number_of_edges() == 0:
|
||||
return {i: [n] for i, n in enumerate(sorted(G.nodes))}
|
||||
|
||||
from graspologic.partition import leiden # lazy - avoids 15s numba JIT on import
|
||||
|
||||
# Leiden warns and drops isolates - handle them separately
|
||||
isolates = [n for n in G.nodes() if G.degree(n) == 0]
|
||||
connected_nodes = [n for n in G.nodes() if G.degree(n) > 0]
|
||||
@@ -45,7 +60,7 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
|
||||
|
||||
raw: dict[int, list[str]] = {}
|
||||
if connected.number_of_nodes() > 0:
|
||||
partition: dict[str, int] = leiden(connected)
|
||||
partition = _partition(connected)
|
||||
for node, cid in partition.items():
|
||||
raw.setdefault(cid, []).append(node)
|
||||
|
||||
@@ -76,13 +91,11 @@ def _split_community(G: nx.Graph, nodes: list[str]) -> list[list[str]]:
|
||||
# No edges - split into individual nodes
|
||||
return [[n] for n in sorted(nodes)]
|
||||
try:
|
||||
from graspologic.partition import leiden
|
||||
sub_partition: dict[str, int] = leiden(subgraph)
|
||||
sub_partition = _partition(subgraph)
|
||||
sub_communities: dict[int, list[str]] = {}
|
||||
for node, cid in sub_partition.items():
|
||||
sub_communities.setdefault(cid, []).append(node)
|
||||
if len(sub_communities) <= 1:
|
||||
# Leiden couldn't split it - return as-is
|
||||
return [sorted(nodes)]
|
||||
return [sorted(v) for v in sub_communities.values()]
|
||||
except Exception:
|
||||
|
||||
@@ -55,6 +55,58 @@ def _html_styles() -> str:
|
||||
</style>"""
|
||||
|
||||
|
||||
def _hyperedge_script(hyperedges_json: str) -> str:
|
||||
return f"""<script>
|
||||
// Render hyperedges as shaded regions
|
||||
const hyperedges = {hyperedges_json};
|
||||
function drawHyperedges() {{
|
||||
const canvas = network.canvas.frame.canvas;
|
||||
const ctx = canvas.getContext('2d');
|
||||
hyperedges.forEach(h => {{
|
||||
const positions = h.nodes
|
||||
.map(nid => network.getPositions([nid])[nid])
|
||||
.filter(p => p !== undefined);
|
||||
if (positions.length < 2) return;
|
||||
// Draw convex hull as filled polygon
|
||||
ctx.save();
|
||||
ctx.globalAlpha = 0.12;
|
||||
ctx.fillStyle = '#6366f1';
|
||||
ctx.strokeStyle = '#6366f1';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
const scale = network.getScale();
|
||||
const offset = network.getViewPosition();
|
||||
const toCanvas = (p) => ({{
|
||||
x: (p.x - offset.x) * scale + canvas.width / 2,
|
||||
y: (p.y - offset.y) * scale + canvas.height / 2
|
||||
}});
|
||||
const pts = positions.map(toCanvas);
|
||||
// Expand hull slightly
|
||||
const cx = pts.reduce((s, p) => s + p.x, 0) / pts.length;
|
||||
const cy = pts.reduce((s, p) => s + p.y, 0) / pts.length;
|
||||
const expanded = pts.map(p => ({{
|
||||
x: cx + (p.x - cx) * 1.15,
|
||||
y: cy + (p.y - cy) * 1.15
|
||||
}}));
|
||||
ctx.moveTo(expanded[0].x, expanded[0].y);
|
||||
expanded.slice(1).forEach(p => ctx.lineTo(p.x, p.y));
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
ctx.globalAlpha = 0.4;
|
||||
ctx.stroke();
|
||||
// Label
|
||||
ctx.globalAlpha = 0.8;
|
||||
ctx.fillStyle = '#4f46e5';
|
||||
ctx.font = 'bold 11px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText(h.label, cx, cy - 5);
|
||||
ctx.restore();
|
||||
}});
|
||||
}}
|
||||
network.on('afterDrawing', drawHyperedges);
|
||||
</script>"""
|
||||
|
||||
|
||||
def _html_script(nodes_json: str, edges_json: str, legend_json: str) -> str:
|
||||
return f"""<script>
|
||||
const RAW_NODES = {nodes_json};
|
||||
@@ -195,11 +247,30 @@ LEGEND.forEach(c => {{
|
||||
</script>"""
|
||||
|
||||
|
||||
_CONFIDENCE_SCORE_DEFAULTS = {"EXTRACTED": 1.0, "INFERRED": 0.5, "AMBIGUOUS": 0.2}
|
||||
|
||||
|
||||
def attach_hyperedges(G: nx.Graph, hyperedges: list) -> None:
|
||||
"""Store hyperedges in the graph's metadata dict."""
|
||||
existing = G.graph.get("hyperedges", [])
|
||||
seen_ids = {h["id"] for h in existing}
|
||||
for h in hyperedges:
|
||||
if h.get("id") and h["id"] not in seen_ids:
|
||||
existing.append(h)
|
||||
seen_ids.add(h["id"])
|
||||
G.graph["hyperedges"] = existing
|
||||
|
||||
|
||||
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) -> None:
|
||||
node_community = _node_community_map(communities)
|
||||
data = json_graph.node_link_data(G, edges="links")
|
||||
for node in data["nodes"]:
|
||||
node["community"] = node_community.get(node["id"])
|
||||
for link in data["links"]:
|
||||
if "confidence_score" not in link:
|
||||
conf = link.get("confidence", "EXTRACTED")
|
||||
link["confidence_score"] = _CONFIDENCE_SCORE_DEFAULTS.get(conf, 1.0)
|
||||
data["hyperedges"] = getattr(G, "graph", {}).get("hyperedges", [])
|
||||
with open(output_path, "w") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
|
||||
@@ -295,6 +366,7 @@ def to_html(
|
||||
nodes_json = json.dumps(vis_nodes)
|
||||
edges_json = json.dumps(vis_edges)
|
||||
legend_json = json.dumps(legend_data)
|
||||
hyperedges_json = json.dumps(getattr(G, "graph", {}).get("hyperedges", []))
|
||||
title = sanitize_label(str(output_path))
|
||||
stats = f"{G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(communities)} communities"
|
||||
|
||||
@@ -324,6 +396,7 @@ def to_html(
|
||||
<div id="stats">{stats}</div>
|
||||
</div>
|
||||
{_html_script(nodes_json, edges_json, legend_json)}
|
||||
{_hyperedge_script(hyperedges_json)}
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
|
||||
+909
-1761
File diff suppressed because it is too large.
Load diff
+86
-41
@@ -1,8 +1,9 @@
|
||||
# git hook integration - install/uninstall graphify post-commit hook
|
||||
# git hook integration - install/uninstall graphify post-commit and post-checkout hooks
|
||||
from __future__ import annotations
|
||||
from pathlib import Path
|
||||
|
||||
_HOOK_MARKER = "# graphify-hook"
|
||||
_CHECKOUT_MARKER = "# graphify-checkout-hook"
|
||||
|
||||
_HOOK_SCRIPT = """\
|
||||
#!/bin/bash
|
||||
@@ -44,6 +45,38 @@ except Exception as exc:
|
||||
"""
|
||||
|
||||
|
||||
_CHECKOUT_SCRIPT = """\
|
||||
#!/bin/bash
|
||||
# graphify-checkout-hook
|
||||
# Auto-rebuilds the knowledge graph (code only) when switching branches.
|
||||
# Installed by: graphify hook install
|
||||
|
||||
PREV_HEAD=$1
|
||||
NEW_HEAD=$2
|
||||
BRANCH_SWITCH=$3
|
||||
|
||||
# Only run on branch switches, not file checkouts
|
||||
if [ "$BRANCH_SWITCH" != "1" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Only run if graphify-out/ exists (graph has been built before)
|
||||
if [ ! -d "graphify-out" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "[graphify] Branch switched - rebuilding knowledge graph (code files)..."
|
||||
python3 -c "
|
||||
from graphify.watch import _rebuild_code
|
||||
from pathlib import Path
|
||||
try:
|
||||
_rebuild_code(Path('.'))
|
||||
except Exception as exc:
|
||||
print(f'[graphify] Rebuild failed: {exc}')
|
||||
"
|
||||
"""
|
||||
|
||||
|
||||
def _git_root(path: Path) -> Path | None:
|
||||
"""Walk up to find .git directory."""
|
||||
current = path.resolve()
|
||||
@@ -53,66 +86,78 @@ def _git_root(path: Path) -> Path | None:
|
||||
return None
|
||||
|
||||
|
||||
def install(path: Path = Path(".")) -> str:
|
||||
"""Install graphify post-commit hook in the nearest git repo.
|
||||
def _install_hook(hooks_dir: Path, name: str, script: str, marker: str) -> str:
|
||||
"""Install a single git hook, appending if an existing hook is present."""
|
||||
hook_path = hooks_dir / name
|
||||
if hook_path.exists():
|
||||
content = hook_path.read_text()
|
||||
if marker in content:
|
||||
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(script)
|
||||
hook_path.chmod(0o755)
|
||||
return f"installed at {hook_path}"
|
||||
|
||||
Returns a message describing what was done.
|
||||
"""
|
||||
|
||||
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."
|
||||
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(before + "\n")
|
||||
return f"graphify removed from {name} at {hook_path} (other hook content preserved)"
|
||||
|
||||
|
||||
def install(path: Path = Path(".")) -> str:
|
||||
"""Install graphify post-commit and post-checkout hooks in the nearest git repo."""
|
||||
root = _git_root(path)
|
||||
if root is None:
|
||||
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
|
||||
|
||||
hooks_dir = root / ".git" / "hooks"
|
||||
hooks_dir.mkdir(exist_ok=True)
|
||||
hook_path = hooks_dir / "post-commit"
|
||||
|
||||
if hook_path.exists():
|
||||
content = hook_path.read_text()
|
||||
if _HOOK_MARKER in content:
|
||||
return f"graphify hook already installed at {hook_path}"
|
||||
# Append to existing hook
|
||||
hook_path.write_text(content.rstrip() + "\n\n" + _HOOK_SCRIPT)
|
||||
return f"graphify hook appended to existing post-commit hook at {hook_path}"
|
||||
commit_msg = _install_hook(hooks_dir, "post-commit", _HOOK_SCRIPT, _HOOK_MARKER)
|
||||
checkout_msg = _install_hook(hooks_dir, "post-checkout", _CHECKOUT_SCRIPT, _CHECKOUT_MARKER)
|
||||
|
||||
hook_path.write_text(_HOOK_SCRIPT)
|
||||
hook_path.chmod(0o755)
|
||||
return f"graphify hook installed at {hook_path}"
|
||||
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
|
||||
|
||||
|
||||
def uninstall(path: Path = Path(".")) -> str:
|
||||
"""Remove graphify post-commit hook."""
|
||||
"""Remove graphify post-commit and post-checkout hooks."""
|
||||
root = _git_root(path)
|
||||
if root is None:
|
||||
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
|
||||
|
||||
hook_path = root / ".git" / "hooks" / "post-commit"
|
||||
if not hook_path.exists():
|
||||
return "No post-commit hook found - nothing to remove."
|
||||
hooks_dir = root / ".git" / "hooks"
|
||||
commit_msg = _uninstall_hook(hooks_dir, "post-commit", _HOOK_MARKER)
|
||||
checkout_msg = _uninstall_hook(hooks_dir, "post-checkout", _CHECKOUT_MARKER)
|
||||
|
||||
content = hook_path.read_text()
|
||||
if _HOOK_MARKER not in content:
|
||||
return "graphify hook not found in post-commit - nothing to remove."
|
||||
|
||||
# Strip everything from our marker onwards
|
||||
before = content.split(_HOOK_MARKER)[0].rstrip()
|
||||
# 'before' is empty or just a shebang line if the whole file was ours
|
||||
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 post-commit hook at {hook_path}"
|
||||
else:
|
||||
hook_path.write_text(before + "\n")
|
||||
return f"graphify hook removed from {hook_path} (other hook content preserved)"
|
||||
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
|
||||
|
||||
|
||||
def status(path: Path = Path(".")) -> str:
|
||||
"""Check if graphify hook is installed."""
|
||||
"""Check if graphify hooks are installed."""
|
||||
root = _git_root(path)
|
||||
if root is None:
|
||||
return "Not in a git repository."
|
||||
hook_path = root / ".git" / "hooks" / "post-commit"
|
||||
if not hook_path.exists():
|
||||
return "graphify hook: not installed"
|
||||
if _HOOK_MARKER in hook_path.read_text():
|
||||
return f"graphify hook: installed at {hook_path}"
|
||||
return "graphify hook: not installed (post-commit exists but graphify hook not found)"
|
||||
hooks_dir = root / ".git" / "hooks"
|
||||
|
||||
def _check(name: str, marker: str) -> str:
|
||||
p = hooks_dir / name
|
||||
if not p.exists():
|
||||
return "not installed"
|
||||
return "installed" if marker in p.read_text() else "not installed (hook exists but graphify not found)"
|
||||
|
||||
commit = _check("post-commit", _HOOK_MARKER)
|
||||
checkout = _check("post-checkout", _CHECKOUT_MARKER)
|
||||
return f"post-commit: {commit}\npost-checkout: {checkout}"
|
||||
+24
-2
@@ -24,6 +24,10 @@ def generate(
|
||||
inf_pct = round(confidences.count("INFERRED") / total * 100)
|
||||
amb_pct = round(confidences.count("AMBIGUOUS") / total * 100)
|
||||
|
||||
inf_edges = [(u, v, d) for u, v, d in G.edges(data=True) if d.get("confidence") == "INFERRED"]
|
||||
inf_scores = [d.get("confidence_score", 0.5) for _, _, d in inf_edges]
|
||||
inf_avg = round(sum(inf_scores) / len(inf_scores), 2) if inf_scores else None
|
||||
|
||||
lines = [
|
||||
f"# Graph Report - {root} ({today})",
|
||||
"",
|
||||
@@ -41,7 +45,8 @@ def generate(
|
||||
"",
|
||||
"## Summary",
|
||||
f"- {G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(communities)} communities detected",
|
||||
f"- Extraction: {ext_pct}% EXTRACTED · {inf_pct}% INFERRED · {amb_pct}% AMBIGUOUS",
|
||||
f"- Extraction: {ext_pct}% EXTRACTED · {inf_pct}% INFERRED · {amb_pct}% AMBIGUOUS"
|
||||
+ (f" · INFERRED: {len(inf_edges)} edges (avg confidence: {inf_avg})" if inf_avg is not None else ""),
|
||||
f"- Token cost: {token_cost.get('input', 0):,} input · {token_cost.get('output', 0):,} output",
|
||||
"",
|
||||
"## God Nodes (most connected - your core abstractions)",
|
||||
@@ -55,13 +60,30 @@ def generate(
|
||||
relation = s.get("relation", "related_to")
|
||||
note = s.get("note", "")
|
||||
files = s.get("source_files", ["", ""])
|
||||
conf = s.get("confidence", "EXTRACTED")
|
||||
cscore = s.get("confidence_score")
|
||||
if conf == "INFERRED" and cscore is not None:
|
||||
conf_tag = f"INFERRED {cscore:.2f}"
|
||||
else:
|
||||
conf_tag = conf
|
||||
sem_tag = " [semantically similar]" if relation == "semantically_similar_to" else ""
|
||||
lines += [
|
||||
f"- `{s['source']}` --{relation}--> `{s['target']}` [{s['confidence']}]",
|
||||
f"- `{s['source']}` --{relation}--> `{s['target']}` [{conf_tag}]{sem_tag}",
|
||||
f" {files[0]} → {files[1]}" + (f" _{note}_" if note else ""),
|
||||
]
|
||||
else:
|
||||
lines.append("- None detected - all connections are within the same source files.")
|
||||
|
||||
hyperedges = G.graph.get("hyperedges", [])
|
||||
if hyperedges:
|
||||
lines += ["", "## Hyperedges (group relationships)"]
|
||||
for h in hyperedges:
|
||||
node_labels = ", ".join(h.get("nodes", []))
|
||||
conf = h.get("confidence", "INFERRED")
|
||||
cscore = h.get("confidence_score")
|
||||
conf_tag = f"{conf} {cscore:.2f}" if cscore is not None else conf
|
||||
lines.append(f"- **{h.get('label', h.get('id', ''))}** — {node_labels} [{conf_tag}]")
|
||||
|
||||
lines += ["", "## Communities"]
|
||||
from .analyze import _is_file_node as _ifn
|
||||
for cid, nodes in communities.items():
|
||||
|
||||
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
+131
-61
@@ -58,15 +58,26 @@ Follow these steps in order. Do not skip steps.
|
||||
### Step 1 - Ensure graphify is installed
|
||||
|
||||
```bash
|
||||
python3 -c "import graphify" 2>/dev/null || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
# 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)"
|
||||
```
|
||||
|
||||
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
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
@@ -95,14 +106,18 @@ Then act on it:
|
||||
|
||||
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
|
||||
|
||||
This step has two parts: **structural extraction** (deterministic, free) then **semantic extraction** (Claude, costs tokens).
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
|
||||
|
||||
#### Part A - Structural extraction for code files
|
||||
|
||||
For any code files detected, run AST extraction first:
|
||||
For any code files detected, run AST extraction in parallel with Part B subagents:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.extract import collect_files, extract
|
||||
from pathlib import Path
|
||||
@@ -140,7 +155,7 @@ Before dispatching subagents, print a timing estimate:
|
||||
Before dispatching any subagents, check which files already have cached extraction results:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from graphify.cache import check_semantic_cache
|
||||
from pathlib import Path
|
||||
@@ -148,10 +163,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, uncached = check_semantic_cache(all_files)
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
|
||||
|
||||
if cached_nodes or cached_edges:
|
||||
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges}))
|
||||
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}))
|
||||
Path('.graphify_uncached.txt').write_text('\n'.join(uncached))
|
||||
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
|
||||
"
|
||||
@@ -191,7 +206,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.
|
||||
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.
|
||||
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.
|
||||
@@ -203,11 +218,31 @@ Image files: use vision to understand what the image IS - do not just OCR.
|
||||
DEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps,
|
||||
shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting.
|
||||
|
||||
Semantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples:
|
||||
- Two functions that both validate user input but never call each other
|
||||
- A class in code and a concept in a paper that describe the same algorithm
|
||||
- Two error types that handle the same failure mode differently
|
||||
Only add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things.
|
||||
|
||||
Hyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples:
|
||||
- All classes that implement a common protocol or interface
|
||||
- All functions in an authentication flow (even if they don't all call each other)
|
||||
- All concepts from a paper section that form one coherent idea
|
||||
Use sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk.
|
||||
|
||||
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
|
||||
|
||||
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","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","source_file":"relative/path","source_location":null,"weight":1.0}],"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|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}
|
||||
```
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
@@ -220,28 +255,29 @@ If more than half the chunks failed, stop and tell the user.
|
||||
|
||||
Save new results to cache:
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -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':[]}
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []))
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
|
||||
print(f'Cached {saved} files')
|
||||
"
|
||||
```
|
||||
|
||||
Merge cached + new results into `.graphify_semantic.json`:
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -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':[]}
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[]}
|
||||
cached = json.loads(Path('.graphify_cached.json').read_text()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
|
||||
all_nodes = cached['nodes'] + new.get('nodes', [])
|
||||
all_edges = cached['edges'] + new.get('edges', [])
|
||||
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
|
||||
seen = set()
|
||||
deduped = []
|
||||
for n in all_nodes:
|
||||
@@ -252,6 +288,7 @@ 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),
|
||||
}
|
||||
@@ -264,7 +301,7 @@ Clean up temp files: `rm -f .graphify_cached.json .graphify_uncached.txt .graphi
|
||||
#### Part C - Merge AST + semantic into final extraction
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from pathlib import Path
|
||||
|
||||
@@ -280,9 +317,11 @@ 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),
|
||||
}
|
||||
@@ -297,7 +336,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
@@ -350,7 +389,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
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import score_all
|
||||
@@ -383,12 +422,14 @@ 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 (default) + optional HTML
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
**Always generate the Obsidian vault and HTML** - they are the primary visualizations. Skip both if `--no-viz` (report + JSON only).
|
||||
**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:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_obsidian, to_canvas
|
||||
@@ -416,10 +457,10 @@ print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries
|
||||
"
|
||||
```
|
||||
|
||||
Also generate the HTML graph (always, unless `--no-viz`):
|
||||
Generate the HTML graph (always, unless `--no-viz`):
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_html
|
||||
@@ -446,7 +487,7 @@ else:
|
||||
**If `--neo4j`** - generate a Cypher file for manual import:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_cypher
|
||||
@@ -461,7 +502,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
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster
|
||||
@@ -483,7 +524,7 @@ Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default
|
||||
### Step 7b - SVG export (only if --svg flag)
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_svg
|
||||
@@ -505,7 +546,7 @@ print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
|
||||
### Step 7c - GraphML export (only if --graphml flag)
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_graphml
|
||||
@@ -547,7 +588,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
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from graphify.benchmark import run_benchmark, print_benchmark
|
||||
from pathlib import Path
|
||||
@@ -565,7 +606,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
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
@@ -599,26 +640,18 @@ 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
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_python
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Tell the user:
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
Graph complete. Outputs are in a hidden folder called graphify-out/ inside the directory you ran this on.
|
||||
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
|
||||
|
||||
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/
|
||||
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)
|
||||
```
|
||||
|
||||
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
|
||||
@@ -645,7 +678,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
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.detect import detect_incremental, save_manifest
|
||||
from pathlib import Path
|
||||
@@ -653,6 +686,7 @@ from pathlib import Path
|
||||
result = detect_incremental(Path('INPUT_PATH'))
|
||||
new_total = result.get('new_total', 0)
|
||||
print(json.dumps(result, indent=2))
|
||||
Path('.graphify_incremental.json').write_text(json.dumps(result))
|
||||
if new_total == 0:
|
||||
print('No files changed since last run. Nothing to update.')
|
||||
raise SystemExit(0)
|
||||
@@ -660,10 +694,30 @@ print(f'{new_total} new/changed file(s) to re-extract.')
|
||||
"
|
||||
```
|
||||
|
||||
If new files exist, run **Steps 3A–3C** on `result['new_files']` only (not the full corpus). Then:
|
||||
If new files exist, first check whether all changed files are code files:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
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'}
|
||||
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)
|
||||
print('code_only:', code_only)
|
||||
"
|
||||
```
|
||||
|
||||
If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8.
|
||||
|
||||
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
|
||||
|
||||
Then:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_json
|
||||
@@ -690,7 +744,7 @@ Then run Steps 4–8 on the merged graph as normal.
|
||||
After Step 4, show the graph diff:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json
|
||||
from graphify.analyze import graph_diff
|
||||
from graphify.build import build_from_json
|
||||
@@ -724,7 +778,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
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections
|
||||
@@ -777,7 +831,7 @@ Two traversal modes - choose based on the question:
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -795,7 +849,7 @@ Load `graphify-out/graph.json`, then:
|
||||
5. If the graph lacks enough information, say so - do not hallucinate edges.
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys, json
|
||||
from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
@@ -886,7 +940,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
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
from graphify.ingest import save_query_result
|
||||
from pathlib import Path
|
||||
save_query_result(
|
||||
@@ -910,7 +964,7 @@ Find the shortest path between two named concepts in the graph.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -920,7 +974,7 @@ if not Path('graphify-out/graph.json').exists():
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
@@ -972,7 +1026,7 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
from graphify.ingest import save_query_result
|
||||
from pathlib import Path
|
||||
save_query_result(
|
||||
@@ -994,7 +1048,7 @@ Give a plain-language explanation of a single node - everything connected to it.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -1004,7 +1058,7 @@ if not Path('graphify-out/graph.json').exists():
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
@@ -1049,7 +1103,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
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
from graphify.ingest import save_query_result
|
||||
from pathlib import Path
|
||||
save_query_result(
|
||||
@@ -1070,7 +1124,7 @@ print('Explanation saved to graphify-out/memory/')
|
||||
Fetch a URL and add it to the corpus, then update the graph.
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
$(cat .graphify_python) -c "
|
||||
import sys
|
||||
from graphify.ingest import ingest
|
||||
from pathlib import Path
|
||||
@@ -1135,6 +1189,22 @@ If a post-commit hook already exists, graphify appends to it rather than replaci
|
||||
|
||||
---
|
||||
|
||||
## For native CLAUDE.md integration
|
||||
|
||||
Run once per project to make graphify always-on in Claude Code sessions:
|
||||
|
||||
```bash
|
||||
graphify claude install
|
||||
```
|
||||
|
||||
This writes a `## graphify` section to the local `CLAUDE.md` that instructs Claude to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions.
|
||||
|
||||
```bash
|
||||
graphify claude uninstall # remove the section
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Honesty Rules
|
||||
|
||||
- Never invent an edge. If unsure, use AMBIGUOUS.
|
||||
|
||||
+7
-7
@@ -4,15 +4,14 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "graphifyy"
|
||||
version = "0.1.10"
|
||||
description = "Claude Code skill - turn any folder of code, docs, papers, images, or tweets into a queryable knowledge graph"
|
||||
version = "0.3.0"
|
||||
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, OpenClaw) - turn any folder of code, docs, papers, or images into a queryable knowledge graph"
|
||||
readme = "README.md"
|
||||
license = { text = "MIT" }
|
||||
keywords = ["claude", "claude-code", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
|
||||
license = { file = "LICENSE" }
|
||||
keywords = ["claude", "claude-code", "codex", "opencode", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"networkx",
|
||||
"graspologic",
|
||||
"tree-sitter",
|
||||
"tree-sitter-python",
|
||||
"tree-sitter-javascript",
|
||||
@@ -39,7 +38,8 @@ mcp = ["mcp"]
|
||||
neo4j = ["neo4j"]
|
||||
pdf = ["pypdf", "html2text"]
|
||||
watch = ["watchdog"]
|
||||
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog"]
|
||||
leiden = ["graspologic"]
|
||||
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic"]
|
||||
|
||||
[project.scripts]
|
||||
graphify = "graphify.__main__:main"
|
||||
@@ -49,4 +49,4 @@ where = ["."]
|
||||
include = ["graphify*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
graphify = ["skill.md"]
|
||||
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-claw.md"]
|
||||
@@ -95,11 +95,15 @@ Then act on it:
|
||||
|
||||
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
|
||||
|
||||
This step has two parts: **structural extraction** (deterministic, free) then **semantic extraction** (Claude, costs tokens).
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
|
||||
|
||||
#### Part A - Structural extraction for code files
|
||||
|
||||
For any code files detected, run AST extraction first:
|
||||
For any code files detected, run AST extraction in parallel with Part B subagents:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
@@ -203,11 +207,30 @@ Image files: use vision to understand what the image IS - do not just OCR.
|
||||
DEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps,
|
||||
shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting.
|
||||
|
||||
Semantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples:
|
||||
- Two functions that both validate user input but never call each other
|
||||
- A class in code and a concept in a paper that describe the same algorithm
|
||||
- Two error types that handle the same failure mode differently
|
||||
Only add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things.
|
||||
|
||||
Hyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples:
|
||||
- All classes that implement a common protocol or interface
|
||||
- All functions in an authentication flow (even if they don't all call each other)
|
||||
- All concepts from a paper section that form one coherent idea
|
||||
Use sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk.
|
||||
|
||||
If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author,
|
||||
contributor onto every node from that file.
|
||||
|
||||
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","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","source_file":"relative/path","source_location":null,"weight":1.0}],"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**
|
||||
@@ -653,6 +676,7 @@ from pathlib import Path
|
||||
result = detect_incremental(Path('INPUT_PATH'))
|
||||
new_total = result.get('new_total', 0)
|
||||
print(json.dumps(result, indent=2))
|
||||
Path('.graphify_incremental.json').write_text(json.dumps(result))
|
||||
if new_total == 0:
|
||||
print('No files changed since last run. Nothing to update.')
|
||||
raise SystemExit(0)
|
||||
@@ -660,7 +684,27 @@ print(f'{new_total} new/changed file(s) to re-extract.')
|
||||
"
|
||||
```
|
||||
|
||||
If new files exist, run **Steps 3A–3C** on `result['new_files']` only (not the full corpus). Then:
|
||||
If new files exist, first check whether all changed files are code files:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
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'}
|
||||
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)
|
||||
print('code_only:', code_only)
|
||||
"
|
||||
```
|
||||
|
||||
If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8.
|
||||
|
||||
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
|
||||
|
||||
Then:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
@@ -1135,6 +1179,22 @@ If a post-commit hook already exists, graphify appends to it rather than replaci
|
||||
|
||||
---
|
||||
|
||||
## For native CLAUDE.md integration
|
||||
|
||||
Run once per project to make graphify always-on in Claude Code sessions:
|
||||
|
||||
```bash
|
||||
graphify claude install
|
||||
```
|
||||
|
||||
This writes a `## graphify` section to the local `CLAUDE.md` that instructs Claude to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions.
|
||||
|
||||
```bash
|
||||
graphify claude uninstall # remove the section
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Honesty Rules
|
||||
|
||||
- Never invent an edge. If unsure, use AMBIGUOUS.
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Tests for graphify claude install / uninstall commands."""
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from graphify.__main__ import claude_install, claude_uninstall, _CLAUDE_MD_MARKER, _CLAUDE_MD_SECTION
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# install
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_install_creates_claude_md(tmp_path):
|
||||
"""Creates CLAUDE.md when none exists."""
|
||||
claude_install(tmp_path)
|
||||
target = tmp_path / "CLAUDE.md"
|
||||
assert target.exists()
|
||||
assert _CLAUDE_MD_MARKER in target.read_text()
|
||||
|
||||
|
||||
def test_install_contains_expected_rules(tmp_path):
|
||||
"""Written section includes the three rules."""
|
||||
claude_install(tmp_path)
|
||||
content = (tmp_path / "CLAUDE.md").read_text()
|
||||
assert "GRAPH_REPORT.md" in content
|
||||
assert "wiki/index.md" in content
|
||||
assert "_rebuild_code" in content
|
||||
|
||||
|
||||
def test_install_appends_to_existing_claude_md(tmp_path):
|
||||
"""Appends to an existing CLAUDE.md without clobbering it."""
|
||||
target = tmp_path / "CLAUDE.md"
|
||||
target.write_text("# Existing content\n\nSome rules here.\n")
|
||||
claude_install(tmp_path)
|
||||
content = target.read_text()
|
||||
assert "Existing content" in content
|
||||
assert _CLAUDE_MD_MARKER in content
|
||||
|
||||
|
||||
def test_install_is_idempotent(tmp_path, capsys):
|
||||
"""Running install twice does not duplicate the section."""
|
||||
claude_install(tmp_path)
|
||||
claude_install(tmp_path)
|
||||
content = (tmp_path / "CLAUDE.md").read_text()
|
||||
assert content.count(_CLAUDE_MD_MARKER) == 1
|
||||
captured = capsys.readouterr()
|
||||
assert "already configured" in captured.out
|
||||
|
||||
|
||||
def test_install_idempotent_message(tmp_path, capsys):
|
||||
"""Second install prints the 'already configured' message."""
|
||||
claude_install(tmp_path)
|
||||
capsys.readouterr() # clear first call output
|
||||
claude_install(tmp_path)
|
||||
out = capsys.readouterr().out
|
||||
assert "already configured" in out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# uninstall
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_uninstall_removes_section(tmp_path):
|
||||
"""Removes the graphify section after it was installed."""
|
||||
claude_install(tmp_path)
|
||||
claude_uninstall(tmp_path)
|
||||
target = tmp_path / "CLAUDE.md"
|
||||
# File may or may not exist depending on whether it was empty
|
||||
if target.exists():
|
||||
assert _CLAUDE_MD_MARKER not in target.read_text()
|
||||
|
||||
|
||||
def test_uninstall_preserves_other_content(tmp_path):
|
||||
"""Uninstall keeps pre-existing content outside the graphify section."""
|
||||
target = tmp_path / "CLAUDE.md"
|
||||
target.write_text("# My Project\n\nSome rules.\n")
|
||||
claude_install(tmp_path)
|
||||
claude_uninstall(tmp_path)
|
||||
assert target.exists()
|
||||
content = target.read_text()
|
||||
assert "My Project" in content
|
||||
assert "Some rules" in content
|
||||
assert _CLAUDE_MD_MARKER not in content
|
||||
|
||||
|
||||
def test_uninstall_no_op_when_not_installed(tmp_path, capsys):
|
||||
"""Uninstall on a CLAUDE.md without graphify section prints a message and exits cleanly."""
|
||||
target = tmp_path / "CLAUDE.md"
|
||||
target.write_text("# Other stuff\n")
|
||||
claude_uninstall(tmp_path)
|
||||
out = capsys.readouterr().out
|
||||
assert "not found" in out or "nothing to do" in out
|
||||
|
||||
|
||||
def test_uninstall_no_op_when_no_file(tmp_path, capsys):
|
||||
"""Uninstall when no CLAUDE.md exists prints a message and exits cleanly."""
|
||||
claude_uninstall(tmp_path)
|
||||
out = capsys.readouterr().out
|
||||
assert "No CLAUDE.md" in out or "nothing to do" in out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# settings.json PreToolUse hook
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_install_creates_settings_json(tmp_path):
|
||||
"""claude_install also writes .claude/settings.json with PreToolUse hook."""
|
||||
import json
|
||||
claude_install(tmp_path)
|
||||
settings_path = tmp_path / ".claude" / "settings.json"
|
||||
assert settings_path.exists()
|
||||
settings = json.loads(settings_path.read_text())
|
||||
hooks = settings.get("hooks", {}).get("PreToolUse", [])
|
||||
assert any("Glob|Grep" in h.get("matcher", "") for h in hooks)
|
||||
|
||||
|
||||
def test_install_settings_json_idempotent(tmp_path):
|
||||
"""Running claude_install twice does not duplicate the PreToolUse hook."""
|
||||
import json
|
||||
claude_install(tmp_path)
|
||||
claude_install(tmp_path)
|
||||
settings_path = tmp_path / ".claude" / "settings.json"
|
||||
settings = json.loads(settings_path.read_text())
|
||||
hooks = settings.get("hooks", {}).get("PreToolUse", [])
|
||||
glob_grep_hooks = [h for h in hooks if "Glob|Grep" in h.get("matcher", "")]
|
||||
assert len(glob_grep_hooks) == 1
|
||||
|
||||
|
||||
def test_uninstall_removes_settings_hook(tmp_path):
|
||||
"""claude_uninstall removes the PreToolUse hook from settings.json."""
|
||||
import json
|
||||
claude_install(tmp_path)
|
||||
claude_uninstall(tmp_path)
|
||||
settings_path = tmp_path / ".claude" / "settings.json"
|
||||
if settings_path.exists():
|
||||
settings = json.loads(settings_path.read_text())
|
||||
hooks = settings.get("hooks", {}).get("PreToolUse", [])
|
||||
assert not any("Glob|Grep" in h.get("matcher", "") for h in hooks)
|
||||
@@ -0,0 +1,192 @@
|
||||
"""Tests for confidence_score on edges."""
|
||||
import json
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import networkx as nx
|
||||
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections
|
||||
from graphify.export import to_json
|
||||
from graphify.report import generate
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
|
||||
def _make_extraction(**edge_overrides):
|
||||
"""Return a minimal extraction dict with one edge of each confidence type."""
|
||||
base = {
|
||||
"nodes": [
|
||||
{"id": "n_a", "label": "A", "file_type": "code", "source_file": "a.py"},
|
||||
{"id": "n_b", "label": "B", "file_type": "code", "source_file": "b.py"},
|
||||
{"id": "n_c", "label": "C", "file_type": "document", "source_file": "c.md"},
|
||||
{"id": "n_d", "label": "D", "file_type": "document", "source_file": "d.md"},
|
||||
],
|
||||
"edges": [
|
||||
{"source": "n_a", "target": "n_b", "relation": "calls", "confidence": "EXTRACTED",
|
||||
"confidence_score": 1.0, "source_file": "a.py", "weight": 1.0},
|
||||
{"source": "n_b", "target": "n_c", "relation": "implements", "confidence": "INFERRED",
|
||||
"confidence_score": 0.75, "source_file": "b.py", "weight": 0.8},
|
||||
{"source": "n_c", "target": "n_d", "relation": "references", "confidence": "AMBIGUOUS",
|
||||
"confidence_score": 0.2, "source_file": "c.md", "weight": 0.5},
|
||||
],
|
||||
"input_tokens": 100,
|
||||
"output_tokens": 50,
|
||||
}
|
||||
return base
|
||||
|
||||
|
||||
def test_extracted_edges_have_score_1():
|
||||
"""EXTRACTED edges must have confidence_score == 1.0."""
|
||||
G = build_from_json(_make_extraction())
|
||||
for u, v, d in G.edges(data=True):
|
||||
if d.get("confidence") == "EXTRACTED":
|
||||
assert d.get("confidence_score") == 1.0, (
|
||||
f"EXTRACTED edge ({u},{v}) should have confidence_score=1.0, got {d.get('confidence_score')}"
|
||||
)
|
||||
|
||||
|
||||
def test_inferred_edges_score_in_range():
|
||||
"""INFERRED edges must have confidence_score between 0.0 and 1.0."""
|
||||
G = build_from_json(_make_extraction())
|
||||
found = False
|
||||
for u, v, d in G.edges(data=True):
|
||||
if d.get("confidence") == "INFERRED":
|
||||
found = True
|
||||
score = d.get("confidence_score")
|
||||
assert score is not None, f"INFERRED edge ({u},{v}) missing confidence_score"
|
||||
assert 0.0 <= score <= 1.0, (
|
||||
f"INFERRED edge ({u},{v}) confidence_score={score} out of range [0,1]"
|
||||
)
|
||||
assert found, "No INFERRED edges found in test fixture"
|
||||
|
||||
|
||||
def test_ambiguous_edges_score_at_most_04():
|
||||
"""AMBIGUOUS edges must have confidence_score <= 0.4."""
|
||||
G = build_from_json(_make_extraction())
|
||||
found = False
|
||||
for u, v, d in G.edges(data=True):
|
||||
if d.get("confidence") == "AMBIGUOUS":
|
||||
found = True
|
||||
score = d.get("confidence_score")
|
||||
assert score is not None, f"AMBIGUOUS edge ({u},{v}) missing confidence_score"
|
||||
assert score <= 0.4, (
|
||||
f"AMBIGUOUS edge ({u},{v}) confidence_score={score} should be <= 0.4"
|
||||
)
|
||||
assert found, "No AMBIGUOUS edges found in test fixture"
|
||||
|
||||
|
||||
def test_confidence_score_round_trip():
|
||||
"""confidence_score survives build_from_json → to_json → JSON parse round-trip."""
|
||||
extraction = _make_extraction()
|
||||
G = build_from_json(extraction)
|
||||
communities = cluster(G)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.json"
|
||||
to_json(G, communities, str(out))
|
||||
data = json.loads(out.read_text())
|
||||
|
||||
# to_json uses node_link_data which puts edges in "links"
|
||||
links = data.get("links", [])
|
||||
assert links, "No links found in exported graph.json"
|
||||
for link in links:
|
||||
assert "confidence_score" in link, f"Link missing confidence_score: {link}"
|
||||
score = link["confidence_score"]
|
||||
assert isinstance(score, float), f"confidence_score should be float, got {type(score)}"
|
||||
assert 0.0 <= score <= 1.0, f"confidence_score={score} out of range"
|
||||
|
||||
|
||||
def test_to_json_defaults_missing_confidence_score():
|
||||
"""Edges lacking confidence_score get sensible defaults in to_json."""
|
||||
extraction = {
|
||||
"nodes": [
|
||||
{"id": "n_x", "label": "X", "file_type": "code", "source_file": "x.py"},
|
||||
{"id": "n_y", "label": "Y", "file_type": "code", "source_file": "y.py"},
|
||||
{"id": "n_z", "label": "Z", "file_type": "code", "source_file": "z.py"},
|
||||
],
|
||||
"edges": [
|
||||
# No confidence_score field on any of these
|
||||
{"source": "n_x", "target": "n_y", "relation": "calls",
|
||||
"confidence": "EXTRACTED", "source_file": "x.py", "weight": 1.0},
|
||||
{"source": "n_y", "target": "n_z", "relation": "depends_on",
|
||||
"confidence": "INFERRED", "source_file": "y.py", "weight": 1.0},
|
||||
],
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0,
|
||||
}
|
||||
G = build_from_json(extraction)
|
||||
communities = cluster(G)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.json"
|
||||
to_json(G, communities, str(out))
|
||||
data = json.loads(out.read_text())
|
||||
|
||||
links_by_conf = {}
|
||||
for link in data.get("links", []):
|
||||
conf = link.get("confidence", "EXTRACTED")
|
||||
links_by_conf[conf] = link.get("confidence_score")
|
||||
|
||||
assert links_by_conf.get("EXTRACTED") == 1.0, "EXTRACTED default should be 1.0"
|
||||
assert links_by_conf.get("INFERRED") == 0.5, "INFERRED default should be 0.5"
|
||||
|
||||
|
||||
def test_report_shows_avg_confidence_for_inferred():
|
||||
"""Report summary line should include avg confidence for INFERRED edges."""
|
||||
extraction = _make_extraction()
|
||||
G = build_from_json(extraction)
|
||||
communities = cluster(G)
|
||||
cohesion = score_all(G, communities)
|
||||
labels = {cid: f"Community {cid}" for cid in communities}
|
||||
gods = god_nodes(G)
|
||||
surprises = surprising_connections(G)
|
||||
detection = {"total_files": 2, "total_words": 5000, "needs_graph": True, "warning": None}
|
||||
tokens = {"input": 100, "output": 50}
|
||||
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, ".")
|
||||
assert "avg confidence" in report, "Report should show avg confidence for INFERRED edges"
|
||||
# The fixture has one INFERRED edge with score 0.75, so avg should be 0.75
|
||||
assert "0.75" in report, f"Expected avg confidence 0.75 in report"
|
||||
|
||||
|
||||
def test_report_inferred_tag_with_score():
|
||||
"""Surprising connections section shows confidence score next to INFERRED edges."""
|
||||
# Build a graph where surprising_connections will find an INFERRED cross-file edge
|
||||
extraction = {
|
||||
"nodes": [
|
||||
{"id": "n_p", "label": "Parser", "file_type": "code", "source_file": "parser.py"},
|
||||
{"id": "n_q", "label": "Renderer", "file_type": "code", "source_file": "renderer.py"},
|
||||
],
|
||||
"edges": [
|
||||
{"source": "n_p", "target": "n_q", "relation": "feeds",
|
||||
"confidence": "INFERRED", "confidence_score": 0.82,
|
||||
"source_file": "parser.py", "weight": 1.0},
|
||||
],
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0,
|
||||
}
|
||||
G = build_from_json(extraction)
|
||||
|
||||
# Manually construct a surprise entry the way analyze.surprising_connections would
|
||||
surprise = {
|
||||
"source": "Parser",
|
||||
"target": "Renderer",
|
||||
"relation": "feeds",
|
||||
"confidence": "INFERRED",
|
||||
"confidence_score": 0.82,
|
||||
"source_files": ["parser.py", "renderer.py"],
|
||||
"note": "",
|
||||
}
|
||||
communities = cluster(G)
|
||||
cohesion = score_all(G, communities)
|
||||
labels = {cid: f"Community {cid}" for cid in communities}
|
||||
gods = god_nodes(G)
|
||||
detection = {"total_files": 2, "total_words": 1000, "needs_graph": True, "warning": None}
|
||||
tokens = {"input": 0, "output": 0}
|
||||
|
||||
report = generate(G, communities, cohesion, labels, gods, [surprise], detection, tokens, ".")
|
||||
assert "INFERRED 0.82" in report, (
|
||||
f"Report should show 'INFERRED 0.82' in surprising connections section. Got:\n{report}"
|
||||
)
|
||||
+34
-2
@@ -2,7 +2,7 @@
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from graphify.hooks import install, uninstall, status, _HOOK_MARKER
|
||||
from graphify.hooks import install, uninstall, status, _HOOK_MARKER, _CHECKOUT_MARKER
|
||||
|
||||
|
||||
def _make_git_repo(tmp_path: Path) -> Path:
|
||||
@@ -53,7 +53,7 @@ def test_uninstall_removes_hook(tmp_path):
|
||||
result = uninstall(repo)
|
||||
hook = repo / ".git" / "hooks" / "post-commit"
|
||||
assert not hook.exists()
|
||||
assert "Removed" in result
|
||||
assert "removed" in result.lower()
|
||||
|
||||
|
||||
def test_uninstall_no_hook(tmp_path):
|
||||
@@ -78,3 +78,35 @@ def test_status_not_installed(tmp_path):
|
||||
def test_no_git_repo_raises(tmp_path):
|
||||
with pytest.raises(RuntimeError, match="No git repository"):
|
||||
install(tmp_path / "not_a_repo")
|
||||
|
||||
|
||||
def test_install_creates_post_checkout_hook(tmp_path):
|
||||
repo = _make_git_repo(tmp_path)
|
||||
install(repo)
|
||||
hook = repo / ".git" / "hooks" / "post-checkout"
|
||||
assert hook.exists()
|
||||
assert _CHECKOUT_MARKER in hook.read_text()
|
||||
|
||||
|
||||
def test_install_post_checkout_is_executable(tmp_path):
|
||||
repo = _make_git_repo(tmp_path)
|
||||
install(repo)
|
||||
hook = repo / ".git" / "hooks" / "post-checkout"
|
||||
assert hook.stat().st_mode & 0o111
|
||||
|
||||
|
||||
def test_uninstall_removes_post_checkout_hook(tmp_path):
|
||||
repo = _make_git_repo(tmp_path)
|
||||
install(repo)
|
||||
uninstall(repo)
|
||||
hook = repo / ".git" / "hooks" / "post-checkout"
|
||||
assert not hook.exists()
|
||||
|
||||
|
||||
def test_status_shows_both_hooks(tmp_path):
|
||||
repo = _make_git_repo(tmp_path)
|
||||
install(repo)
|
||||
result = status(repo)
|
||||
assert "post-commit" in result
|
||||
assert "post-checkout" in result
|
||||
assert result.count("installed") >= 2
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Tests for hyperedge support in graphify."""
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import networkx as nx
|
||||
import pytest
|
||||
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import attach_hyperedges, to_json
|
||||
from graphify.report import generate
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
SAMPLE_EXTRACTION = {
|
||||
"nodes": [
|
||||
{"id": "BasicAuth", "label": "BasicAuth", "file_type": "code", "source_file": "auth.py"},
|
||||
{"id": "DigestAuth", "label": "DigestAuth", "file_type": "code", "source_file": "auth.py"},
|
||||
{"id": "Request", "label": "Request", "file_type": "code", "source_file": "http.py"},
|
||||
{"id": "Response", "label": "Response", "file_type": "code", "source_file": "http.py"},
|
||||
{"id": "BaseClient", "label": "BaseClient", "file_type": "code", "source_file": "client.py"},
|
||||
],
|
||||
"edges": [
|
||||
{"source": "BasicAuth", "target": "Request", "relation": "uses", "confidence": "EXTRACTED", "confidence_score": 1.0, "source_file": "auth.py"},
|
||||
],
|
||||
"hyperedges": [
|
||||
{
|
||||
"id": "auth_flow",
|
||||
"label": "Auth Flow",
|
||||
"nodes": ["BasicAuth", "DigestAuth", "Request", "Response", "BaseClient"],
|
||||
"relation": "participate_in",
|
||||
"confidence": "INFERRED",
|
||||
"confidence_score": 0.75,
|
||||
"source_file": "auth.py",
|
||||
}
|
||||
],
|
||||
"input_tokens": 10,
|
||||
"output_tokens": 5,
|
||||
}
|
||||
|
||||
SAMPLE_DETECTION = {
|
||||
"total_files": 3,
|
||||
"total_words": 500,
|
||||
"files": {"code": ["auth.py", "http.py", "client.py"]},
|
||||
"skipped_sensitive": [],
|
||||
"warning": None,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. Hyperedges survive build_from_json round-trip
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_build_from_json_stores_hyperedges():
|
||||
G = build_from_json(SAMPLE_EXTRACTION)
|
||||
assert "hyperedges" in G.graph
|
||||
assert len(G.graph["hyperedges"]) == 1
|
||||
assert G.graph["hyperedges"][0]["id"] == "auth_flow"
|
||||
|
||||
|
||||
def test_build_from_json_no_hyperedges():
|
||||
extraction = {**SAMPLE_EXTRACTION, "hyperedges": []}
|
||||
G = build_from_json(extraction)
|
||||
assert G.graph.get("hyperedges", []) == []
|
||||
|
||||
|
||||
def test_build_from_json_missing_hyperedges_key():
|
||||
extraction = {k: v for k, v in SAMPLE_EXTRACTION.items() if k != "hyperedges"}
|
||||
G = build_from_json(extraction)
|
||||
assert G.graph.get("hyperedges", []) == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. attach_hyperedges deduplicates by id
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_attach_hyperedges_adds_new():
|
||||
G = nx.Graph()
|
||||
attach_hyperedges(G, [{"id": "auth_flow", "label": "Auth Flow", "nodes": ["A", "B", "C"]}])
|
||||
assert len(G.graph["hyperedges"]) == 1
|
||||
|
||||
|
||||
def test_attach_hyperedges_deduplicates():
|
||||
G = nx.Graph()
|
||||
h = {"id": "auth_flow", "label": "Auth Flow", "nodes": ["A", "B", "C"]}
|
||||
attach_hyperedges(G, [h])
|
||||
attach_hyperedges(G, [h]) # second call with same id should not duplicate
|
||||
assert len(G.graph["hyperedges"]) == 1
|
||||
|
||||
|
||||
def test_attach_hyperedges_multiple_different_ids():
|
||||
G = nx.Graph()
|
||||
attach_hyperedges(G, [
|
||||
{"id": "flow_a", "label": "Flow A", "nodes": ["A", "B", "C"]},
|
||||
{"id": "flow_b", "label": "Flow B", "nodes": ["D", "E", "F"]},
|
||||
])
|
||||
assert len(G.graph["hyperedges"]) == 2
|
||||
|
||||
|
||||
def test_attach_hyperedges_skips_entry_without_id():
|
||||
G = nx.Graph()
|
||||
attach_hyperedges(G, [{"label": "No ID", "nodes": ["A", "B", "C"]}])
|
||||
assert G.graph.get("hyperedges", []) == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. to_json includes hyperedges key
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_to_json_includes_hyperedges():
|
||||
G = build_from_json(SAMPLE_EXTRACTION)
|
||||
communities = {0: list(G.nodes())}
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
path = f.name
|
||||
to_json(G, communities, path)
|
||||
data = json.loads(Path(path).read_text())
|
||||
assert "hyperedges" in data
|
||||
assert len(data["hyperedges"]) == 1
|
||||
assert data["hyperedges"][0]["id"] == "auth_flow"
|
||||
|
||||
|
||||
def test_to_json_hyperedges_empty_when_none():
|
||||
extraction = {**SAMPLE_EXTRACTION, "hyperedges": []}
|
||||
G = build_from_json(extraction)
|
||||
communities = {0: list(G.nodes())}
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
path = f.name
|
||||
to_json(G, communities, path)
|
||||
data = json.loads(Path(path).read_text())
|
||||
assert "hyperedges" in data
|
||||
assert data["hyperedges"] == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. Hyperedges loaded from graph.json via build_from_json
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_hyperedges_roundtrip_via_json_file():
|
||||
"""Write graph.json then reload it - hyperedges must survive."""
|
||||
G = build_from_json(SAMPLE_EXTRACTION)
|
||||
communities = {0: list(G.nodes())}
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
path = f.name
|
||||
to_json(G, communities, path)
|
||||
|
||||
# Reload the JSON as if build_from_json were called on it
|
||||
data = json.loads(Path(path).read_text())
|
||||
G2 = build_from_json({
|
||||
"nodes": [{"id": n["id"], **{k: v for k, v in n.items() if k != "id"}} for n in data["nodes"]],
|
||||
"edges": [{"source": e["source"], "target": e["target"], **{k: v for k, v in e.items() if k not in ("source", "target")}} for e in data.get("links", [])],
|
||||
"hyperedges": data.get("hyperedges", []),
|
||||
})
|
||||
assert G2.graph.get("hyperedges", []) != []
|
||||
assert G2.graph["hyperedges"][0]["id"] == "auth_flow"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. Report includes hyperedges section when hyperedges present
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_report(G):
|
||||
communities = {0: list(G.nodes())}
|
||||
cohesion = {0: 1.0}
|
||||
labels = {0: "All"}
|
||||
gods = [{"label": "BasicAuth", "edges": 2}]
|
||||
surprises = []
|
||||
return generate(G, communities, cohesion, labels, gods, surprises, SAMPLE_DETECTION, {"input": 10, "output": 5}, ".")
|
||||
|
||||
|
||||
def test_report_includes_hyperedges_section():
|
||||
G = build_from_json(SAMPLE_EXTRACTION)
|
||||
report = _make_report(G)
|
||||
assert "## Hyperedges (group relationships)" in report
|
||||
assert "Auth Flow" in report
|
||||
assert "INFERRED 0.75" in report
|
||||
|
||||
|
||||
def test_report_includes_hyperedge_node_list():
|
||||
G = build_from_json(SAMPLE_EXTRACTION)
|
||||
report = _make_report(G)
|
||||
# Node IDs should appear in the report line
|
||||
assert "BasicAuth" in report
|
||||
assert "DigestAuth" in report
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 6. Report skips hyperedges section when none present
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_report_skips_hyperedges_section_when_empty():
|
||||
extraction = {**SAMPLE_EXTRACTION, "hyperedges": []}
|
||||
G = build_from_json(extraction)
|
||||
report = _make_report(G)
|
||||
assert "## Hyperedges" not in report
|
||||
|
||||
|
||||
def test_report_skips_hyperedges_section_when_key_missing():
|
||||
extraction = {k: v for k, v in SAMPLE_EXTRACTION.items() if k != "hyperedges"}
|
||||
G = build_from_json(extraction)
|
||||
report = _make_report(G)
|
||||
assert "## Hyperedges" not in report
|
||||
@@ -0,0 +1,159 @@
|
||||
"""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
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Tests for rationale/docstring extraction in extract.py."""
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from graphify.extract import extract_python
|
||||
|
||||
|
||||
def _write_py(tmp_path: Path, code: str) -> Path:
|
||||
p = tmp_path / "sample.py"
|
||||
p.write_text(textwrap.dedent(code))
|
||||
return p
|
||||
|
||||
|
||||
def test_module_docstring_extracted(tmp_path):
|
||||
path = _write_py(tmp_path, '''
|
||||
"""This module handles authentication because legacy sessions were insecure."""
|
||||
def login(): pass
|
||||
''')
|
||||
result = extract_python(path)
|
||||
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
|
||||
assert len(rationale) >= 1
|
||||
assert any("authentication" in n["label"] for n in rationale)
|
||||
|
||||
|
||||
def test_function_docstring_extracted(tmp_path):
|
||||
path = _write_py(tmp_path, '''
|
||||
def process():
|
||||
"""We use chunked processing here because the full dataset exceeds RAM."""
|
||||
pass
|
||||
''')
|
||||
result = extract_python(path)
|
||||
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
|
||||
assert any("chunked" in n["label"] for n in rationale)
|
||||
|
||||
|
||||
def test_class_docstring_extracted(tmp_path):
|
||||
path = _write_py(tmp_path, '''
|
||||
class Cache:
|
||||
"""Chosen over Redis because we need zero external dependencies in the test env."""
|
||||
pass
|
||||
''')
|
||||
result = extract_python(path)
|
||||
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
|
||||
assert any("Redis" in n["label"] for n in rationale)
|
||||
|
||||
|
||||
def test_rationale_comment_extracted(tmp_path):
|
||||
path = _write_py(tmp_path, '''
|
||||
def build():
|
||||
# NOTE: must run before compile() or linker will fail
|
||||
pass
|
||||
''')
|
||||
result = extract_python(path)
|
||||
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
|
||||
assert any("NOTE" in n["label"] for n in rationale)
|
||||
|
||||
|
||||
def test_rationale_for_edges_present(tmp_path):
|
||||
path = _write_py(tmp_path, '''
|
||||
"""Module docstring explaining the why."""
|
||||
def foo():
|
||||
"""Function docstring with rationale."""
|
||||
pass
|
||||
''')
|
||||
result = extract_python(path)
|
||||
rationale_edges = [e for e in result["edges"] if e.get("relation") == "rationale_for"]
|
||||
assert len(rationale_edges) >= 1
|
||||
|
||||
|
||||
def test_short_docstring_ignored(tmp_path):
|
||||
"""Trivial docstrings under 20 chars should not become rationale nodes."""
|
||||
path = _write_py(tmp_path, '''
|
||||
def foo():
|
||||
"""Constructor."""
|
||||
pass
|
||||
''')
|
||||
result = extract_python(path)
|
||||
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
|
||||
assert len(rationale) == 0
|
||||
|
||||
|
||||
def test_rationale_confidence_is_extracted(tmp_path):
|
||||
path = _write_py(tmp_path, '''
|
||||
"""This module exists because we needed a standalone parser."""
|
||||
def parse(): pass
|
||||
''')
|
||||
result = extract_python(path)
|
||||
rationale_edges = [e for e in result["edges"] if e.get("relation") == "rationale_for"]
|
||||
assert all(e.get("confidence") == "EXTRACTED" for e in rationale_edges)
|
||||
@@ -0,0 +1,194 @@
|
||||
"""Tests for semantically_similar_to edge support."""
|
||||
import networkx as nx
|
||||
import pytest
|
||||
from graphify.build import build_from_json
|
||||
from graphify.analyze import surprising_connections, _surprise_score
|
||||
from graphify.report import generate
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_extraction_with_semantic_edge():
|
||||
"""Two nodes in separate files connected by a semantically_similar_to edge."""
|
||||
return {
|
||||
"nodes": [
|
||||
{"id": "a_validate_input", "label": "validate_input", "file_type": "code",
|
||||
"source_file": "auth/validators.py", "source_location": "L5"},
|
||||
{"id": "b_check_input", "label": "check_input", "file_type": "code",
|
||||
"source_file": "api/checks.py", "source_location": "L12"},
|
||||
],
|
||||
"edges": [
|
||||
{
|
||||
"source": "a_validate_input",
|
||||
"target": "b_check_input",
|
||||
"relation": "semantically_similar_to",
|
||||
"confidence": "INFERRED",
|
||||
"confidence_score": 0.82,
|
||||
"source_file": "auth/validators.py",
|
||||
"source_location": None,
|
||||
"weight": 0.82,
|
||||
}
|
||||
],
|
||||
"input_tokens": 100,
|
||||
"output_tokens": 50,
|
||||
}
|
||||
|
||||
|
||||
def _make_graph_with_semantic_edge():
|
||||
return build_from_json(_make_extraction_with_semantic_edge())
|
||||
|
||||
|
||||
def _make_two_edge_graph():
|
||||
"""Graph with one semantically_similar_to edge and one references edge, both cross-file."""
|
||||
G = nx.Graph()
|
||||
for nid, label, src in [
|
||||
("a", "ValidateInput", "auth/validators.py"),
|
||||
("b", "CheckInput", "api/checks.py"),
|
||||
("c", "LoadConfig", "config/loader.py"),
|
||||
("d", "ReadConfig", "utils/reader.py"),
|
||||
]:
|
||||
G.add_node(nid, label=label, source_file=src, file_type="code")
|
||||
# semantically_similar_to edge
|
||||
G.add_edge("a", "b", relation="semantically_similar_to", confidence="INFERRED",
|
||||
confidence_score=0.82, source_file="auth/validators.py", weight=0.82,
|
||||
_src="a", _tgt="b")
|
||||
# plain references edge (same confidence tier)
|
||||
G.add_edge("c", "d", relation="references", confidence="INFERRED",
|
||||
confidence_score=0.7, source_file="config/loader.py", weight=0.7,
|
||||
_src="c", _tgt="d")
|
||||
return G
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Test 1: semantically_similar_to passes through build_from_json without being dropped
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_semantic_edge_survives_build_from_json():
|
||||
G = _make_graph_with_semantic_edge()
|
||||
assert G.number_of_edges() == 1
|
||||
u, v, data = next(iter(G.edges(data=True)))
|
||||
assert data["relation"] == "semantically_similar_to"
|
||||
|
||||
|
||||
def test_semantic_edge_nodes_present():
|
||||
G = _make_graph_with_semantic_edge()
|
||||
assert "a_validate_input" in G.nodes
|
||||
assert "b_check_input" in G.nodes
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Test 2: confidence_score is preserved for semantically_similar_to edges
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_semantic_edge_confidence_score_preserved():
|
||||
G = _make_graph_with_semantic_edge()
|
||||
u, v, data = next(iter(G.edges(data=True)))
|
||||
assert data.get("confidence_score") == pytest.approx(0.82)
|
||||
assert data.get("confidence") == "INFERRED"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Test 3: surprising_connections scores semantically_similar_to edges higher
|
||||
# than references edges with the same community membership
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_semantic_edge_scores_higher_than_references():
|
||||
G = _make_two_edge_graph()
|
||||
communities = {0: ["a", "b"], 1: ["c", "d"]}
|
||||
node_community = {"a": 0, "b": 0, "c": 1, "d": 1}
|
||||
|
||||
score_sem, reasons_sem = _surprise_score(
|
||||
G, "a", "b", G.edges["a", "b"], node_community,
|
||||
"auth/validators.py", "api/checks.py"
|
||||
)
|
||||
score_ref, _ = _surprise_score(
|
||||
G, "c", "d", G.edges["c", "d"], node_community,
|
||||
"config/loader.py", "utils/reader.py"
|
||||
)
|
||||
assert score_sem > score_ref
|
||||
|
||||
|
||||
def test_semantic_edge_reason_mentions_similarity():
|
||||
G = _make_two_edge_graph()
|
||||
communities = {0: ["a", "b"], 1: ["c", "d"]}
|
||||
node_community = {"a": 0, "b": 0, "c": 1, "d": 1}
|
||||
|
||||
_, reasons = _surprise_score(
|
||||
G, "a", "b", G.edges["a", "b"], node_community,
|
||||
"auth/validators.py", "api/checks.py"
|
||||
)
|
||||
assert any("similar" in r for r in reasons)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Test 4: report renders [semantically similar] tag for these edges
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_report_with_semantic_surprise():
|
||||
G = _make_graph_with_semantic_edge()
|
||||
communities = {0: ["a_validate_input", "b_check_input"]}
|
||||
cohesion = {0: 0.5}
|
||||
labels = {0: "Validators"}
|
||||
gods = []
|
||||
surprises = [
|
||||
{
|
||||
"source": "validate_input",
|
||||
"target": "check_input",
|
||||
"relation": "semantically_similar_to",
|
||||
"confidence": "INFERRED",
|
||||
"confidence_score": 0.82,
|
||||
"source_files": ["auth/validators.py", "api/checks.py"],
|
||||
"why": "semantically similar concepts with no structural link",
|
||||
}
|
||||
]
|
||||
detection = {"total_files": 2, "total_words": 500, "needs_graph": True, "warning": None}
|
||||
tokens = {"input": 100, "output": 50}
|
||||
return generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, "./project")
|
||||
|
||||
|
||||
def test_report_renders_semantically_similar_tag():
|
||||
report = _make_report_with_semantic_surprise()
|
||||
assert "[semantically similar]" in report
|
||||
|
||||
|
||||
def test_report_semantic_tag_on_correct_line():
|
||||
report = _make_report_with_semantic_surprise()
|
||||
for line in report.splitlines():
|
||||
if "semantically_similar_to" in line:
|
||||
assert "[semantically similar]" in line
|
||||
break
|
||||
else:
|
||||
pytest.fail("No line with semantically_similar_to found in report")
|
||||
|
||||
|
||||
def test_report_no_semantic_tag_for_other_relations():
|
||||
"""Non-semantic edges must not get the [semantically similar] tag."""
|
||||
G = nx.Graph()
|
||||
for nid, label, src in [
|
||||
("x", "Alpha", "repo1/a.py"),
|
||||
("y", "Beta", "repo2/b.py"),
|
||||
]:
|
||||
G.add_node(nid, label=label, source_file=src, file_type="code")
|
||||
G.add_edge("x", "y", relation="references", confidence="EXTRACTED",
|
||||
confidence_score=1.0, source_file="repo1/a.py", weight=1.0)
|
||||
|
||||
communities = {0: ["x", "y"]}
|
||||
cohesion = {0: 0.5}
|
||||
labels = {0: "Misc"}
|
||||
gods = []
|
||||
surprises = [
|
||||
{
|
||||
"source": "Alpha",
|
||||
"target": "Beta",
|
||||
"relation": "references",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_files": ["repo1/a.py", "repo2/b.py"],
|
||||
"why": "cross-file connection",
|
||||
}
|
||||
]
|
||||
detection = {"total_files": 2, "total_words": 200, "needs_graph": True, "warning": None}
|
||||
tokens = {"input": 50, "output": 25}
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, "./project")
|
||||
assert "[semantically similar]" not in report
|
||||
Reference in new issue
Block a user