Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1184e7d4d5 | ||
|
|
d3c7f950d5 | ||
|
|
5f02b3dfe1 | ||
|
|
5164d972ed | ||
|
|
6dc07e5f99 | ||
|
|
ccdd465a08 | ||
|
|
90fac738e2 | ||
|
|
83c2f4245c | ||
|
|
b37f187767 | ||
|
|
6fe4c01bb8 | ||
|
|
a7fc2493f0 | ||
|
|
494f519bf4 | ||
|
|
d23ae1774d | ||
|
|
e6fefa8a2c | ||
|
|
0f11f6a32d | ||
|
|
e8b8e2039d | ||
|
|
e4bc87a284 | ||
|
|
0a31c0862b | ||
|
|
2a8b6c16ad | ||
|
|
014758f61d | ||
|
|
5617a7d285 | ||
|
|
154919bb64 | ||
|
|
3baf316044 | ||
|
|
0fee55726d | ||
|
|
c488808842 | ||
|
|
546fc0b346 | ||
|
|
5ae2be8ca7 | ||
|
|
fd2cc8d8a7 | ||
|
|
ef06d7d8d9 | ||
|
|
93b8ec3cde | ||
|
|
e98c1b6297 | ||
|
|
a4ae70892a | ||
|
|
a1be5abb24 | ||
|
|
0061b36c29 | ||
|
|
c88528dfa3 | ||
|
|
a7f8cab1a9 | ||
|
|
fa702bd69f | ||
|
|
1cd52f191e | ||
|
|
d7a54d7e14 | ||
|
|
8708333484 | ||
|
|
a7d1969f02 | ||
|
|
258eff3e9f | ||
|
|
a7f910667d | ||
|
|
cf7f42d3e7 | ||
|
|
24bcd6d448 |
No files matched your search
@@ -0,0 +1,36 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["v1", "v2", "main"]
|
||||
pull_request:
|
||||
branches: ["v1", "v2", "main"]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: ["3.10", "3.12"]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pip install -e ".[mcp,pdf,watch]"
|
||||
pip install pytest
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
python -m pytest tests/ -q --tb=short
|
||||
|
||||
- name: Verify install works end-to-end
|
||||
run: |
|
||||
graphify --help
|
||||
graphify install
|
||||
@@ -13,3 +13,5 @@ build/
|
||||
*.so
|
||||
*.egg
|
||||
.graphify/
|
||||
graphify-out/
|
||||
.graphify_*.json
|
||||
@@ -0,0 +1,84 @@
|
||||
# Architecture
|
||||
|
||||
graphify is a Claude Code skill backed by a Python library. The skill orchestrates the library; the library can be used standalone.
|
||||
|
||||
## Pipeline
|
||||
|
||||
```
|
||||
detect() → extract() → build_graph() → cluster() → analyze() → report() → export()
|
||||
```
|
||||
|
||||
Each stage is a single function in its own module. They communicate through plain Python dicts and NetworkX graphs - no shared state, no side effects outside `graphify-out/`.
|
||||
|
||||
## Module responsibilities
|
||||
|
||||
| Module | Function | Input → Output |
|
||||
|--------|----------|----------------|
|
||||
| `detect.py` | `collect_files(root)` | directory → `[Path]` filtered list |
|
||||
| `extract.py` | `extract(path)` | file path → `{nodes, edges}` dict |
|
||||
| `build.py` | `build_graph(extractions)` | list of extraction dicts → `nx.Graph` |
|
||||
| `cluster.py` | `cluster(G)` | graph → graph with `community` attr on each node |
|
||||
| `analyze.py` | `analyze(G)` | graph → analysis dict (god nodes, surprises, questions) |
|
||||
| `report.py` | `render_report(G, analysis)` | graph + analysis → GRAPH_REPORT.md string |
|
||||
| `export.py` | `export(G, out_dir, ...)` | graph → Obsidian vault, graph.json, graph.html, graph.svg |
|
||||
| `ingest.py` | `ingest(url, ...)` | URL → file saved to corpus dir |
|
||||
| `cache.py` | `check_semantic_cache / save_semantic_cache` | files → (cached, uncached) split |
|
||||
| `security.py` | validation helpers | URL / path / label → validated or raises |
|
||||
| `validate.py` | `validate_extraction(data)` | extraction dict → raises on schema errors |
|
||||
| `serve.py` | `start_server(graph_path)` | graph file path → MCP stdio server |
|
||||
| `watch.py` | `watch(root, flag_path)` | directory → writes flag file on change |
|
||||
| `benchmark.py` | `run_benchmark(graph_path)` | graph file → corpus vs subgraph token comparison |
|
||||
|
||||
## Extraction output schema
|
||||
|
||||
Every extractor returns:
|
||||
|
||||
```json
|
||||
{
|
||||
"nodes": [
|
||||
{"id": "unique_string", "label": "human name", "source_file": "path", "source_location": "L42"}
|
||||
],
|
||||
"edges": [
|
||||
{"source": "id_a", "target": "id_b", "relation": "calls|imports|uses|...", "confidence": "EXTRACTED|INFERRED|AMBIGUOUS"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`validate.py` enforces this schema before `build_graph()` consumes it.
|
||||
|
||||
## Confidence labels
|
||||
|
||||
| Label | Meaning |
|
||||
|-------|---------|
|
||||
| `EXTRACTED` | Relationship is explicitly stated in the source (e.g., an import statement, a direct call) |
|
||||
| `INFERRED` | Relationship is a reasonable deduction (e.g., call-graph second pass, co-occurrence in context) |
|
||||
| `AMBIGUOUS` | Relationship is uncertain; flagged for human review in GRAPH_REPORT.md |
|
||||
|
||||
## Adding a new language extractor
|
||||
|
||||
1. Add a `extract_<lang>(path: Path) -> dict` function in `extract.py` following the existing pattern (tree-sitter parse → walk nodes → collect `nodes` and `edges` → call-graph second pass for INFERRED `calls` edges).
|
||||
2. Register the file suffix in `extract()` dispatch and `collect_files()`.
|
||||
3. Add the suffix to `CODE_EXTENSIONS` in `detect.py` and `_WATCHED_EXTENSIONS` in `watch.py`.
|
||||
4. Add the tree-sitter package to `pyproject.toml` dependencies.
|
||||
5. Add a fixture file to `tests/fixtures/` and tests to `tests/test_languages.py`.
|
||||
|
||||
## Security
|
||||
|
||||
All external input passes through `graphify/security.py` before use:
|
||||
|
||||
- URLs → `validate_url()` (http/https only) + `_NoFileRedirectHandler` (blocks file:// redirects)
|
||||
- Fetched content → `safe_fetch()` / `safe_fetch_text()` (size cap, timeout)
|
||||
- Graph file paths → `validate_graph_path()` (must resolve inside `graphify-out/`)
|
||||
- Node labels → `sanitize_label()` (strips control chars, caps 256 chars, HTML-escapes)
|
||||
|
||||
See `SECURITY.md` for the full threat model.
|
||||
|
||||
## Testing
|
||||
|
||||
One test file per module under `tests/`. Run with:
|
||||
|
||||
```bash
|
||||
pytest tests/ -q
|
||||
```
|
||||
|
||||
All tests are pure unit tests - no network calls, no file system side effects outside `tmp_path`.
|
||||
@@ -0,0 +1,72 @@
|
||||
# Changelog
|
||||
|
||||
## 0.1.8 (2026-04-05)
|
||||
|
||||
- Fix: follow-up questions now check for wiki first (graphify-out/wiki/index.md) before falling back to graph.json
|
||||
- Fix: --update now auto-regenerates wiki if graphify-out/wiki/ exists
|
||||
- Fix: community articles show truncation notice ("... and N more nodes") when > 25 nodes
|
||||
- UX: pipeline completion message now lists all available flags and commands so users know what graphify can do
|
||||
|
||||
## 0.1.7 (2026-04-05)
|
||||
|
||||
- Add: `--wiki` flag — generates Wikipedia-style agent-crawlable wiki from the graph (index.md + community articles + god node articles)
|
||||
- Add: `graphify/wiki.py` module with `to_wiki()` — cross-community wikilinks, cohesion scores, audit trail, navigation footer
|
||||
- Add: 14 wiki tests (245 total)
|
||||
- Fix: follow-up question example code now correctly splits node labels by `_` to extract verb prefixes (previous version used `def`/`fn` prefix matching which always returned zero results)
|
||||
|
||||
## 0.1.6 (2026-04-05)
|
||||
|
||||
- Fix: follow-up questions after pipeline now answered from graph.json, not by re-exploring the directory (was 25 tool calls / 1m30s; now instant)
|
||||
- Skill: added "Answering Follow-up Questions" section with graph query patterns
|
||||
|
||||
## 0.1.5 (2026-04-05)
|
||||
|
||||
- Perf: semantic extraction chunks 12-15 → 20-25 files (fewer subagent round trips)
|
||||
- Perf: code-only corpora skip semantic dispatch entirely (AST handles it)
|
||||
- Perf: print timing estimate before extraction so the wait feels intentional
|
||||
- Fix: 5 skill gaps - --graphml in Usage table, --update manifest timing, query/path/explain graph existence check, --no-viz clarity
|
||||
- Refactor: dead imports removed (shutil, sys, inline os); _node_community_map() helper replaces 8 copy-pasted dict comprehensions; to_html() split into _html_styles() + _html_script(); serve.py call_tool() if/elif chain replaced with dispatch table
|
||||
- Test: end-to-end pipeline integration test (detect → extract → build → cluster → analyze → report → export)
|
||||
|
||||
## 0.1.4 (2026-04-05)
|
||||
|
||||
- Replace pyvis with custom vis.js HTML renderer - node size by degree, click-to-inspect panel with clickable neighbors, search box, community filter, physics clustering
|
||||
- HTML graph generated by default on every run (no flag needed)
|
||||
- Token reduction benchmark auto-runs after every pipeline on corpora over 5,000 words
|
||||
- Fix: 292 edge warnings per run eliminated - stdlib/external edges now silently skipped
|
||||
- Fix: `build()` cross-extraction edges were silently dropped - now merged before assembly
|
||||
- Fix: `pip install graphify` → `pip install graphifyy` in skill Step 1 (critical install bug)
|
||||
- Add: `--graphml` flag implemented in skill pipeline (was documented but not wired up)
|
||||
- Remove: pyvis dependency, dead lib/ folder, misplaced eval reports from tests/
|
||||
- Add: 5 HTML renderer tests (223 total)
|
||||
|
||||
## 0.1.3 (2026-04-04)
|
||||
|
||||
- Fix: `pyproject.toml` structure - `requires-python` and `dependencies` were incorrectly placed under `[project.urls]`
|
||||
- Add: GitHub repository and issues URLs to PyPI page
|
||||
- Add: `keywords` for PyPI search discoverability
|
||||
- Docs: README clarifies Claude Code requirement, temporary PyPI name, worked examples footnote
|
||||
|
||||
## 0.1.1 (2026-04-04)
|
||||
|
||||
- Add: CI badge to README (GitHub Actions, Python 3.10 + 3.12)
|
||||
- Add: ARCHITECTURE.md - pipeline overview, module table, extraction schema, how to add a language
|
||||
- Add: SECURITY.md - threat model, mitigations, vulnerability reporting
|
||||
- Add: `worked/` directory with eval reports (karpathy-repos 71.5x benchmark, httpx, mixed-corpus)
|
||||
- Fix: pytest not found in CI - added explicit `pip install pytest` step
|
||||
- Fix: README test count (163 → 212), language table, worked examples links
|
||||
- Docs: README reframed as Claude Code skill; Karpathy problem → graphify answer framing
|
||||
|
||||
## 0.1.0 (2026-04-03)
|
||||
|
||||
Initial release.
|
||||
|
||||
- 13-language AST extraction via tree-sitter (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP)
|
||||
- Leiden community detection via graspologic with oversized community splitting
|
||||
- SHA256 semantic cache - warm re-runs skip unchanged files
|
||||
- MCP stdio server - `query_graph`, `get_node`, `get_neighbors`, `shortest_path`, `god_nodes`
|
||||
- Memory feedback loop - Q&A results saved to `graphify-out/memory/`, extracted on `--update`
|
||||
- Obsidian vault export with wikilinks, community tags, Canvas layout
|
||||
- Security module - URL validation, safe fetch with size cap, path guards, label sanitisation
|
||||
- `graphify install` CLI - copies skill to `~/.claude/skills/` and registers in `CLAUDE.md`
|
||||
- Parallel subagent extraction for docs, papers, and images
|
||||
@@ -1,44 +1,41 @@
|
||||
# graphify
|
||||
|
||||
any folder of files → persistent knowledge graph → Obsidian vault, graph.json, audit report
|
||||
[](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. 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.
|
||||
|
||||
```
|
||||
/graphify ./raw
|
||||
/graphify . # works on any folder - your codebase, notes, papers, anything
|
||||
```
|
||||
|
||||
```
|
||||
.graphify/
|
||||
├── obsidian/ open as Obsidian vault — visual graph, wikilinks, filter by community
|
||||
├── GRAPH_REPORT.md what the graph found: god nodes, surprising connections, suggested questions
|
||||
├── graph.json persistent graph — query it weeks later without re-reading anything
|
||||
├── cache/ per-file SHA256 cache — re-runs only process changed files
|
||||
└── memory/ Q&A results filed back in — what you ask grows the graph on next --update
|
||||
graphify-out/
|
||||
├── graph.html interactive graph - click nodes, search, filter by community
|
||||
├── 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
|
||||
```
|
||||
|
||||
[placeholder: animated GIF showing the full pipeline — detect → extract → cluster → report → Obsidian vault]
|
||||
## How it works
|
||||
|
||||
## Why this exists
|
||||
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.
|
||||
|
||||
**The problem:** Andrej Karpathy described it well: he keeps a `/raw` folder where he drops papers, tweets, screenshots, and notes. The problem is that folder becomes opaque. You forget what's in it. You can't see what connects. Ask Claude "what links paper A to the code in repo B?" and it will hallucinate — it hasn't read both, and even if it has, it has no memory of that connection next session.
|
||||
|
||||
**What LLMs get wrong:** Naive summarization fills in every gap confidently. You get a summary that sounds complete but you can't tell what was actually in the files vs invented by the model. And next session, it's all gone — no memory of what it extracted.
|
||||
|
||||
**What graphify does differently:**
|
||||
|
||||
- **Persistent graph** — relationships are stored in `.graphify/graph.json` and survive across sessions. Query weeks later without re-reading anything.
|
||||
- **Honest audit trail** — every edge is tagged `EXTRACTED` (explicitly stated), `INFERRED` (call-graph or reasonable deduction), or `AMBIGUOUS` (flagged for review). You always know what was found vs invented.
|
||||
- **Cross-document surprise** — Leiden community detection finds clusters, then surfaces cross-community connections: the things you would never think to ask about directly.
|
||||
- **Feedback loop** — every query answer is saved to `.graphify/memory/`. On next `--update`, that Q&A becomes a node. The graph grows from what you ask, not just what you add.
|
||||
|
||||
The result: a navigable map of your corpus that is honest about what it knows and what it guessed.
|
||||
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+
|
||||
|
||||
```bash
|
||||
pip install graphify && graphify install
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
That's it. This copies the skill file into `~/.claude/skills/graphify/` and registers it in `~/.claude/CLAUDE.md` automatically. The Python package and all dependencies install on first `/graphify` run — you never touch pip manually again.
|
||||
> 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:
|
||||
|
||||
@@ -46,23 +43,37 @@ Then open Claude Code in any directory and type:
|
||||
/graphify .
|
||||
```
|
||||
|
||||
### Make Claude always use the graph (recommended)
|
||||
|
||||
After building a graph, run this once in your project:
|
||||
|
||||
```bash
|
||||
graphify claude install
|
||||
```
|
||||
|
||||
This does two things:
|
||||
|
||||
1. **CLAUDE.md rules** - tells Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and to rebuild the graph after editing code files.
|
||||
|
||||
2. **PreToolUse hook** (`settings.json`) - fires automatically before every Glob and Grep call. If a knowledge graph exists, Claude sees: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ This means Claude navigates via the graph instead of grepping through every file - faster answers, fewer wasted tool calls, and responses grounded in the actual structure of your codebase rather than keyword matches.
|
||||
|
||||
Without this, Claude will grep raw files by default even when a graph exists. With it, the graph becomes the first thing Claude reaches for.
|
||||
|
||||
Uninstall with `graphify claude uninstall`.
|
||||
|
||||
<details>
|
||||
<summary>Manual install (curl)</summary>
|
||||
|
||||
**Step 1 — copy the skill file**
|
||||
|
||||
```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/v2/graphify/skill.md \
|
||||
> ~/.claude/skills/graphify/SKILL.md
|
||||
```
|
||||
|
||||
**Step 2 — register it in Claude Code**
|
||||
|
||||
Add this to `~/.claude/CLAUDE.md` (create the file if it doesn't exist):
|
||||
Add to `~/.claude/CLAUDE.md`:
|
||||
|
||||
```
|
||||
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) — any input to knowledge graph. Trigger: `/graphify`
|
||||
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
|
||||
```
|
||||
|
||||
@@ -70,147 +81,89 @@ When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"`
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
```
|
||||
/graphify # run on current directory
|
||||
/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 --watch # notify when new files appear
|
||||
/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 <url> --author "Karpathy" --contributor "safi"
|
||||
|
||||
/graphify query "what connects attention to the optimizer?" # BFS — broad context
|
||||
/graphify query "how does the encoder reach the loss?" --dfs # DFS — trace a path
|
||||
/graphify query "..." --budget 1500 # cap at N tokens
|
||||
/graphify query "what connects attention to the optimizer?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
/graphify path "DigestAuth" "Response" # shortest path between two concepts
|
||||
/graphify explain "SwinTransformer" # plain-language node explanation
|
||||
/graphify ./raw --watch # auto-sync graph as files change (code: instant, docs: notifies you)
|
||||
/graphify ./raw --wiki # build agent-crawlable wiki (index.md + article per community)
|
||||
/graphify ./raw --svg # export graph.svg
|
||||
/graphify ./raw --graphml # export graph.graphml (Gephi, yEd)
|
||||
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
|
||||
/graphify ./raw --mcp # start MCP stdio server
|
||||
|
||||
/graphify ./raw --html # also export graph.html (browser, no Obsidian needed)
|
||||
/graphify ./raw --svg # also export graph.svg (embeds in Notion, GitHub)
|
||||
/graphify ./raw --neo4j # generate cypher.txt for Neo4j import
|
||||
/graphify ./raw --mcp # start MCP stdio server for agent access
|
||||
graphify hook install # git hooks - rebuilds graph on commit and branch switch
|
||||
graphify claude install # always-on: CLAUDE.md + PreToolUse hook for this project
|
||||
```
|
||||
|
||||
Works with any mix of file types in the same folder:
|
||||
Works with any mix of file types:
|
||||
|
||||
| Type | Extensions | How it's extracted |
|
||||
|------|-----------|-------------------|
|
||||
| Code | `.py .ts .tsx .js .go .rs` | AST (deterministic) + call-graph pass (INFERRED) |
|
||||
| Code | `.java .cpp .c .rb .swift .kt` | Claude semantic extraction |
|
||||
| Documents | `.md .txt .rst` | Concepts + relationships via Claude |
|
||||
| Type | Extensions | Extraction |
|
||||
|------|-----------|------------|
|
||||
| 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 .svg` | Claude vision — screenshots, charts, whiteboards, any language |
|
||||
| Images | `.png .jpg .webp .gif` | Claude vision - screenshots, diagrams, any language |
|
||||
|
||||
## What you get
|
||||
|
||||
After running, Claude outputs three things directly in chat:
|
||||
**God nodes** - highest-degree concepts (what everything connects through)
|
||||
|
||||
**God nodes** — highest-degree concepts (what everything connects through)
|
||||
**Surprising connections** - ranked by composite score. Code-paper edges rank higher than code-code. Each result includes a plain-English why.
|
||||
|
||||
**Surprising connections** — cross-community edges; relationships between concepts in different clusters that you didn't know to look for
|
||||
**Suggested questions** - 4-5 questions the graph is uniquely positioned to answer
|
||||
|
||||
**Suggested questions** — 4-5 questions the graph is uniquely positioned to answer, with the reason why (which bridge node makes it interesting, which community boundary it crosses)
|
||||
**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.
|
||||
|
||||
The full GRAPH_REPORT.md adds community summaries with cohesion scores and a list of ambiguous edges for review.
|
||||
**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.
|
||||
|
||||
## Key files explained
|
||||
**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.
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `GRAPH_REPORT.md` | The audit report. God nodes, surprising connections, community cohesion scores, ambiguous edge list, suggested questions. |
|
||||
| `graph.json` | Persistent graph in node-link format. Load it with NetworkX or push to Neo4j. Survives sessions. |
|
||||
| `obsidian/` | Wikilink vault. Open in Obsidian → enable graph view → see communities as clusters. Filter by tag, search across everything. |
|
||||
| `.graphify/cache/` | SHA256-based per-file cache. A re-run on an unchanged corpus takes seconds. |
|
||||
| `.graphify/memory/` | Q&A feedback loop. Every `/graphify query` answer is saved here. Next `--update` extracts it into the graph. |
|
||||
**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.
|
||||
|
||||
## What this skill will NOT do
|
||||
**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.
|
||||
|
||||
- **Won't invent edges** — `AMBIGUOUS` exists so uncertain relationships are flagged, not hidden. If the connection isn't clear, it's tagged, not fabricated.
|
||||
- **Won't claim the graph is useful when it isn't** — a corpus over 2M words or 200 files gets a cost warning before proceeding.
|
||||
- **Won't re-extract unchanged files** — SHA256 cache ensures warm re-runs skip everything that hasn't changed.
|
||||
- **Won't visualize graphs over 5,000 nodes** — use `--no-viz` or query instead.
|
||||
- **Won't download datasets or set up infrastructure** — graphify reads your files. What you put in the folder is what it works with.
|
||||
- **Won't implement baselines or run experiments** — it reads and maps. Analysis is yours.
|
||||
**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.
|
||||
|
||||
## Design principles
|
||||
**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.
|
||||
|
||||
1. **Extraction quality is everything** — clustering is downstream of it. A bad graph clusters into bad communities. The AST + call-graph pass exists because deterministic beats probabilistic for code.
|
||||
2. **Show the numbers** — cohesion is `0.91`, not "good". Token cost is always printed. You know what you spent.
|
||||
3. **The best output is what you didn't know** — Surprising Connections is not optional. God nodes you probably already suspected. Cross-community edges are what you came for.
|
||||
4. **The graph earns its complexity** — below a certain density, just use Claude directly. The graph adds value when you have more than you can hold in context across sessions.
|
||||
5. **What you ask grows the graph** — query results are filed back in automatically. The corpus is not static.
|
||||
6. **Honest uncertainty** — `EXTRACTED`, `INFERRED`, `AMBIGUOUS` are not cosmetic labels. They are the difference between trusting the graph and being misled by it.
|
||||
|
||||
## Contributing
|
||||
|
||||
**Adding worked examples**
|
||||
|
||||
Worked examples are the most trust-building part of this project. To add one:
|
||||
|
||||
1. Pick a real corpus (people should be able to verify the output)
|
||||
2. Run the skill: `/graphify <path>`
|
||||
3. Save the full output to `worked/{corpus_slug}/`
|
||||
4. Write a `review.md` that honestly evaluates:
|
||||
- What the graph got right
|
||||
- What edges it correctly flagged AMBIGUOUS
|
||||
- Any mistakes or missed connections
|
||||
- Any surprising connections that were genuinely surprising
|
||||
5. Submit a PR with all of the above
|
||||
|
||||
**Improving extraction**
|
||||
|
||||
If you find a file type or language where extraction is poor, open an issue with a minimal reproduction case. The best bug reports include: the input file, the extraction output (`.graphify/cache/` entry), and what was missed or invented.
|
||||
|
||||
**Adding domain knowledge**
|
||||
|
||||
If corpora in your domain consistently contain structures graphify doesn't extract well (e.g., legal documents, lab notebooks, musical scores), open a discussion with examples.
|
||||
**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.
|
||||
|
||||
## Worked examples
|
||||
|
||||
| Corpus | Type | Eval report |
|
||||
|--------|------|-------------|
|
||||
| httpx (Python HTTP client) | Codebase | `tests/EVAL_httpx.md` + `tests/GRAPH_REPORT_httpx.md` |
|
||||
| Mixed corpus (code + paper + Arabic image) | Multi-type | `tests/EVAL_mixed_corpus.md` |
|
||||
| Corpus | Files | Reduction | Output |
|
||||
|--------|-------|-----------|--------|
|
||||
| Karpathy repos + 5 papers + 4 images | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
|
||||
| graphify source + Transformer paper | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
|
||||
| httpx (synthetic Python library) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
|
||||
|
||||
Each includes the full graph output and an honest evaluation of what the skill got right and wrong.
|
||||
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 the Claude API (Anthropic) for semantic extraction of docs, papers, and images. Code files are processed locally via tree-sitter AST — no file contents leave your machine for code. No telemetry, usage tracking, or analytics of any kind. The only network calls are to Anthropic's API during extraction, using your own API key via Claude Code.
|
||||
|
||||
## Tech stack
|
||||
|
||||
| Layer | Library | Why |
|
||||
|-------|---------|-----|
|
||||
| Graph | NetworkX | Pure Python, same internals as MS GraphRAG |
|
||||
| Community detection | Leiden via graspologic | Better than K-means for sparse graphs |
|
||||
| Code parsing | tree-sitter | Multi-language AST, deterministic, zero hallucination |
|
||||
| Extraction | Claude (parallel subagents) | Reads anything, outputs structured graph data |
|
||||
| Visualization | Obsidian vault | Native graph view, wikilinks, no server needed |
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + Claude + vis.js. No Neo4j required, no server, runs entirely locally.
|
||||
|
||||
No Neo4j required. No dashboards. No server. Runs entirely locally.
|
||||
<details>
|
||||
<summary>Contributing</summary>
|
||||
|
||||
## Files
|
||||
**Worked examples** are the most trust-building contribution. Run `/graphify` on a real corpus, save output to `worked/{slug}/`, write an honest `review.md` evaluating what the graph got right and wrong, submit a PR.
|
||||
|
||||
```
|
||||
graphify/
|
||||
├── detect.py detect file types, auto-exclude venvs/caches/node_modules; scan .graphify/memory/
|
||||
├── extract.py AST extraction (Python, TypeScript, JavaScript, Go, Rust) + call-graph pass
|
||||
├── build.py assemble NetworkX graph from extraction JSON; schema-validates before assembly
|
||||
├── cluster.py Leiden community detection, cohesion scoring
|
||||
├── analyze.py god nodes, bridge nodes, surprising connections, suggested questions, graph diff
|
||||
├── report.py render GRAPH_REPORT.md
|
||||
├── export.py Obsidian vault, graph.json, graph.html, graph.svg, Neo4j Cypher, Canvas
|
||||
├── ingest.py fetch URLs (arXiv, Twitter/X, PDF, any webpage); save Q&A to .graphify/memory/
|
||||
├── cache.py SHA256-based per-file extraction cache; check_semantic_cache / save_semantic_cache
|
||||
├── security.py URL validation (http/https only), safe fetch with size cap, path guards, label sanitisation
|
||||
├── validate.py JSON schema checks on extraction output
|
||||
├── serve.py MCP stdio server — query_graph, get_node, get_neighbors, shortest_path, god_nodes
|
||||
└── watch.py fs watcher, writes flag file when new files appear
|
||||
**Extraction bugs** - open an issue with the input file, the cache entry (`graphify-out/cache/`), and what was missed or invented.
|
||||
|
||||
skills/graphify/
|
||||
└── skill.md the Claude Code skill — the full pipeline the agent runs step by step
|
||||
See [ARCHITECTURE.md](ARCHITECTURE.md) for module responsibilities and how to add a language.
|
||||
|
||||
SECURITY.md threat model, mitigations, vulnerability reporting
|
||||
tests/ 163 tests, one file per module
|
||||
pyproject.toml pip install graphify | pip install graphify[mcp,neo4j,pdf,watch]
|
||||
```
|
||||
</details>
|
||||
+7
-7
@@ -22,27 +22,27 @@ We will acknowledge receipt within 48 hours and aim to release a fix within 7 da
|
||||
|
||||
## Security Model
|
||||
|
||||
graphify is a **local development tool**. It runs as a Claude Code skill and optionally as a local MCP stdio server. It makes no network calls during graph analysis — only during `ingest` (explicit URL fetch by the user).
|
||||
graphify is a **local development tool**. It runs as a Claude Code skill and optionally as a local MCP stdio server. It makes no network calls during graph analysis - only during `ingest` (explicit URL fetch by the user).
|
||||
|
||||
### Threat Surface
|
||||
|
||||
| Vector | Mitigation |
|
||||
|--------|-----------|
|
||||
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes. Redirect targets are re-validated by `_NoFileRedirectHandler` — a redirect to `file://` is blocked. |
|
||||
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes. Redirect targets are re-validated by `_NoFileRedirectHandler` - a redirect to `file://` is blocked. |
|
||||
| Oversized downloads | `safe_fetch()` streams responses and aborts at 50 MB. `safe_fetch_text()` aborts at 10 MB. |
|
||||
| Non-2xx HTTP responses | `safe_fetch()` raises `HTTPError` on non-2xx status codes — error pages are not silently treated as content. |
|
||||
| Path traversal in MCP server | `security.validate_graph_path()` resolves paths and requires them to be inside `.graphify/`. Also requires the `.graphify/` directory to exist. |
|
||||
| Non-2xx HTTP responses | `safe_fetch()` raises `HTTPError` on non-2xx status codes - error pages are not silently treated as content. |
|
||||
| Path traversal in MCP server | `security.validate_graph_path()` resolves paths and requires them to be inside `graphify-out/`. Also requires the `graphify-out/` directory to exist. |
|
||||
| XSS in graph HTML output | `security.sanitize_label()` strips control characters, caps at 256 chars, and HTML-escapes all node labels and edge titles before pyvis embeds them. |
|
||||
| Prompt injection via node labels | `sanitize_label()` also applied to MCP text output — node labels from user-controlled source files cannot break the text format returned to agents. |
|
||||
| Prompt injection via node labels | `sanitize_label()` also applied to MCP text output - node labels from user-controlled source files cannot break the text format returned to agents. |
|
||||
| YAML frontmatter injection | Newlines stripped from user-provided strings before embedding in YAML frontmatter (e.g. in `save_query_result()`). |
|
||||
| Encoding crashes on source files | All tree-sitter byte slices decoded with `errors="replace"` — non-UTF-8 source files degrade gracefully instead of crashing extraction. |
|
||||
| Encoding crashes on source files | All tree-sitter byte slices decoded with `errors="replace"` - non-UTF-8 source files degrade gracefully instead of crashing extraction. |
|
||||
| Symlink traversal | `os.walk(..., followlinks=False)` is explicit throughout `detect.py`. |
|
||||
| Corrupted graph.json | `_load_graph()` in `serve.py` wraps `json.JSONDecodeError` and prints a clear recovery message instead of crashing. |
|
||||
|
||||
### What graphify does NOT do
|
||||
|
||||
- Does not run a network listener (MCP server communicates over stdio only)
|
||||
- Does not execute code from source files (tree-sitter parses ASTs — no eval/exec)
|
||||
- Does not execute code from source files (tree-sitter parses ASTs - no eval/exec)
|
||||
- Does not use `shell=True` in any subprocess call
|
||||
- Does not store credentials or API keys
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""graphify — extract · build · cluster · analyze · report."""
|
||||
"""graphify - extract · build · cluster · analyze · report."""
|
||||
|
||||
|
||||
def __getattr__(name):
|
||||
@@ -18,6 +18,7 @@ def __getattr__(name):
|
||||
"to_html": ("graphify.export", "to_html"),
|
||||
"to_svg": ("graphify.export", "to_svg"),
|
||||
"to_canvas": ("graphify.export", "to_canvas"),
|
||||
"to_wiki": ("graphify.wiki", "to_wiki"),
|
||||
}
|
||||
if name in _map:
|
||||
import importlib
|
||||
|
||||
+157
-4
@@ -1,14 +1,29 @@
|
||||
"""graphify CLI — `graphify install` sets up the Claude Code skill."""
|
||||
"""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`) "
|
||||
"— any input to knowledge graph. Trigger: `/graphify`\n"
|
||||
"- any input to knowledge graph. Trigger: `/graphify`\n"
|
||||
"When the user types `/graphify`, invoke the Skill tool "
|
||||
"with `skill: \"graphify\"` before doing anything else.\n"
|
||||
)
|
||||
@@ -22,7 +37,7 @@ def _bundled_skill() -> Path:
|
||||
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)
|
||||
print("error: skill.md not found in package - reinstall graphify", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Copy skill to ~/.claude/skills/graphify/SKILL.md
|
||||
@@ -52,6 +67,118 @@ def install() -> None:
|
||||
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"
|
||||
|
||||
|
||||
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>")
|
||||
@@ -59,15 +186,41 @@ def main() -> None:
|
||||
print("Commands:")
|
||||
print(" install copy skill to ~/.claude/skills/ and register in CLAUDE.md")
|
||||
print(" benchmark [graph.json] measure token reduction vs naive full-corpus approach")
|
||||
print(" hook install install post-commit git hook (auto-rebuilds graph on commit)")
|
||||
print(" hook uninstall remove post-commit git hook")
|
||||
print(" hook status check if hook is installed")
|
||||
print(" claude install write graphify section to local CLAUDE.md")
|
||||
print(" claude uninstall remove graphify section from local CLAUDE.md")
|
||||
print()
|
||||
return
|
||||
|
||||
cmd = sys.argv[1]
|
||||
if cmd == "install":
|
||||
install()
|
||||
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 == "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 ""
|
||||
if subcmd == "install":
|
||||
print(hook_install(Path(".")))
|
||||
elif subcmd == "uninstall":
|
||||
print(hook_uninstall(Path(".")))
|
||||
elif subcmd == "status":
|
||||
print(hook_status(Path(".")))
|
||||
else:
|
||||
print("Usage: graphify hook [install|uninstall|status]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
elif cmd == "benchmark":
|
||||
from graphify.benchmark import run_benchmark, print_benchmark
|
||||
graph_path = sys.argv[2] if len(sys.argv) > 2 else ".graphify/graph.json"
|
||||
graph_path = sys.argv[2] if len(sys.argv) > 2 else "graphify-out/graph.json"
|
||||
# Try to load corpus_words from detect output
|
||||
corpus_words = None
|
||||
detect_path = Path(".graphify_detect.json")
|
||||
|
||||
+134
-41
@@ -3,6 +3,11 @@ from __future__ import annotations
|
||||
import networkx as nx
|
||||
|
||||
|
||||
def _node_community_map(communities: dict[int, list[str]]) -> dict[str, int]:
|
||||
"""Invert communities dict: node_id -> community_id."""
|
||||
return {n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
|
||||
|
||||
def _is_file_node(G: nx.Graph, node_id: str) -> bool:
|
||||
"""
|
||||
Return True if this node is a file-level hub node (e.g. 'client', 'models')
|
||||
@@ -20,7 +25,7 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
|
||||
# Method stub: AST extractor labels methods as '.method_name()'
|
||||
if label.startswith(".") and label.endswith("()"):
|
||||
return True
|
||||
# Module-level function stub: labeled 'function_name()' — only has a contains edge
|
||||
# Module-level function stub: labeled 'function_name()' - only has a contains edge
|
||||
# These are real functions but structurally isolated by definition; not a gap worth flagging
|
||||
if label.endswith("()") and G.degree(node_id) <= 1:
|
||||
return True
|
||||
@@ -28,7 +33,7 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
|
||||
|
||||
|
||||
def god_nodes(G: nx.Graph, top_n: int = 10) -> list[dict]:
|
||||
"""Return the top_n most-connected real entities — the core abstractions.
|
||||
"""Return the top_n most-connected real entities - the core abstractions.
|
||||
|
||||
File-level hub nodes are excluded: they accumulate import/contains edges
|
||||
mechanically and don't represent meaningful architectural abstractions.
|
||||
@@ -55,7 +60,7 @@ def surprising_connections(
|
||||
top_n: int = 5,
|
||||
) -> list[dict]:
|
||||
"""
|
||||
Find connections that are genuinely surprising — not obvious from file structure.
|
||||
Find connections that are genuinely surprising - not obvious from file structure.
|
||||
|
||||
Strategy:
|
||||
- Multi-file corpora: cross-file edges between real entities (not concept nodes).
|
||||
@@ -100,21 +105,105 @@ def _is_concept_node(G: nx.Graph, node_id: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
_CODE_EXTENSIONS = {"py", "ts", "tsx", "js", "go", "rs", "java", "rb", "cpp", "c", "h", "cs", "kt", "scala", "php"}
|
||||
_DOC_EXTENSIONS = {"md", "txt", "rst"}
|
||||
_PAPER_EXTENSIONS = {"pdf"}
|
||||
_IMAGE_EXTENSIONS = {"png", "jpg", "jpeg", "webp", "gif", "svg"}
|
||||
|
||||
|
||||
def _file_category(path: str) -> str:
|
||||
ext = path.rsplit(".", 1)[-1].lower() if "." in path else ""
|
||||
if ext in _CODE_EXTENSIONS:
|
||||
return "code"
|
||||
if ext in _PAPER_EXTENSIONS:
|
||||
return "paper"
|
||||
if ext in _IMAGE_EXTENSIONS:
|
||||
return "image"
|
||||
return "doc"
|
||||
|
||||
|
||||
def _top_level_dir(path: str) -> str:
|
||||
"""Return the first path component - used to detect cross-repo edges."""
|
||||
return path.split("/")[0] if "/" in path else path
|
||||
|
||||
|
||||
def _surprise_score(
|
||||
G: nx.Graph,
|
||||
u: str,
|
||||
v: str,
|
||||
data: dict,
|
||||
node_community: dict[str, int],
|
||||
u_source: str,
|
||||
v_source: str,
|
||||
) -> tuple[int, list[str]]:
|
||||
"""Score how surprising a cross-file edge is. Returns (score, reasons)."""
|
||||
score = 0
|
||||
reasons: list[str] = []
|
||||
|
||||
# 1. Confidence weight - uncertain connections are more noteworthy
|
||||
conf = data.get("confidence", "EXTRACTED")
|
||||
conf_bonus = {"AMBIGUOUS": 3, "INFERRED": 2, "EXTRACTED": 1}.get(conf, 1)
|
||||
score += conf_bonus
|
||||
if conf in ("AMBIGUOUS", "INFERRED"):
|
||||
reasons.append(f"{conf.lower()} connection - not explicitly stated in source")
|
||||
|
||||
# 2. Cross file-type bonus - code↔paper or code↔image is non-obvious
|
||||
cat_u = _file_category(u_source)
|
||||
cat_v = _file_category(v_source)
|
||||
if cat_u != cat_v:
|
||||
score += 2
|
||||
reasons.append(f"crosses file types ({cat_u} ↔ {cat_v})")
|
||||
|
||||
# 3. Cross-repo bonus - different top-level directory
|
||||
if _top_level_dir(u_source) != _top_level_dir(v_source):
|
||||
score += 2
|
||||
reasons.append("connects across different repos/directories")
|
||||
|
||||
# 4. Cross-community bonus - Leiden says these are structurally distant
|
||||
cid_u = node_community.get(u)
|
||||
cid_v = node_community.get(v)
|
||||
if cid_u is not None and cid_v is not None and cid_u != cid_v:
|
||||
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)
|
||||
if min(deg_u, deg_v) <= 2 and max(deg_u, deg_v) >= 5:
|
||||
score += 1
|
||||
peripheral = G.nodes[u].get("label", u) if deg_u <= 2 else G.nodes[v].get("label", v)
|
||||
hub = G.nodes[v].get("label", v) if deg_u <= 2 else G.nodes[u].get("label", u)
|
||||
reasons.append(f"peripheral node `{peripheral}` unexpectedly reaches hub `{hub}`")
|
||||
|
||||
return score, reasons
|
||||
|
||||
|
||||
def _cross_file_surprises(G: nx.Graph, communities: dict[int, list[str]], top_n: int) -> list[dict]:
|
||||
"""
|
||||
Cross-file edges between real code/doc entities.
|
||||
Excludes concept nodes, file hub nodes, and plain import edges.
|
||||
Sorted AMBIGUOUS → INFERRED → EXTRACTED.
|
||||
Cross-file edges between real code/doc entities, ranked by a composite
|
||||
surprise score rather than confidence alone.
|
||||
|
||||
Surprise score accounts for:
|
||||
- Confidence (AMBIGUOUS > INFERRED > EXTRACTED)
|
||||
- Cross file-type (code↔paper is more surprising than code↔code)
|
||||
- Cross-repo (different top-level directory)
|
||||
- Cross-community (Leiden says structurally distant)
|
||||
- Peripheral→hub (low-degree node reaching a god node)
|
||||
|
||||
Each result includes a 'why' field explaining what makes it non-obvious.
|
||||
"""
|
||||
surprises = []
|
||||
order = {"AMBIGUOUS": 0, "INFERRED": 1, "EXTRACTED": 2}
|
||||
node_community = _node_community_map(communities)
|
||||
candidates = []
|
||||
|
||||
for u, v, data in G.edges(data=True):
|
||||
# Skip structural scaffolding — not insights
|
||||
relation = data.get("relation", "")
|
||||
if relation in ("imports", "imports_from", "contains", "method"):
|
||||
continue
|
||||
# Skip if either endpoint is a concept or file-level node
|
||||
if _is_concept_node(G, u) or _is_concept_node(G, v):
|
||||
continue
|
||||
if _is_file_node(G, u) or _is_file_node(G, v):
|
||||
@@ -123,28 +212,32 @@ def _cross_file_surprises(G: nx.Graph, communities: dict[int, list[str]], top_n:
|
||||
u_source = G.nodes[u].get("source_file", "")
|
||||
v_source = G.nodes[v].get("source_file", "")
|
||||
|
||||
if u_source and v_source and u_source != v_source:
|
||||
# Respect original edge direction stored in _src/_tgt (if present),
|
||||
# otherwise fall back to u/v which may be in arbitrary order.
|
||||
src_id = data.get("_src", u)
|
||||
tgt_id = data.get("_tgt", v)
|
||||
surprises.append({
|
||||
"source": G.nodes[src_id].get("label", src_id),
|
||||
"target": G.nodes[tgt_id].get("label", tgt_id),
|
||||
"source_files": [
|
||||
G.nodes[src_id].get("source_file", ""),
|
||||
G.nodes[tgt_id].get("source_file", ""),
|
||||
],
|
||||
"confidence": data.get("confidence", "EXTRACTED"),
|
||||
"relation": relation,
|
||||
})
|
||||
if not u_source or not v_source or u_source == v_source:
|
||||
continue
|
||||
|
||||
surprises.sort(key=lambda x: order.get(x["confidence"], 3))
|
||||
if surprises:
|
||||
return surprises[:top_n]
|
||||
score, reasons = _surprise_score(G, u, v, data, node_community, u_source, v_source)
|
||||
src_id = data.get("_src", u)
|
||||
tgt_id = data.get("_tgt", v)
|
||||
candidates.append({
|
||||
"_score": score,
|
||||
"source": G.nodes[src_id].get("label", src_id),
|
||||
"target": G.nodes[tgt_id].get("label", tgt_id),
|
||||
"source_files": [
|
||||
G.nodes[src_id].get("source_file", ""),
|
||||
G.nodes[tgt_id].get("source_file", ""),
|
||||
],
|
||||
"confidence": data.get("confidence", "EXTRACTED"),
|
||||
"relation": relation,
|
||||
"why": "; ".join(reasons) if reasons else "cross-file semantic connection",
|
||||
})
|
||||
|
||||
candidates.sort(key=lambda x: x["_score"], reverse=True)
|
||||
for c in candidates:
|
||||
c.pop("_score")
|
||||
|
||||
if candidates:
|
||||
return candidates[:top_n]
|
||||
|
||||
# Fallback: no semantic cross-file edges found (pure AST corpus).
|
||||
# Surface cross-community bridge edges as structural surprises instead.
|
||||
return _cross_community_surprises(G, communities, top_n)
|
||||
|
||||
|
||||
@@ -155,13 +248,13 @@ def _cross_community_surprises(
|
||||
) -> list[dict]:
|
||||
"""
|
||||
For single-source corpora: find edges that bridge different communities.
|
||||
These are surprising because Leiden grouped everything else tightly —
|
||||
These are surprising because Leiden grouped everything else tightly -
|
||||
these edges cut across the natural structure.
|
||||
|
||||
Falls back to high-betweenness edges if no community info is provided.
|
||||
"""
|
||||
if not communities:
|
||||
# No community info — use edge betweenness centrality
|
||||
# No community info - use edge betweenness centrality
|
||||
if G.number_of_edges() == 0:
|
||||
return []
|
||||
betweenness = nx.edge_betweenness_centrality(G)
|
||||
@@ -183,7 +276,7 @@ def _cross_community_surprises(
|
||||
return result
|
||||
|
||||
# Build node → community map
|
||||
node_community = {n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
node_community = _node_community_map(communities)
|
||||
|
||||
surprises = []
|
||||
for u, v, data in G.edges(data=True):
|
||||
@@ -197,7 +290,7 @@ def _cross_community_surprises(
|
||||
relation = data.get("relation", "")
|
||||
if relation in ("imports", "imports_from", "contains", "method"):
|
||||
continue
|
||||
# This edge crosses community boundaries — interesting
|
||||
# This edge crosses community boundaries - interesting
|
||||
confidence = data.get("confidence", "EXTRACTED")
|
||||
src_id = data.get("_src", u)
|
||||
tgt_id = data.get("_tgt", v)
|
||||
@@ -218,7 +311,7 @@ def _cross_community_surprises(
|
||||
order = {"AMBIGUOUS": 0, "INFERRED": 1, "EXTRACTED": 2}
|
||||
surprises.sort(key=lambda x: order.get(x["confidence"], 3))
|
||||
|
||||
# Deduplicate by community pair — one representative edge per (A→B) boundary.
|
||||
# Deduplicate by community pair - one representative edge per (A→B) boundary.
|
||||
# Without this, a single high-betweenness god node dominates all results.
|
||||
seen_pairs: set[tuple] = set()
|
||||
deduped = []
|
||||
@@ -242,7 +335,7 @@ def suggest_questions(
|
||||
Each question has a 'type', 'question', and 'why' field.
|
||||
"""
|
||||
questions = []
|
||||
node_community = {n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
node_community = _node_community_map(communities)
|
||||
|
||||
# 1. AMBIGUOUS edges → unresolved relationship questions
|
||||
for u, v, data in G.edges(data=True):
|
||||
@@ -253,7 +346,7 @@ def suggest_questions(
|
||||
questions.append({
|
||||
"type": "ambiguous_edge",
|
||||
"question": f"What is the exact relationship between `{ul}` and `{vl}`?",
|
||||
"why": f"Edge tagged AMBIGUOUS (relation: {relation}) — confidence is low.",
|
||||
"why": f"Edge tagged AMBIGUOUS (relation: {relation}) - confidence is low.",
|
||||
})
|
||||
|
||||
# 2. Bridge nodes (high betweenness) → cross-cutting concern questions
|
||||
@@ -277,7 +370,7 @@ def suggest_questions(
|
||||
questions.append({
|
||||
"type": "bridge_node",
|
||||
"question": f"Why does `{label}` connect `{comm_label}` to {', '.join(f'`{l}`' for l in other_labels)}?",
|
||||
"why": f"High betweenness centrality ({score:.3f}) — this node is a cross-community bridge.",
|
||||
"why": f"High betweenness centrality ({score:.3f}) - this node is a cross-community bridge.",
|
||||
})
|
||||
|
||||
# 3. God nodes with many INFERRED edges → verification questions
|
||||
@@ -304,7 +397,7 @@ def suggest_questions(
|
||||
questions.append({
|
||||
"type": "verify_inferred",
|
||||
"question": f"Are the {len(inferred)} inferred relationships involving `{label}` (e.g. with `{others[0]}` and `{others[1]}`) actually correct?",
|
||||
"why": f"`{label}` has {len(inferred)} INFERRED edges — model-reasoned connections that need verification.",
|
||||
"why": f"`{label}` has {len(inferred)} INFERRED edges - model-reasoned connections that need verification.",
|
||||
})
|
||||
|
||||
# 4. Isolated or weakly-connected nodes → exploration questions
|
||||
@@ -317,7 +410,7 @@ def suggest_questions(
|
||||
questions.append({
|
||||
"type": "isolated_nodes",
|
||||
"question": f"What connects {', '.join(f'`{l}`' for l in labels)} to the rest of the system?",
|
||||
"why": f"{len(isolated)} weakly-connected nodes found — possible documentation gaps or missing edges.",
|
||||
"why": f"{len(isolated)} weakly-connected nodes found - possible documentation gaps or missing edges.",
|
||||
})
|
||||
|
||||
# 5. Low-cohesion communities → structural questions
|
||||
@@ -329,7 +422,7 @@ def suggest_questions(
|
||||
questions.append({
|
||||
"type": "low_cohesion",
|
||||
"question": f"Should `{label}` be split into smaller, more focused modules?",
|
||||
"why": f"Cohesion score {score} — nodes in this community are weakly interconnected.",
|
||||
"why": f"Cohesion score {score} - nodes in this community are weakly interconnected.",
|
||||
})
|
||||
|
||||
if not questions:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Token-reduction benchmark — measures how much context graphify saves vs naive full-corpus approach."""
|
||||
"""Token-reduction benchmark - measures how much context graphify saves vs naive full-corpus approach."""
|
||||
from __future__ import annotations
|
||||
import json
|
||||
from pathlib import Path
|
||||
@@ -62,7 +62,7 @@ _SAMPLE_QUESTIONS = [
|
||||
|
||||
|
||||
def run_benchmark(
|
||||
graph_path: str = ".graphify/graph.json",
|
||||
graph_path: str = "graphify-out/graph.json",
|
||||
corpus_words: int | None = None,
|
||||
questions: list[str] | None = None,
|
||||
) -> dict:
|
||||
|
||||
+21
-10
@@ -7,25 +7,36 @@ from .validate import validate_extraction
|
||||
|
||||
def build_from_json(extraction: dict) -> nx.Graph:
|
||||
errors = validate_extraction(extraction)
|
||||
if errors:
|
||||
print(f"[graphify] Extraction warning ({len(errors)} issues): {errors[0]}", file=sys.stderr)
|
||||
# Dangling edges (stdlib/external imports) are expected - only warn about real schema errors.
|
||||
real_errors = [e for e in errors if "does not match any node id" not in e]
|
||||
if real_errors:
|
||||
print(f"[graphify] Extraction warning ({len(real_errors)} issues): {real_errors[0]}", file=sys.stderr)
|
||||
G = nx.Graph()
|
||||
for node in extraction.get("nodes", []):
|
||||
G.add_node(node["id"], **{k: v for k, v in node.items() if k != "id"})
|
||||
node_set = set(G.nodes())
|
||||
for edge in extraction.get("edges", []):
|
||||
src, tgt = edge["source"], edge["target"]
|
||||
if src not in node_set or tgt not in node_set:
|
||||
continue # skip edges to external/stdlib nodes - expected, not an error
|
||||
attrs = {k: v for k, v in edge.items() if k not in ("source", "target")}
|
||||
# Preserve original edge direction — undirected graphs lose it otherwise,
|
||||
# Preserve original edge direction - undirected graphs lose it otherwise,
|
||||
# causing display functions to show edges backwards.
|
||||
attrs["_src"] = edge["source"]
|
||||
attrs["_tgt"] = edge["target"]
|
||||
G.add_edge(edge["source"], edge["target"], **attrs)
|
||||
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."""
|
||||
G = nx.Graph()
|
||||
combined: dict = {"nodes": [], "edges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
for ext in extractions:
|
||||
sub = build_from_json(ext)
|
||||
G.update(sub)
|
||||
return G
|
||||
combined["nodes"].extend(ext.get("nodes", []))
|
||||
combined["edges"].extend(ext.get("edges", []))
|
||||
combined["input_tokens"] += ext.get("input_tokens", 0)
|
||||
combined["output_tokens"] += ext.get("output_tokens", 0)
|
||||
return build_from_json(combined)
|
||||
+17
-11
@@ -1,9 +1,8 @@
|
||||
# per-file extraction cache — skip unchanged files on re-run
|
||||
# per-file extraction cache - skip unchanged files on re-run
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -13,8 +12,8 @@ def file_hash(path: Path) -> str:
|
||||
|
||||
|
||||
def cache_dir(root: Path = Path(".")) -> Path:
|
||||
"""Returns .graphify/cache/ — creates it if needed."""
|
||||
d = Path(root) / ".graphify" / "cache"
|
||||
"""Returns graphify-out/cache/ - creates it if needed."""
|
||||
d = Path(root) / "graphify-out" / "cache"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
@@ -23,7 +22,7 @@ def load_cached(path: Path, root: Path = Path(".")) -> dict | None:
|
||||
"""Return cached extraction for this file if hash matches, else None.
|
||||
|
||||
Cache key: SHA256 of file contents.
|
||||
Cache value: stored as .graphify/cache/{hash}.json
|
||||
Cache value: stored as graphify-out/cache/{hash}.json
|
||||
Returns None if no cache entry or file has changed.
|
||||
"""
|
||||
try:
|
||||
@@ -42,7 +41,7 @@ def load_cached(path: Path, root: Path = Path(".")) -> dict | None:
|
||||
def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
|
||||
"""Save extraction result for this file.
|
||||
|
||||
Stores as .graphify/cache/{hash}.json where hash = SHA256 of current file contents.
|
||||
Stores as graphify-out/cache/{hash}.json where hash = SHA256 of current file contents.
|
||||
result should be a dict with 'nodes' and 'edges' lists.
|
||||
"""
|
||||
h = file_hash(path)
|
||||
@@ -57,7 +56,7 @@ def cached_files(root: Path = Path(".")) -> set[str]:
|
||||
|
||||
|
||||
def clear_cache(root: Path = Path(".")) -> None:
|
||||
"""Delete all .graphify/cache/*.json files."""
|
||||
"""Delete all graphify-out/cache/*.json files."""
|
||||
d = cache_dir(root)
|
||||
for f in d.glob("*.json"):
|
||||
f.unlink()
|
||||
@@ -66,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:
|
||||
@@ -81,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.
|
||||
@@ -99,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:
|
||||
@@ -108,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():
|
||||
|
||||
+22
-9
@@ -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,16 +53,14 @@ 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
|
||||
# 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]
|
||||
connected = G.subgraph(connected_nodes)
|
||||
|
||||
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)
|
||||
|
||||
@@ -73,16 +88,14 @@ def _split_community(G: nx.Graph, nodes: list[str]) -> list[list[str]]:
|
||||
"""Run a second Leiden pass on a community subgraph to split it further."""
|
||||
subgraph = G.subgraph(nodes)
|
||||
if subgraph.number_of_edges() == 0:
|
||||
# No edges — split into individual nodes
|
||||
# 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:
|
||||
|
||||
+13
-13
@@ -1,6 +1,7 @@
|
||||
# file discovery, type classification, and corpus health checks
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
@@ -13,18 +14,18 @@ class FileType(str, Enum):
|
||||
IMAGE = "image"
|
||||
|
||||
|
||||
_MANIFEST_PATH = ".graphify/manifest.json"
|
||||
_MANIFEST_PATH = "graphify-out/manifest.json"
|
||||
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.tsx', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php'}
|
||||
DOC_EXTENSIONS = {'.md', '.txt', '.rst'}
|
||||
PAPER_EXTENSIONS = {'.pdf'}
|
||||
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
|
||||
|
||||
CORPUS_WARN_THRESHOLD = 50_000 # words — below this, warn "you may not need a graph"
|
||||
CORPUS_UPPER_THRESHOLD = 500_000 # words — above this, warn about token cost
|
||||
FILE_COUNT_UPPER = 200 # files — above this, warn about token cost
|
||||
CORPUS_WARN_THRESHOLD = 50_000 # words - below this, warn "you may not need a graph"
|
||||
CORPUS_UPPER_THRESHOLD = 500_000 # words - above this, warn about token cost
|
||||
FILE_COUNT_UPPER = 200 # files - above this, warn about token cost
|
||||
|
||||
# Files that may contain secrets — skip silently
|
||||
# Files that may contain secrets - skip silently
|
||||
_SENSITIVE_PATTERNS = [
|
||||
re.compile(r'(^|[\\/])\.(env|envrc)(\.|$)', re.IGNORECASE),
|
||||
re.compile(r'\.(pem|key|p12|pfx|cert|crt|der|p8)$', re.IGNORECASE),
|
||||
@@ -111,7 +112,7 @@ def count_words(path: Path) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
# Directory names to always skip — venvs, caches, build artifacts, deps
|
||||
# Directory names to always skip - venvs, caches, build artifacts, deps
|
||||
_SKIP_DIRS = {
|
||||
"venv", ".venv", "env", ".env",
|
||||
"node_modules", "__pycache__", ".git",
|
||||
@@ -144,8 +145,8 @@ def detect(root: Path) -> dict:
|
||||
|
||||
skipped_sensitive: list[str] = []
|
||||
|
||||
# Always include .graphify/memory/ — query results filed back into the graph
|
||||
memory_dir = root / ".graphify" / "memory"
|
||||
# Always include graphify-out/memory/ - query results filed back into the graph
|
||||
memory_dir = root / "graphify-out" / "memory"
|
||||
scan_paths = [root]
|
||||
if memory_dir.exists():
|
||||
scan_paths.append(memory_dir)
|
||||
@@ -155,7 +156,6 @@ def detect(root: Path) -> dict:
|
||||
|
||||
for scan_root in scan_paths:
|
||||
in_memory_tree = memory_dir.exists() and str(scan_root).startswith(str(memory_dir))
|
||||
import os
|
||||
for dirpath, dirnames, filenames in os.walk(scan_root, followlinks=False):
|
||||
dp = Path(dirpath)
|
||||
if not in_memory_tree:
|
||||
@@ -189,11 +189,11 @@ def detect(root: Path) -> dict:
|
||||
total_files = sum(len(v) for v in files.values())
|
||||
needs_graph = total_words >= CORPUS_WARN_THRESHOLD
|
||||
|
||||
# Determine warning — lower bound, upper bound, or sensitive files skipped
|
||||
# Determine warning - lower bound, upper bound, or sensitive files skipped
|
||||
warning: str | None = None
|
||||
if not needs_graph:
|
||||
warning = (
|
||||
f"Corpus is ~{total_words:,} words — fits in a single context window. "
|
||||
f"Corpus is ~{total_words:,} words - fits in a single context window. "
|
||||
f"You may not need a graph."
|
||||
)
|
||||
elif total_words >= CORPUS_UPPER_THRESHOLD or total_files >= FILE_COUNT_UPPER:
|
||||
@@ -229,7 +229,7 @@ def save_manifest(files: dict[str, list[str]], manifest_path: str = _MANIFEST_PA
|
||||
try:
|
||||
manifest[f] = Path(f).stat().st_mtime
|
||||
except OSError:
|
||||
pass # file deleted between detect() and manifest write — skip it
|
||||
pass # file deleted between detect() and manifest write - skip it
|
||||
Path(manifest_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(manifest_path).write_text(json.dumps(manifest, indent=2))
|
||||
|
||||
@@ -244,7 +244,7 @@ def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
|
||||
manifest = load_manifest(manifest_path)
|
||||
|
||||
if not manifest:
|
||||
# No previous run — treat everything as new
|
||||
# No previous run - treat everything as new
|
||||
full["incremental"] = True
|
||||
full["new_files"] = full["files"]
|
||||
full["unchanged_files"] = {k: [] for k in full["files"]}
|
||||
|
||||
+374
-76
@@ -1,4 +1,4 @@
|
||||
# write graph to HTML, JSON, SVG, Obsidian vault, and Neo4j Cypher
|
||||
# write graph to HTML, JSON, SVG, GraphML, Obsidian vault, and Neo4j Cypher
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import math
|
||||
@@ -17,17 +17,266 @@ COMMUNITY_COLORS = [
|
||||
MAX_NODES_FOR_VIZ = 5_000
|
||||
|
||||
|
||||
def _node_community_map(communities: dict[int, list[str]]) -> dict[str, int]:
|
||||
"""Invert communities dict: node_id -> community_id."""
|
||||
return {n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
|
||||
|
||||
def _html_styles() -> str:
|
||||
return """<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { background: #0f0f1a; color: #e0e0e0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; display: flex; height: 100vh; overflow: hidden; }
|
||||
#graph { flex: 1; }
|
||||
#sidebar { width: 280px; background: #1a1a2e; border-left: 1px solid #2a2a4e; display: flex; flex-direction: column; overflow: hidden; }
|
||||
#search-wrap { padding: 12px; border-bottom: 1px solid #2a2a4e; }
|
||||
#search { width: 100%; background: #0f0f1a; border: 1px solid #3a3a5e; color: #e0e0e0; padding: 7px 10px; border-radius: 6px; font-size: 13px; outline: none; }
|
||||
#search:focus { border-color: #4E79A7; }
|
||||
#search-results { max-height: 140px; overflow-y: auto; padding: 4px 12px; border-bottom: 1px solid #2a2a4e; display: none; }
|
||||
.search-item { padding: 4px 6px; cursor: pointer; border-radius: 4px; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.search-item:hover { background: #2a2a4e; }
|
||||
#info-panel { padding: 14px; border-bottom: 1px solid #2a2a4e; min-height: 140px; }
|
||||
#info-panel h3 { font-size: 13px; color: #aaa; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.05em; }
|
||||
#info-content { font-size: 13px; color: #ccc; line-height: 1.6; }
|
||||
#info-content .field { margin-bottom: 5px; }
|
||||
#info-content .field b { color: #e0e0e0; }
|
||||
#info-content .empty { color: #555; font-style: italic; }
|
||||
.neighbor-link { display: block; padding: 2px 6px; margin: 2px 0; border-radius: 3px; cursor: pointer; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border-left: 3px solid #333; }
|
||||
.neighbor-link:hover { background: #2a2a4e; }
|
||||
#neighbors-list { max-height: 160px; overflow-y: auto; margin-top: 4px; }
|
||||
#legend-wrap { flex: 1; overflow-y: auto; padding: 12px; }
|
||||
#legend-wrap h3 { font-size: 13px; color: #aaa; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.05em; }
|
||||
.legend-item { display: flex; align-items: center; gap: 8px; padding: 4px 0; cursor: pointer; border-radius: 4px; font-size: 12px; }
|
||||
.legend-item:hover { background: #2a2a4e; padding-left: 4px; }
|
||||
.legend-item.dimmed { opacity: 0.35; }
|
||||
.legend-dot { width: 12px; height: 12px; border-radius: 50%; flex-shrink: 0; }
|
||||
.legend-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.legend-count { color: #666; font-size: 11px; }
|
||||
#stats { padding: 10px 14px; border-top: 1px solid #2a2a4e; font-size: 11px; color: #555; }
|
||||
</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};
|
||||
const RAW_EDGES = {edges_json};
|
||||
const LEGEND = {legend_json};
|
||||
|
||||
// Build vis datasets
|
||||
const nodesDS = new vis.DataSet(RAW_NODES.map(n => ({{
|
||||
id: n.id, label: n.label, color: n.color, size: n.size,
|
||||
font: n.font, title: n.title,
|
||||
_community: n.community, _community_name: n.community_name,
|
||||
_source_file: n.source_file, _file_type: n.file_type, _degree: n.degree,
|
||||
}})));
|
||||
|
||||
const edgesDS = new vis.DataSet(RAW_EDGES.map((e, i) => ({{
|
||||
id: i, from: e.from, to: e.to,
|
||||
label: '',
|
||||
title: e.title,
|
||||
dashes: e.dashes,
|
||||
width: e.width,
|
||||
color: e.color,
|
||||
arrows: {{ to: {{ enabled: true, scaleFactor: 0.5 }} }},
|
||||
}})));
|
||||
|
||||
const container = document.getElementById('graph');
|
||||
const network = new vis.Network(container, {{ nodes: nodesDS, edges: edgesDS }}, {{
|
||||
physics: {{
|
||||
enabled: true,
|
||||
solver: 'forceAtlas2Based',
|
||||
forceAtlas2Based: {{
|
||||
gravitationalConstant: -60,
|
||||
centralGravity: 0.005,
|
||||
springLength: 120,
|
||||
springConstant: 0.08,
|
||||
damping: 0.4,
|
||||
avoidOverlap: 0.8,
|
||||
}},
|
||||
stabilization: {{ iterations: 200, fit: true }},
|
||||
}},
|
||||
interaction: {{
|
||||
hover: true,
|
||||
tooltipDelay: 100,
|
||||
hideEdgesOnDrag: true,
|
||||
navigationButtons: false,
|
||||
keyboard: false,
|
||||
}},
|
||||
nodes: {{ shape: 'dot', borderWidth: 1.5 }},
|
||||
edges: {{ smooth: {{ type: 'continuous', roundness: 0.2 }}, selectionWidth: 3 }},
|
||||
}});
|
||||
|
||||
network.once('stabilizationIterationsDone', () => {{
|
||||
network.setOptions({{ physics: {{ enabled: false }} }});
|
||||
}});
|
||||
|
||||
function showInfo(nodeId) {{
|
||||
const n = nodesDS.get(nodeId);
|
||||
if (!n) return;
|
||||
const neighborIds = network.getConnectedNodes(nodeId);
|
||||
const neighborItems = neighborIds.map(nid => {{
|
||||
const nb = nodesDS.get(nid);
|
||||
const color = nb ? nb.color.background : '#555';
|
||||
return `<span class="neighbor-link" style="border-left-color:${{color}}" onclick="focusNode('${{nid}}')">${{nb ? nb.label : nid}}</span>`;
|
||||
}}).join('');
|
||||
document.getElementById('info-content').innerHTML = `
|
||||
<div class="field"><b>${{n.label}}</b></div>
|
||||
<div class="field">Type: ${{n._file_type || 'unknown'}}</div>
|
||||
<div class="field">Community: ${{n._community_name}}</div>
|
||||
<div class="field">Source: ${{n._source_file || '-'}}</div>
|
||||
<div class="field">Degree: ${{n._degree}}</div>
|
||||
${{neighborIds.length ? `<div class="field" style="margin-top:8px;color:#aaa;font-size:11px">Neighbors (${{neighborIds.length}})</div><div id="neighbors-list">${{neighborItems}}</div>` : ''}}
|
||||
`;
|
||||
}}
|
||||
|
||||
function focusNode(nodeId) {{
|
||||
network.focus(nodeId, {{ scale: 1.4, animation: true }});
|
||||
network.selectNodes([nodeId]);
|
||||
showInfo(nodeId);
|
||||
}}
|
||||
|
||||
network.on('click', params => {{
|
||||
if (params.nodes.length > 0) showInfo(params.nodes[0]);
|
||||
else document.getElementById('info-content').innerHTML = '<span class="empty">Click a node to inspect it</span>';
|
||||
}});
|
||||
|
||||
const searchInput = document.getElementById('search');
|
||||
const searchResults = document.getElementById('search-results');
|
||||
searchInput.addEventListener('input', () => {{
|
||||
const q = searchInput.value.toLowerCase().trim();
|
||||
searchResults.innerHTML = '';
|
||||
if (!q) {{ searchResults.style.display = 'none'; return; }}
|
||||
const matches = RAW_NODES.filter(n => n.label.toLowerCase().includes(q)).slice(0, 20);
|
||||
if (!matches.length) {{ searchResults.style.display = 'none'; return; }}
|
||||
searchResults.style.display = 'block';
|
||||
matches.forEach(n => {{
|
||||
const el = document.createElement('div');
|
||||
el.className = 'search-item';
|
||||
el.textContent = n.label;
|
||||
el.style.borderLeft = `3px solid ${{n.color.background}}`;
|
||||
el.style.paddingLeft = '8px';
|
||||
el.onclick = () => {{
|
||||
network.focus(n.id, {{ scale: 1.5, animation: true }});
|
||||
network.selectNodes([n.id]);
|
||||
showInfo(n.id);
|
||||
searchResults.style.display = 'none';
|
||||
searchInput.value = '';
|
||||
}};
|
||||
searchResults.appendChild(el);
|
||||
}});
|
||||
}});
|
||||
document.addEventListener('click', e => {{
|
||||
if (!searchResults.contains(e.target) && e.target !== searchInput)
|
||||
searchResults.style.display = 'none';
|
||||
}});
|
||||
|
||||
const hiddenCommunities = new Set();
|
||||
const legendEl = document.getElementById('legend');
|
||||
LEGEND.forEach(c => {{
|
||||
const item = document.createElement('div');
|
||||
item.className = 'legend-item';
|
||||
item.innerHTML = `<div class="legend-dot" style="background:${{c.color}}"></div>
|
||||
<span class="legend-label">${{c.label}}</span>
|
||||
<span class="legend-count">${{c.count}}</span>`;
|
||||
item.onclick = () => {{
|
||||
if (hiddenCommunities.has(c.cid)) {{
|
||||
hiddenCommunities.delete(c.cid);
|
||||
item.classList.remove('dimmed');
|
||||
}} else {{
|
||||
hiddenCommunities.add(c.cid);
|
||||
item.classList.add('dimmed');
|
||||
}}
|
||||
const updates = RAW_NODES
|
||||
.filter(n => n.community === c.cid)
|
||||
.map(n => ({{ id: n.id, hidden: hiddenCommunities.has(c.cid) }}));
|
||||
nodesDS.update(updates);
|
||||
}};
|
||||
legendEl.appendChild(item);
|
||||
}});
|
||||
</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 = {n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
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)
|
||||
|
||||
|
||||
def to_cypher(G: nx.Graph, output_path: str) -> None:
|
||||
lines = ["// Neo4j Cypher import — generated by /graphify", ""]
|
||||
lines = ["// Neo4j Cypher import - generated by /graphify", ""]
|
||||
for node_id, data in G.nodes(data=True):
|
||||
label = data.get("label", node_id).replace("'", "\\'")
|
||||
ftype = data.get("file_type", "unknown").capitalize()
|
||||
@@ -50,76 +299,111 @@ def to_html(
|
||||
output_path: str,
|
||||
community_labels: dict[int, str] | None = None,
|
||||
) -> None:
|
||||
"""Generate an interactive pyvis HTML visualization of the graph.
|
||||
"""Generate an interactive vis.js HTML visualization of the graph.
|
||||
|
||||
Merged from visualizer.py. Raises ValueError if graph exceeds MAX_NODES_FOR_VIZ.
|
||||
Features: node size by degree, click-to-inspect panel, search box,
|
||||
community filter, physics clustering by community, confidence-styled edges.
|
||||
Raises ValueError if graph exceeds MAX_NODES_FOR_VIZ.
|
||||
"""
|
||||
from pyvis.network import Network
|
||||
|
||||
if G.number_of_nodes() > MAX_NODES_FOR_VIZ:
|
||||
raise ValueError(
|
||||
f"Graph has {G.number_of_nodes()} nodes — too large for pyvis. "
|
||||
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz. "
|
||||
f"Use --no-viz or reduce input size."
|
||||
)
|
||||
|
||||
node_community = {n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
|
||||
net = Network(height="800px", width="100%", bgcolor="#1a1a2e", font_color="white")
|
||||
net.barnes_hut()
|
||||
node_community = _node_community_map(communities)
|
||||
degree = dict(G.degree())
|
||||
max_deg = max(degree.values()) if degree else 1
|
||||
|
||||
# Build nodes list for vis.js
|
||||
vis_nodes = []
|
||||
for node_id, data in G.nodes(data=True):
|
||||
cid = node_community.get(node_id, 0)
|
||||
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
|
||||
net.add_node(
|
||||
node_id,
|
||||
label=sanitize_label(data.get("label", node_id)),
|
||||
color=color,
|
||||
title=sanitize_label(
|
||||
f"Source: {data.get('source_file', 'unknown')}\n"
|
||||
f"Type: {data.get('file_type', 'unknown')}\n"
|
||||
f"Community: {community_labels.get(cid, str(cid)) if community_labels else cid}"
|
||||
),
|
||||
)
|
||||
label = sanitize_label(data.get("label", node_id))
|
||||
deg = degree.get(node_id, 1)
|
||||
size = 10 + 30 * (deg / max_deg)
|
||||
# Only show label for high-degree nodes by default; others show on hover
|
||||
font_size = 12 if deg >= max_deg * 0.15 else 0
|
||||
vis_nodes.append({
|
||||
"id": node_id,
|
||||
"label": label,
|
||||
"color": {"background": color, "border": color, "highlight": {"background": "#ffffff", "border": color}},
|
||||
"size": round(size, 1),
|
||||
"font": {"size": font_size, "color": "#ffffff"},
|
||||
"title": f"{label}",
|
||||
"community": cid,
|
||||
"community_name": (community_labels or {}).get(cid, f"Community {cid}"),
|
||||
"source_file": sanitize_label(data.get("source_file", "")),
|
||||
"file_type": data.get("file_type", ""),
|
||||
"degree": deg,
|
||||
})
|
||||
|
||||
# Build edges list
|
||||
vis_edges = []
|
||||
for u, v, data in G.edges(data=True):
|
||||
confidence = data.get("confidence", "EXTRACTED")
|
||||
width = {"EXTRACTED": 2, "INFERRED": 1, "AMBIGUOUS": 1}.get(confidence, 1)
|
||||
net.add_edge(
|
||||
u, v,
|
||||
title=f"{data.get('relation', '')} [{confidence}]",
|
||||
width=width,
|
||||
dashes=(confidence != "EXTRACTED"),
|
||||
)
|
||||
relation = data.get("relation", "")
|
||||
vis_edges.append({
|
||||
"from": u,
|
||||
"to": v,
|
||||
"label": relation,
|
||||
"title": f"{relation} [{confidence}]",
|
||||
"dashes": confidence != "EXTRACTED",
|
||||
"width": 2 if confidence == "EXTRACTED" else 1,
|
||||
"color": {"opacity": 0.7 if confidence == "EXTRACTED" else 0.35},
|
||||
"confidence": confidence,
|
||||
})
|
||||
|
||||
net.save_graph(output_path)
|
||||
# Build community legend data
|
||||
legend_data = []
|
||||
for cid in sorted((community_labels or {}).keys()):
|
||||
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
|
||||
lbl = (community_labels or {}).get(cid, f"Community {cid}")
|
||||
n = len(communities.get(cid, []))
|
||||
legend_data.append({"cid": cid, "color": color, "label": lbl, "count": n})
|
||||
|
||||
# Inject community legend into saved HTML
|
||||
if community_labels:
|
||||
legend_items = ""
|
||||
for cid in sorted(community_labels.keys()):
|
||||
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
|
||||
label = community_labels[cid]
|
||||
n_nodes = len(communities.get(cid, []))
|
||||
legend_items += (
|
||||
f'<div style="margin:4px 0">'
|
||||
f'<span style="color:{color};font-size:18px">■</span> '
|
||||
f'<span style="font-size:13px">{label} ({n_nodes})</span>'
|
||||
f'</div>'
|
||||
)
|
||||
legend_html = (
|
||||
'<div style="position:fixed;top:10px;right:10px;background:#2a2a4e;'
|
||||
'padding:12px 16px;border-radius:8px;font-family:sans-serif;color:white;'
|
||||
'z-index:9999;min-width:180px;">'
|
||||
'<b style="font-size:14px">Communities</b><br>'
|
||||
+ legend_items +
|
||||
'</div>'
|
||||
)
|
||||
content = Path(output_path).read_text()
|
||||
content = content.replace("</body>", legend_html + "\n</body>")
|
||||
Path(output_path).write_text(content)
|
||||
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"
|
||||
|
||||
html = f"""<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>graphify - {title}</title>
|
||||
<script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>
|
||||
{_html_styles()}
|
||||
</head>
|
||||
<body>
|
||||
<div id="graph"></div>
|
||||
<div id="sidebar">
|
||||
<div id="search-wrap">
|
||||
<input id="search" type="text" placeholder="Search nodes..." autocomplete="off">
|
||||
<div id="search-results"></div>
|
||||
</div>
|
||||
<div id="info-panel">
|
||||
<h3>Node Info</h3>
|
||||
<div id="info-content"><span class="empty">Click a node to inspect it</span></div>
|
||||
</div>
|
||||
<div id="legend-wrap">
|
||||
<h3>Communities</h3>
|
||||
<div id="legend"></div>
|
||||
</div>
|
||||
<div id="stats">{stats}</div>
|
||||
</div>
|
||||
{_html_script(nodes_json, edges_json, legend_json)}
|
||||
{_hyperedge_script(hyperedges_json)}
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
Path(output_path).write_text(html, encoding="utf-8")
|
||||
|
||||
|
||||
# Keep backward-compatible alias — skill.md calls generate_html
|
||||
# Keep backward-compatible alias - skill.md calls generate_html
|
||||
generate_html = to_html
|
||||
|
||||
|
||||
@@ -130,7 +414,7 @@ def to_obsidian(
|
||||
community_labels: dict[int, str] | None = None,
|
||||
cohesion: dict[int, float] | None = None,
|
||||
) -> int:
|
||||
"""Export graph as an Obsidian vault — one .md file per node with [[wikilinks]],
|
||||
"""Export graph as an Obsidian vault - one .md file per node with [[wikilinks]],
|
||||
plus one _COMMUNITY_name.md overview note per community (sorted to top by underscore prefix).
|
||||
|
||||
Open the output directory as a vault in Obsidian to get an interactive
|
||||
@@ -141,7 +425,7 @@ def to_obsidian(
|
||||
out = Path(output_dir)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
node_community = {n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
node_community = _node_community_map(communities)
|
||||
|
||||
# Map node_id → safe filename so wikilinks stay consistent.
|
||||
# Deduplicate: if two nodes produce the same filename, append a numeric suffix.
|
||||
@@ -196,7 +480,7 @@ def to_obsidian(
|
||||
|
||||
lines: list[str] = []
|
||||
|
||||
# YAML frontmatter — readable in Obsidian's properties panel
|
||||
# YAML frontmatter - readable in Obsidian's properties panel
|
||||
lines += [
|
||||
"---",
|
||||
f'source_file: "{data.get("source_file", "")}"',
|
||||
@@ -220,7 +504,7 @@ def to_obsidian(
|
||||
neighbor_label = node_filename[neighbor]
|
||||
relation = edge_data.get("relation", "")
|
||||
confidence = edge_data.get("confidence", "EXTRACTED")
|
||||
lines.append(f"- [[{neighbor_label}]] — `{relation}` [{confidence}]")
|
||||
lines.append(f"- [[{neighbor_label}]] - `{relation}` [{confidence}]")
|
||||
lines.append("")
|
||||
|
||||
# Inline tags at bottom of note body (for Obsidian tag panel)
|
||||
@@ -283,7 +567,7 @@ def to_obsidian(
|
||||
else "moderately connected" if coh_value >= 0.4
|
||||
else "loosely connected"
|
||||
)
|
||||
lines.append(f"**Cohesion:** {coh_value:.2f} — {cohesion_desc}")
|
||||
lines.append(f"**Cohesion:** {coh_value:.2f} - {cohesion_desc}")
|
||||
lines.append(f"**Members:** {n_members} nodes")
|
||||
lines.append("")
|
||||
|
||||
@@ -296,9 +580,9 @@ def to_obsidian(
|
||||
source = data.get("source_file", "")
|
||||
entry = f"- [[{node_label}]]"
|
||||
if ftype:
|
||||
entry += f" — {ftype}"
|
||||
entry += f" - {ftype}"
|
||||
if source:
|
||||
entry += f" — {source}"
|
||||
entry += f" - {source}"
|
||||
lines.append(entry)
|
||||
lines.append("")
|
||||
|
||||
@@ -326,7 +610,7 @@ def to_obsidian(
|
||||
lines.append(f"- {edge_count} edge{'s' if edge_count != 1 else ''} to [[_COMMUNITY_{other_safe}]]")
|
||||
lines.append("")
|
||||
|
||||
# Top bridge nodes — highest degree nodes that connect to other communities
|
||||
# Top bridge nodes - highest degree nodes that connect to other communities
|
||||
bridge_nodes = [
|
||||
(node_id, G.degree(node_id), _community_reach(node_id))
|
||||
for node_id in members
|
||||
@@ -339,7 +623,7 @@ def to_obsidian(
|
||||
for node_id, degree, reach in top_bridges:
|
||||
node_label = node_filename[node_id]
|
||||
lines.append(
|
||||
f"- [[{node_label}]] — degree {degree}, connects to {reach} "
|
||||
f"- [[{node_label}]] - degree {degree}, connects to {reach} "
|
||||
f"{'community' if reach == 1 else 'communities'}"
|
||||
)
|
||||
|
||||
@@ -372,7 +656,7 @@ def to_canvas(
|
||||
community_labels: dict[int, str] | None = None,
|
||||
node_filenames: dict[str, str] | None = None,
|
||||
) -> None:
|
||||
"""Export graph as an Obsidian Canvas file — communities as groups, nodes as cards.
|
||||
"""Export graph as an Obsidian Canvas file - communities as groups, nodes as cards.
|
||||
|
||||
Generates a structured layout: communities arranged in a grid, nodes within
|
||||
each community arranged in rows. Edges shown between connected nodes.
|
||||
@@ -481,7 +765,7 @@ def to_canvas(
|
||||
"color": canvas_color,
|
||||
})
|
||||
|
||||
# Node cards inside the group — rows of 3
|
||||
# Node cards inside the group - rows of 3
|
||||
sorted_members = sorted(members, key=lambda n: G.nodes[n].get("label", n))
|
||||
for m_idx, node_id in enumerate(sorted_members):
|
||||
col = m_idx % 3
|
||||
@@ -499,7 +783,7 @@ def to_canvas(
|
||||
"height": 60,
|
||||
})
|
||||
|
||||
# Generate edges — only between nodes both in canvas, cap at 200 highest-weight
|
||||
# Generate edges - only between nodes both in canvas, cap at 200 highest-weight
|
||||
all_edges_weighted: list[tuple[float, str, str, str]] = []
|
||||
for u, v, edata in G.edges(data=True):
|
||||
if u in all_canvas_nodes and v in all_canvas_nodes:
|
||||
@@ -533,7 +817,7 @@ def push_to_neo4j(
|
||||
|
||||
Requires: pip install neo4j
|
||||
|
||||
Uses MERGE so re-running is safe — nodes and edges are upserted, not duplicated.
|
||||
Uses MERGE so re-running is safe - nodes and edges are upserted, not duplicated.
|
||||
Returns a dict with counts of nodes and edges pushed.
|
||||
"""
|
||||
try:
|
||||
@@ -543,10 +827,7 @@ def push_to_neo4j(
|
||||
"neo4j driver not installed. Run: pip install neo4j"
|
||||
) from e
|
||||
|
||||
node_community = (
|
||||
{n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
if communities else {}
|
||||
)
|
||||
node_community = _node_community_map(communities) if communities else {}
|
||||
|
||||
def _safe_rel(relation: str) -> str:
|
||||
return re.sub(r"[^A-Z0-9_]", "_", relation.upper().replace(" ", "_").replace("-", "_")) or "RELATED_TO"
|
||||
@@ -586,6 +867,23 @@ def push_to_neo4j(
|
||||
return {"nodes": nodes_pushed, "edges": edges_pushed}
|
||||
|
||||
|
||||
def to_graphml(
|
||||
G: nx.Graph,
|
||||
communities: dict[int, list[str]],
|
||||
output_path: str,
|
||||
) -> None:
|
||||
"""Export graph as GraphML - opens in Gephi, yEd, and any GraphML-compatible tool.
|
||||
|
||||
Community IDs are written as a node attribute so Gephi can colour by community.
|
||||
Edge confidence (EXTRACTED/INFERRED/AMBIGUOUS) is preserved as an edge attribute.
|
||||
"""
|
||||
H = G.copy()
|
||||
node_community = _node_community_map(communities)
|
||||
for node_id in H.nodes():
|
||||
H.nodes[node_id]["community"] = node_community.get(node_id, -1)
|
||||
nx.write_graphml(H, output_path)
|
||||
|
||||
|
||||
def to_svg(
|
||||
G: nx.Graph,
|
||||
communities: dict[int, list[str]],
|
||||
@@ -595,10 +893,10 @@ def to_svg(
|
||||
) -> None:
|
||||
"""Export graph as an SVG file using matplotlib + spring layout.
|
||||
|
||||
Lightweight and embeddable — works in Obsidian notes, Notion, GitHub READMEs,
|
||||
Lightweight and embeddable - works in Obsidian notes, Notion, GitHub READMEs,
|
||||
and any markdown renderer. No JavaScript required.
|
||||
|
||||
Node size scales with degree. Community colors match the pyvis HTML output.
|
||||
Node size scales with degree. Community colors match the HTML output.
|
||||
"""
|
||||
try:
|
||||
import matplotlib
|
||||
@@ -608,7 +906,7 @@ def to_svg(
|
||||
except ImportError as e:
|
||||
raise ImportError("matplotlib not installed. Run: pip install matplotlib") from e
|
||||
|
||||
node_community = {n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
node_community = _node_community_map(communities)
|
||||
|
||||
fig, ax = plt.subplots(figsize=figsize, facecolor="#1a1a2e")
|
||||
ax.set_facecolor("#1a1a2e")
|
||||
@@ -622,7 +920,7 @@ def to_svg(
|
||||
node_colors = [COMMUNITY_COLORS[node_community.get(n, 0) % len(COMMUNITY_COLORS)] for n in G.nodes()]
|
||||
node_sizes = [300 + 1200 * (degree.get(n, 1) / max_deg) for n in G.nodes()]
|
||||
|
||||
# Draw edges — dashed for non-EXTRACTED
|
||||
# Draw edges - dashed for non-EXTRACTED
|
||||
for u, v, data in G.edges(data=True):
|
||||
conf = data.get("confidence", "EXTRACTED")
|
||||
style = "solid" if conf == "EXTRACTED" else "dashed"
|
||||
|
||||
+97
-11
@@ -60,7 +60,7 @@ def extract_python(path: Path) -> dict:
|
||||
"weight": 1.0,
|
||||
})
|
||||
|
||||
# File-level node — stable ID based on stem only
|
||||
# File-level node - stable ID based on stem only
|
||||
file_nid = _make_id(stem)
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
@@ -94,7 +94,7 @@ def extract_python(path: Path) -> dict:
|
||||
add_node(class_nid, class_name, line)
|
||||
add_edge(file_nid, class_nid, "contains", line)
|
||||
|
||||
# Inheritance — create stub node for external bases so the edge is never dropped
|
||||
# Inheritance - create stub node for external bases so the edge is never dropped
|
||||
args = node.child_by_field_name("superclasses")
|
||||
if args:
|
||||
for arg in args.children:
|
||||
@@ -103,7 +103,7 @@ def extract_python(path: Path) -> dict:
|
||||
# Try same-file base first; fall back to a bare stub
|
||||
base_nid = _make_id(stem, base)
|
||||
if base_nid not in seen_ids:
|
||||
# External or forward-declared base — add a stub so edge survives
|
||||
# External or forward-declared base - add a stub so edge survives
|
||||
base_nid = _make_id(base)
|
||||
if base_nid not in seen_ids:
|
||||
nodes.append({
|
||||
@@ -149,6 +149,92 @@ def extract_python(path: Path) -> dict:
|
||||
function_bodies: list[tuple[str, object]] = []
|
||||
walk(root)
|
||||
|
||||
# ── Docstring + rationale comment extraction ──────────────────────────────
|
||||
# Extract module/class/function docstrings and inline rationale comments.
|
||||
# These become rationale nodes connected to their parent entity via rationale_for.
|
||||
|
||||
_RATIONALE_PREFIXES = ("# NOTE:", "# IMPORTANT:", "# HACK:", "# WHY:", "# RATIONALE:", "# TODO:", "# FIXME:")
|
||||
|
||||
def _get_docstring(body_node) -> tuple[str, int] | None:
|
||||
"""Return (text, line) of the first string literal in a body node, or None."""
|
||||
if not body_node:
|
||||
return None
|
||||
for child in body_node.children:
|
||||
if child.type == "expression_statement":
|
||||
for sub in child.children:
|
||||
if sub.type in ("string", "concatenated_string"):
|
||||
text = source[sub.start_byte:sub.end_byte].decode("utf-8", errors="replace")
|
||||
text = text.strip("\"'").strip('"""').strip("'''").strip()
|
||||
if len(text) > 20:
|
||||
return text, child.start_point[0] + 1
|
||||
break # docstring must be the first statement
|
||||
return None
|
||||
|
||||
def _add_rationale(text: str, line: int, parent_nid: str) -> None:
|
||||
label = text[:80].replace("\n", " ").strip()
|
||||
rid = _make_id(stem, "rationale", str(line))
|
||||
if rid not in seen_ids:
|
||||
seen_ids.add(rid)
|
||||
nodes.append({
|
||||
"id": rid,
|
||||
"label": label,
|
||||
"file_type": "rationale",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
})
|
||||
edges.append({
|
||||
"source": rid,
|
||||
"target": parent_nid,
|
||||
"relation": "rationale_for",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
"weight": 1.0,
|
||||
})
|
||||
|
||||
# Module-level docstring
|
||||
module_body = root # module itself acts as the body
|
||||
ds = _get_docstring(module_body)
|
||||
if ds:
|
||||
_add_rationale(ds[0], ds[1], file_nid)
|
||||
|
||||
# Class and function docstrings (re-walk tree for body nodes)
|
||||
def walk_docstrings(node, parent_nid: str) -> None:
|
||||
t = node.type
|
||||
if t == "class_definition":
|
||||
name_node = node.child_by_field_name("name")
|
||||
body = node.child_by_field_name("body")
|
||||
if name_node and body:
|
||||
class_name = source[name_node.start_byte:name_node.end_byte].decode("utf-8", errors="replace")
|
||||
nid = _make_id(stem, class_name)
|
||||
ds = _get_docstring(body)
|
||||
if ds:
|
||||
_add_rationale(ds[0], ds[1], nid)
|
||||
for child in body.children:
|
||||
walk_docstrings(child, nid)
|
||||
return
|
||||
if t == "function_definition":
|
||||
name_node = node.child_by_field_name("name")
|
||||
body = node.child_by_field_name("body")
|
||||
if name_node and body:
|
||||
func_name = source[name_node.start_byte:name_node.end_byte].decode("utf-8", errors="replace")
|
||||
nid = _make_id(parent_nid, func_name) if parent_nid != file_nid else _make_id(stem, func_name)
|
||||
ds = _get_docstring(body)
|
||||
if ds:
|
||||
_add_rationale(ds[0], ds[1], nid)
|
||||
return
|
||||
for child in node.children:
|
||||
walk_docstrings(child, parent_nid)
|
||||
|
||||
walk_docstrings(root, file_nid)
|
||||
|
||||
# Rationale comments (# NOTE:, # IMPORTANT:, etc.)
|
||||
source_text = source.decode("utf-8", errors="replace")
|
||||
for lineno, line_text in enumerate(source_text.splitlines(), start=1):
|
||||
stripped = line_text.strip()
|
||||
if any(stripped.startswith(p) for p in _RATIONALE_PREFIXES):
|
||||
_add_rationale(stripped, lineno, file_nid)
|
||||
|
||||
# ── Call-graph pass ───────────────────────────────────────────────────────
|
||||
# Build label→nid lookup from all nodes collected above.
|
||||
# Normalise: strip "()" suffix and leading "." so "cohesion_score()" and
|
||||
@@ -162,7 +248,7 @@ def extract_python(path: Path) -> dict:
|
||||
seen_call_pairs: set[tuple[str, str]] = set()
|
||||
|
||||
def walk_calls(node, caller_nid: str) -> None:
|
||||
# Don't recurse into nested function definitions — they have their own context.
|
||||
# Don't recurse into nested function definitions - they have their own context.
|
||||
if node.type == "function_definition":
|
||||
return
|
||||
if node.type == "call":
|
||||
@@ -1316,7 +1402,7 @@ def extract_ruby(path: Path) -> dict:
|
||||
add_edge_raw(file_nid, class_nid, "contains", line)
|
||||
body = node.child_by_field_name("body")
|
||||
if body is None:
|
||||
# body may not be a named field — walk all children except first/last
|
||||
# body may not be a named field - walk all children except first/last
|
||||
for child in node.children:
|
||||
if child.type == "body_statement":
|
||||
body = child
|
||||
@@ -1725,7 +1811,7 @@ def extract_kotlin(path: Path) -> dict:
|
||||
if first.type == "simple_identifier":
|
||||
callee_name = source[first.start_byte:first.end_byte].decode("utf-8", errors="replace")
|
||||
elif first.type == "navigation_expression":
|
||||
# obj.method — get the suffix
|
||||
# obj.method - get the suffix
|
||||
for child in reversed(first.children):
|
||||
if child.type == "simple_identifier":
|
||||
callee_name = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
|
||||
@@ -2127,8 +2213,8 @@ def _resolve_cross_file_imports(
|
||||
"""
|
||||
Two-pass import resolution: turn file-level imports into class-level edges.
|
||||
|
||||
Pass 1 — build a global map: class/function name → node_id, per stem.
|
||||
Pass 2 — for each `from .module import Name`, look up Name in the global
|
||||
Pass 1 - build a global map: class/function name → node_id, per stem.
|
||||
Pass 2 - for each `from .module import Name`, look up Name in the global
|
||||
map and add a direct INFERRED edge from each class in the
|
||||
importing file to the imported entity.
|
||||
|
||||
@@ -2189,7 +2275,7 @@ def _resolve_cross_file_imports(
|
||||
|
||||
def walk_imports(node) -> None:
|
||||
if node.type == "import_from_statement":
|
||||
# Find the module name — handles both absolute and relative imports.
|
||||
# Find the module name - handles both absolute and relative imports.
|
||||
# Relative: `from .models import X` → relative_import → dotted_name
|
||||
# Absolute: `from models import X` → module_name field
|
||||
target_stem: str | None = None
|
||||
@@ -2224,7 +2310,7 @@ def _resolve_cross_file_imports(
|
||||
source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
|
||||
)
|
||||
elif child.type == "aliased_import":
|
||||
# `import X as Y` — take the original name
|
||||
# `import X as Y` - take the original name
|
||||
name_node = child.child_by_field_name("name")
|
||||
if name_node:
|
||||
imported_names.append(
|
||||
@@ -2396,7 +2482,7 @@ def extract(paths: list[Path]) -> dict:
|
||||
all_nodes.extend(result.get("nodes", []))
|
||||
all_edges.extend(result.get("edges", []))
|
||||
|
||||
# Add cross-file class-level edges (Python only — uses Python parser internally)
|
||||
# Add cross-file class-level edges (Python only - uses Python parser internally)
|
||||
py_paths = [p for p in paths if p.suffix == ".py"]
|
||||
py_results = [r for r, p in zip(per_file, paths) if p.suffix == ".py"]
|
||||
cross_file_edges = _resolve_cross_file_imports(py_results, py_paths)
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
# 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
|
||||
# graphify-hook
|
||||
# Auto-rebuilds the knowledge graph after each commit (code files only, no LLM needed).
|
||||
# Installed by: graphify hook install
|
||||
|
||||
CHANGED=$(git diff --name-only HEAD~1 HEAD 2>/dev/null || git diff --name-only HEAD 2>/dev/null)
|
||||
if [ -z "$CHANGED" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
export GRAPHIFY_CHANGED="$CHANGED"
|
||||
python3 -c "
|
||||
import os, sys
|
||||
from pathlib import Path
|
||||
|
||||
CODE_EXTS = {
|
||||
'.py', '.ts', '.js', '.go', '.rs', '.java', '.cpp', '.c', '.rb', '.swift',
|
||||
'.kt', '.cs', '.scala', '.php', '.cc', '.cxx', '.hpp', '.h', '.kts',
|
||||
}
|
||||
|
||||
changed_raw = os.environ.get('GRAPHIFY_CHANGED', '')
|
||||
changed = [Path(f.strip()) for f in changed_raw.strip().splitlines() if f.strip()]
|
||||
code_changed = [f for f in changed if f.suffix.lower() in CODE_EXTS and f.exists()]
|
||||
|
||||
if not code_changed:
|
||||
sys.exit(0)
|
||||
|
||||
print(f'[graphify hook] {len(code_changed)} code file(s) changed - rebuilding graph...')
|
||||
|
||||
try:
|
||||
from graphify.watch import _rebuild_code
|
||||
_rebuild_code(Path('.'))
|
||||
except Exception as exc:
|
||||
print(f'[graphify hook] Rebuild failed: {exc}')
|
||||
sys.exit(0)
|
||||
"
|
||||
"""
|
||||
|
||||
|
||||
_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()
|
||||
for parent in [current, *current.parents]:
|
||||
if (parent / ".git").exists():
|
||||
return parent
|
||||
return None
|
||||
|
||||
|
||||
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}"
|
||||
|
||||
|
||||
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)
|
||||
|
||||
commit_msg = _install_hook(hooks_dir, "post-commit", _HOOK_SCRIPT, _HOOK_MARKER)
|
||||
checkout_msg = _install_hook(hooks_dir, "post-checkout", _CHECKOUT_SCRIPT, _CHECKOUT_MARKER)
|
||||
|
||||
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
|
||||
|
||||
|
||||
def uninstall(path: Path = Path(".")) -> str:
|
||||
"""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()}")
|
||||
|
||||
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)
|
||||
|
||||
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
|
||||
|
||||
|
||||
def status(path: Path = Path(".")) -> str:
|
||||
"""Check if graphify hooks are installed."""
|
||||
root = _git_root(path)
|
||||
if root is None:
|
||||
return "Not in a git repository."
|
||||
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}"
|
||||
+3
-4
@@ -2,7 +2,6 @@
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
from datetime import datetime, timezone
|
||||
@@ -74,7 +73,7 @@ def _fetch_tweet(url: str, author: str | None, contributor: str | None) -> tuple
|
||||
tweet_text = re.sub(r"<[^>]+>", "", data.get("html", "")).strip()
|
||||
tweet_author = data.get("author_name", "unknown")
|
||||
except Exception:
|
||||
# oEmbed failed — save URL stub
|
||||
# oEmbed failed - save URL stub
|
||||
tweet_text = f"Tweet at {url} (could not fetch content)"
|
||||
tweet_author = "unknown"
|
||||
|
||||
@@ -215,7 +214,7 @@ def ingest(url: str, target_dir: Path, author: str | None = None, contributor: s
|
||||
raise RuntimeError(f"ingest: failed to fetch {url!r}: {exc}") from exc
|
||||
|
||||
out_path = target_dir / filename
|
||||
# Avoid overwriting — append counter if needed
|
||||
# Avoid overwriting - append counter if needed
|
||||
counter = 1
|
||||
while out_path.exists():
|
||||
stem = Path(filename).stem
|
||||
@@ -236,7 +235,7 @@ def save_query_result(
|
||||
) -> Path:
|
||||
"""Save a Q&A result as markdown so it gets extracted into the graph on next --update.
|
||||
|
||||
Files are stored in memory_dir (typically .graphify/memory/) with YAML frontmatter
|
||||
Files are stored in memory_dir (typically graphify-out/memory/) with YAML frontmatter
|
||||
that graphify's extractor reads as node metadata. This closes the feedback loop:
|
||||
the system grows smarter from both what you add AND what you ask.
|
||||
"""
|
||||
|
||||
+34
-12
@@ -1,4 +1,4 @@
|
||||
# generate GRAPH_REPORT.md — the human-readable audit trail
|
||||
# generate GRAPH_REPORT.md - the human-readable audit trail
|
||||
from __future__ import annotations
|
||||
from datetime import date
|
||||
import networkx as nx
|
||||
@@ -24,8 +24,12 @@ 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})",
|
||||
f"# Graph Report - {root} ({today})",
|
||||
"",
|
||||
"## Corpus Check",
|
||||
]
|
||||
@@ -41,13 +45,14 @@ 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)",
|
||||
"## God Nodes (most connected - your core abstractions)",
|
||||
]
|
||||
for i, node in enumerate(god_node_list, 1):
|
||||
lines.append(f"{i}. `{node['label']}` — {node['edges']} edges")
|
||||
lines.append(f"{i}. `{node['label']}` - {node['edges']} edges")
|
||||
|
||||
lines += ["", "## Surprising Connections (you probably didn't know these)"]
|
||||
if surprise_list:
|
||||
@@ -55,32 +60,49 @@ 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.")
|
||||
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():
|
||||
label = community_labels.get(cid, f"Community {cid}")
|
||||
score = cohesion_scores.get(cid, 0.0)
|
||||
# Filter method/function stubs from display — they're structural noise
|
||||
# Filter method/function stubs from display - they're structural noise
|
||||
real_nodes = [n for n in nodes if not _ifn(G, n)]
|
||||
display = [G.nodes[n].get("label", n) for n in real_nodes[:8]]
|
||||
suffix = f" (+{len(real_nodes)-8} more)" if len(real_nodes) > 8 else ""
|
||||
lines += [
|
||||
"",
|
||||
f"### Community {cid} — \"{label}\"",
|
||||
f"### Community {cid} - \"{label}\"",
|
||||
f"Cohesion: {score}",
|
||||
f"Nodes ({len(real_nodes)}): {', '.join(display)}{suffix}",
|
||||
]
|
||||
|
||||
ambiguous = [(u, v, d) for u, v, d in G.edges(data=True) if d.get("confidence") == "AMBIGUOUS"]
|
||||
if ambiguous:
|
||||
lines += ["", "## Ambiguous Edges — Review These"]
|
||||
lines += ["", "## Ambiguous Edges - Review These"]
|
||||
for u, v, d in ambiguous:
|
||||
ul = G.nodes[u].get("label", u)
|
||||
vl = G.nodes[v].get("label", v)
|
||||
@@ -107,13 +129,13 @@ def generate(
|
||||
isolated_labels = [G.nodes[n].get("label", n) for n in isolated[:5]]
|
||||
suffix = f" (+{len(isolated)-5} more)" if len(isolated) > 5 else ""
|
||||
lines.append(f"- **{len(isolated)} isolated node(s):** {', '.join(f'`{l}`' for l in isolated_labels)}{suffix}")
|
||||
lines.append(" These have ≤1 connection — possible missing edges or undocumented components.")
|
||||
lines.append(" These have ≤1 connection - possible missing edges or undocumented components.")
|
||||
if thin_communities:
|
||||
for cid, nodes in thin_communities.items():
|
||||
label = community_labels.get(cid, f"Community {cid}")
|
||||
node_labels = [G.nodes[n].get("label", n) for n in nodes]
|
||||
lines.append(f"- **Thin community `{label}`** ({len(nodes)} nodes): {', '.join(f'`{l}`' for l in node_labels)}")
|
||||
lines.append(" Too small to be a meaningful cluster — may be noise or needs more connections extracted.")
|
||||
lines.append(" Too small to be a meaningful cluster - may be noise or needs more connections extracted.")
|
||||
if amb_pct > 20:
|
||||
lines.append(f"- **High ambiguity: {amb_pct}% of edges are AMBIGUOUS.** Review the Ambiguous Edges section above.")
|
||||
|
||||
|
||||
+11
-11
@@ -1,4 +1,4 @@
|
||||
# Security helpers — URL validation, safe fetch, path guards, label sanitisation
|
||||
# Security helpers - URL validation, safe fetch, path guards, label sanitisation
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
@@ -26,7 +26,7 @@ def validate_url(url: str) -> str:
|
||||
parsed = urllib.parse.urlparse(url)
|
||||
if parsed.scheme.lower() not in _ALLOWED_SCHEMES:
|
||||
raise ValueError(
|
||||
f"Blocked URL scheme '{parsed.scheme}' — only http and https are allowed. "
|
||||
f"Blocked URL scheme '{parsed.scheme}' - only http and https are allowed. "
|
||||
f"Got: {url!r}"
|
||||
)
|
||||
return url
|
||||
@@ -63,10 +63,10 @@ def safe_fetch(url: str, max_bytes: int = _MAX_FETCH_BYTES, timeout: int = 30) -
|
||||
- Network errors propagate as urllib.error.URLError / OSError
|
||||
|
||||
Raises:
|
||||
ValueError — disallowed scheme or redirect target
|
||||
urllib.error.HTTPError — non-2xx HTTP status
|
||||
urllib.error.URLError — DNS / connection failure
|
||||
OSError — size cap exceeded
|
||||
ValueError - disallowed scheme or redirect target
|
||||
urllib.error.HTTPError - non-2xx HTTP status
|
||||
urllib.error.URLError - DNS / connection failure
|
||||
OSError - size cap exceeded
|
||||
"""
|
||||
validate_url(url)
|
||||
opener = _build_opener()
|
||||
@@ -112,16 +112,16 @@ def safe_fetch_text(url: str, max_bytes: int = _MAX_TEXT_BYTES, timeout: int = 1
|
||||
def validate_graph_path(path: str | Path, base: Path | None = None) -> Path:
|
||||
"""Resolve *path* and verify it stays inside *base*.
|
||||
|
||||
*base* defaults to the `.graphify` directory relative to CWD.
|
||||
*base* defaults to the `graphify-out` directory relative to CWD.
|
||||
Also requires the base directory to exist, so a caller cannot
|
||||
trick graphify into reading files before any graph has been built.
|
||||
|
||||
Raises:
|
||||
ValueError — path escapes base, or base does not exist
|
||||
FileNotFoundError — resolved path does not exist
|
||||
ValueError - path escapes base, or base does not exist
|
||||
FileNotFoundError - resolved path does not exist
|
||||
"""
|
||||
if base is None:
|
||||
base = Path(".graphify").resolve()
|
||||
base = Path("graphify-out").resolve()
|
||||
|
||||
base = base.resolve()
|
||||
if not base.exists():
|
||||
@@ -136,7 +136,7 @@ def validate_graph_path(path: str | Path, base: Path | None = None) -> Path:
|
||||
except ValueError:
|
||||
raise ValueError(
|
||||
f"Path {path!r} escapes the allowed directory {base}. "
|
||||
"Only paths inside .graphify/ are permitted."
|
||||
"Only paths inside graphify-out/ are permitted."
|
||||
)
|
||||
|
||||
if not resolved.exists():
|
||||
|
||||
+133
-139
@@ -1,4 +1,4 @@
|
||||
# MCP stdio server — exposes graph query tools to Claude and other agents
|
||||
# MCP stdio server - exposes graph query tools to Claude and other agents
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import sys
|
||||
@@ -93,7 +93,14 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
|
||||
return output
|
||||
|
||||
|
||||
def serve(graph_path: str = ".graphify/graph.json") -> None:
|
||||
def _find_node(G: nx.Graph, label: str) -> list[str]:
|
||||
"""Return node IDs whose label or ID matches the search term (case-insensitive)."""
|
||||
term = label.lower()
|
||||
return [nid for nid, d in G.nodes(data=True)
|
||||
if term in d.get("label", "").lower() or term == nid.lower()]
|
||||
|
||||
|
||||
def serve(graph_path: str = "graphify-out/graph.json") -> None:
|
||||
"""Start the MCP server. Requires pip install mcp."""
|
||||
try:
|
||||
from mcp.server import Server
|
||||
@@ -130,9 +137,7 @@ def serve(graph_path: str = ".graphify/graph.json") -> None:
|
||||
description="Get full details for a specific node by label or ID.",
|
||||
inputSchema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"label": {"type": "string", "description": "Node label or ID to look up"},
|
||||
},
|
||||
"properties": {"label": {"type": "string", "description": "Node label or ID to look up"}},
|
||||
"required": ["label"],
|
||||
},
|
||||
),
|
||||
@@ -150,24 +155,17 @@ def serve(graph_path: str = ".graphify/graph.json") -> None:
|
||||
),
|
||||
types.Tool(
|
||||
name="get_community",
|
||||
description="Get all nodes in a community by community ID or label.",
|
||||
description="Get all nodes in a community by community ID.",
|
||||
inputSchema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"community_id": {"type": "integer", "description": "Community ID (0-indexed by size)"},
|
||||
},
|
||||
"properties": {"community_id": {"type": "integer", "description": "Community ID (0-indexed by size)"}},
|
||||
"required": ["community_id"],
|
||||
},
|
||||
),
|
||||
types.Tool(
|
||||
name="god_nodes",
|
||||
description="Return the most connected nodes — the core abstractions of the knowledge graph.",
|
||||
inputSchema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"top_n": {"type": "integer", "default": 10},
|
||||
},
|
||||
},
|
||||
description="Return the most connected nodes - the core abstractions of the knowledge graph.",
|
||||
inputSchema={"type": "object", "properties": {"top_n": {"type": "integer", "default": 10}}},
|
||||
),
|
||||
types.Tool(
|
||||
name="graph_stats",
|
||||
@@ -189,130 +187,126 @@ def serve(graph_path: str = ".graphify/graph.json") -> None:
|
||||
),
|
||||
]
|
||||
|
||||
def _tool_query_graph(arguments: dict) -> str:
|
||||
question = arguments["question"]
|
||||
mode = arguments.get("mode", "bfs")
|
||||
depth = min(int(arguments.get("depth", 3)), 6)
|
||||
budget = int(arguments.get("token_budget", 2000))
|
||||
terms = [t.lower() for t in question.split() if len(t) > 2]
|
||||
scored = _score_nodes(G, terms)
|
||||
start_nodes = [nid for _, nid in scored[:3]]
|
||||
if not start_nodes:
|
||||
return "No matching nodes found."
|
||||
nodes, edges = _dfs(G, start_nodes, depth) if mode == "dfs" else _bfs(G, start_nodes, depth)
|
||||
header = f"Traversal: {mode.upper()} depth={depth} | Start: {[G.nodes[n].get('label', n) for n in start_nodes]} | {len(nodes)} nodes found\n\n"
|
||||
return header + _subgraph_to_text(G, nodes, edges, budget)
|
||||
|
||||
def _tool_get_node(arguments: dict) -> str:
|
||||
label = arguments["label"].lower()
|
||||
matches = [(nid, d) for nid, d in G.nodes(data=True)
|
||||
if label in d.get("label", "").lower() or label == nid.lower()]
|
||||
if not matches:
|
||||
return f"No node matching '{label}' found."
|
||||
nid, d = matches[0]
|
||||
return "\n".join([
|
||||
f"Node: {d.get('label', nid)}",
|
||||
f" ID: {nid}",
|
||||
f" Source: {d.get('source_file', '')} {d.get('source_location', '')}",
|
||||
f" Type: {d.get('file_type', '')}",
|
||||
f" Community: {d.get('community', '')}",
|
||||
f" Degree: {G.degree(nid)}",
|
||||
])
|
||||
|
||||
def _tool_get_neighbors(arguments: dict) -> str:
|
||||
label = arguments["label"].lower()
|
||||
rel_filter = arguments.get("relation_filter", "").lower()
|
||||
matches = _find_node(G, label)
|
||||
if not matches:
|
||||
return f"No node matching '{label}' found."
|
||||
nid = matches[0]
|
||||
lines = [f"Neighbors of {G.nodes[nid].get('label', nid)}:"]
|
||||
for neighbor in G.neighbors(nid):
|
||||
d = G.edges[nid, neighbor]
|
||||
rel = d.get("relation", "")
|
||||
if rel_filter and rel_filter not in rel.lower():
|
||||
continue
|
||||
lines.append(f" --> {G.nodes[neighbor].get('label', neighbor)} [{rel}] [{d.get('confidence', '')}]")
|
||||
return "\n".join(lines)
|
||||
|
||||
def _tool_get_community(arguments: dict) -> str:
|
||||
cid = int(arguments["community_id"])
|
||||
nodes = communities.get(cid, [])
|
||||
if not nodes:
|
||||
return f"Community {cid} not found."
|
||||
lines = [f"Community {cid} ({len(nodes)} nodes):"]
|
||||
for n in nodes:
|
||||
d = G.nodes[n]
|
||||
lines.append(f" {d.get('label', n)} [{d.get('source_file', '')}]")
|
||||
return "\n".join(lines)
|
||||
|
||||
def _tool_god_nodes(arguments: dict) -> str:
|
||||
from .analyze import god_nodes as _god_nodes
|
||||
nodes = _god_nodes(G, top_n=int(arguments.get("top_n", 10)))
|
||||
lines = ["God nodes (most connected):"]
|
||||
lines += [f" {i}. {n['label']} - {n['edges']} edges" for i, n in enumerate(nodes, 1)]
|
||||
return "\n".join(lines)
|
||||
|
||||
def _tool_graph_stats(_: dict) -> str:
|
||||
confs = [d.get("confidence", "EXTRACTED") for _, _, d in G.edges(data=True)]
|
||||
total = len(confs) or 1
|
||||
return (
|
||||
f"Nodes: {G.number_of_nodes()}\n"
|
||||
f"Edges: {G.number_of_edges()}\n"
|
||||
f"Communities: {len(communities)}\n"
|
||||
f"EXTRACTED: {round(confs.count('EXTRACTED')/total*100)}%\n"
|
||||
f"INFERRED: {round(confs.count('INFERRED')/total*100)}%\n"
|
||||
f"AMBIGUOUS: {round(confs.count('AMBIGUOUS')/total*100)}%\n"
|
||||
)
|
||||
|
||||
def _tool_shortest_path(arguments: dict) -> str:
|
||||
src_scored = _score_nodes(G, [t.lower() for t in arguments["source"].split()])
|
||||
tgt_scored = _score_nodes(G, [t.lower() for t in arguments["target"].split()])
|
||||
if not src_scored:
|
||||
return f"No node matching source '{arguments['source']}' found."
|
||||
if not tgt_scored:
|
||||
return f"No node matching target '{arguments['target']}' found."
|
||||
src_nid, tgt_nid = src_scored[0][1], tgt_scored[0][1]
|
||||
max_hops = int(arguments.get("max_hops", 8))
|
||||
try:
|
||||
path_nodes = nx.shortest_path(G, src_nid, tgt_nid)
|
||||
except (nx.NetworkXNoPath, nx.NodeNotFound):
|
||||
return f"No path found between '{G.nodes[src_nid].get('label', src_nid)}' and '{G.nodes[tgt_nid].get('label', tgt_nid)}'."
|
||||
hops = len(path_nodes) - 1
|
||||
if hops > max_hops:
|
||||
return f"Path exceeds max_hops={max_hops} ({hops} hops found)."
|
||||
segments = []
|
||||
for i in range(len(path_nodes) - 1):
|
||||
u, v = path_nodes[i], path_nodes[i + 1]
|
||||
edata = G.edges[u, v]
|
||||
rel = edata.get("relation", "")
|
||||
conf = edata.get("confidence", "")
|
||||
conf_str = f" [{conf}]" if conf else ""
|
||||
if i == 0:
|
||||
segments.append(G.nodes[u].get("label", u))
|
||||
segments.append(f"--{rel}{conf_str}--> {G.nodes[v].get('label', v)}")
|
||||
return f"Shortest path ({hops} hops):\n " + " ".join(segments)
|
||||
|
||||
_handlers = {
|
||||
"query_graph": _tool_query_graph,
|
||||
"get_node": _tool_get_node,
|
||||
"get_neighbors": _tool_get_neighbors,
|
||||
"get_community": _tool_get_community,
|
||||
"god_nodes": _tool_god_nodes,
|
||||
"graph_stats": _tool_graph_stats,
|
||||
"shortest_path": _tool_shortest_path,
|
||||
}
|
||||
|
||||
@server.call_tool()
|
||||
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
|
||||
if name == "query_graph":
|
||||
question = arguments["question"]
|
||||
mode = arguments.get("mode", "bfs")
|
||||
depth = min(int(arguments.get("depth", 3)), 6)
|
||||
budget = int(arguments.get("token_budget", 2000))
|
||||
terms = [t.lower() for t in question.split() if len(t) > 2]
|
||||
scored = _score_nodes(G, terms)
|
||||
start_nodes = [nid for _, nid in scored[:3]]
|
||||
if not start_nodes:
|
||||
return [types.TextContent(type="text", text="No matching nodes found.")]
|
||||
if mode == "dfs":
|
||||
nodes, edges = _dfs(G, start_nodes, depth)
|
||||
else:
|
||||
nodes, edges = _bfs(G, start_nodes, depth)
|
||||
text = f"Traversal: {mode.upper()} depth={depth} | Start: {[G.nodes[n].get('label', n) for n in start_nodes]} | {len(nodes)} nodes found\n\n"
|
||||
text += _subgraph_to_text(G, nodes, edges, budget)
|
||||
return [types.TextContent(type="text", text=text)]
|
||||
|
||||
elif name == "get_node":
|
||||
label = arguments["label"].lower()
|
||||
matches = [(nid, d) for nid, d in G.nodes(data=True)
|
||||
if label in d.get("label", "").lower() or label == nid.lower()]
|
||||
if not matches:
|
||||
return [types.TextContent(type="text", text=f"No node matching '{label}' found.")]
|
||||
nid, d = matches[0]
|
||||
lines = [f"Node: {d.get('label', nid)}",
|
||||
f" ID: {nid}",
|
||||
f" Source: {d.get('source_file', '')} {d.get('source_location', '')}",
|
||||
f" Type: {d.get('file_type', '')}",
|
||||
f" Community: {d.get('community', '')}",
|
||||
f" Degree: {G.degree(nid)}"]
|
||||
return [types.TextContent(type="text", text="\n".join(lines))]
|
||||
|
||||
elif name == "get_neighbors":
|
||||
label = arguments["label"].lower()
|
||||
rel_filter = arguments.get("relation_filter", "").lower()
|
||||
matches = [nid for nid, d in G.nodes(data=True)
|
||||
if label in d.get("label", "").lower() or label == nid.lower()]
|
||||
if not matches:
|
||||
return [types.TextContent(type="text", text=f"No node matching '{label}' found.")]
|
||||
nid = matches[0]
|
||||
lines = [f"Neighbors of {G.nodes[nid].get('label', nid)}:"]
|
||||
for neighbor in G.neighbors(nid):
|
||||
d = G.edges[nid, neighbor]
|
||||
rel = d.get("relation", "")
|
||||
if rel_filter and rel_filter not in rel.lower():
|
||||
continue
|
||||
conf = d.get("confidence", "")
|
||||
nlabel = G.nodes[neighbor].get("label", neighbor)
|
||||
lines.append(f" --> {nlabel} [{rel}] [{conf}]")
|
||||
return [types.TextContent(type="text", text="\n".join(lines))]
|
||||
|
||||
elif name == "get_community":
|
||||
cid = int(arguments["community_id"])
|
||||
nodes = communities.get(cid, [])
|
||||
if not nodes:
|
||||
return [types.TextContent(type="text", text=f"Community {cid} not found.")]
|
||||
lines = [f"Community {cid} ({len(nodes)} nodes):"]
|
||||
for n in nodes:
|
||||
d = G.nodes[n]
|
||||
lines.append(f" {d.get('label', n)} [{d.get('source_file', '')}]")
|
||||
return [types.TextContent(type="text", text="\n".join(lines))]
|
||||
|
||||
elif name == "god_nodes":
|
||||
from .analyze import god_nodes as _god_nodes
|
||||
top_n = int(arguments.get("top_n", 10))
|
||||
nodes = _god_nodes(G, top_n=top_n)
|
||||
lines = ["God nodes (most connected):"]
|
||||
for i, n in enumerate(nodes, 1):
|
||||
lines.append(f" {i}. {n['label']} — {n['edges']} edges")
|
||||
return [types.TextContent(type="text", text="\n".join(lines))]
|
||||
|
||||
elif name == "graph_stats":
|
||||
confs = [d.get("confidence", "EXTRACTED") for _, _, d in G.edges(data=True)]
|
||||
total = len(confs) or 1
|
||||
text = (
|
||||
f"Nodes: {G.number_of_nodes()}\n"
|
||||
f"Edges: {G.number_of_edges()}\n"
|
||||
f"Communities: {len(communities)}\n"
|
||||
f"EXTRACTED: {round(confs.count('EXTRACTED')/total*100)}%\n"
|
||||
f"INFERRED: {round(confs.count('INFERRED')/total*100)}%\n"
|
||||
f"AMBIGUOUS: {round(confs.count('AMBIGUOUS')/total*100)}%\n"
|
||||
)
|
||||
return [types.TextContent(type="text", text=text)]
|
||||
|
||||
elif name == "shortest_path":
|
||||
src_terms = [t.lower() for t in arguments["source"].split()]
|
||||
tgt_terms = [t.lower() for t in arguments["target"].split()]
|
||||
max_hops = int(arguments.get("max_hops", 8))
|
||||
src_scored = _score_nodes(G, src_terms)
|
||||
tgt_scored = _score_nodes(G, tgt_terms)
|
||||
if not src_scored:
|
||||
return [types.TextContent(type="text", text=f"No node matching source '{arguments['source']}' found.")]
|
||||
if not tgt_scored:
|
||||
return [types.TextContent(type="text", text=f"No node matching target '{arguments['target']}' found.")]
|
||||
src_nid = src_scored[0][1]
|
||||
tgt_nid = tgt_scored[0][1]
|
||||
try:
|
||||
path_nodes = nx.shortest_path(G, src_nid, tgt_nid)
|
||||
except (nx.NetworkXNoPath, nx.NodeNotFound):
|
||||
src_label = G.nodes[src_nid].get("label", src_nid)
|
||||
tgt_label = G.nodes[tgt_nid].get("label", tgt_nid)
|
||||
return [types.TextContent(type="text", text=f"No path found between '{src_label}' and '{tgt_label}'.")]
|
||||
hops = len(path_nodes) - 1
|
||||
if hops > max_hops:
|
||||
return [types.TextContent(type="text", text=f"Path exceeds max_hops={max_hops} ({hops} hops found).")]
|
||||
segments = []
|
||||
for i in range(len(path_nodes) - 1):
|
||||
u, v = path_nodes[i], path_nodes[i + 1]
|
||||
u_label = G.nodes[u].get("label", u)
|
||||
v_label = G.nodes[v].get("label", v)
|
||||
edata = G.edges[u, v]
|
||||
rel = edata.get("relation", "")
|
||||
conf = edata.get("confidence", "")
|
||||
conf_str = f" [{conf}]" if conf else ""
|
||||
if i == 0:
|
||||
segments.append(f"{u_label}")
|
||||
segments.append(f"--{rel}{conf_str}--> {v_label}")
|
||||
text = f"Shortest path ({hops} hops):\n " + " ".join(segments)
|
||||
return [types.TextContent(type="text", text=text)]
|
||||
|
||||
return [types.TextContent(type="text", text=f"Unknown tool: {name}")]
|
||||
handler = _handlers.get(name)
|
||||
if not handler:
|
||||
return [types.TextContent(type="text", text=f"Unknown tool: {name}")]
|
||||
return [types.TextContent(type="text", text=handler(arguments))]
|
||||
|
||||
import asyncio
|
||||
|
||||
@@ -324,5 +318,5 @@ def serve(graph_path: str = ".graphify/graph.json") -> None:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
graph_path = sys.argv[1] if len(sys.argv) > 1 else ".graphify/graph.json"
|
||||
graph_path = sys.argv[1] if len(sys.argv) > 1 else "graphify-out/graph.json"
|
||||
serve(graph_path)
|
||||
+344
-166
File diff suppressed because it is too large.
Load diff
@@ -10,7 +10,7 @@ REQUIRED_EDGE_FIELDS = {"source", "target", "relation", "confidence", "source_fi
|
||||
def validate_extraction(data: dict) -> list[str]:
|
||||
"""
|
||||
Validate an extraction JSON dict against the graphify schema.
|
||||
Returns a list of error strings — empty list means valid.
|
||||
Returns a list of error strings - empty list means valid.
|
||||
"""
|
||||
if not isinstance(data, dict):
|
||||
return ["Extraction must be a JSON object"]
|
||||
@@ -33,7 +33,7 @@ def validate_extraction(data: dict) -> list[str]:
|
||||
if "file_type" in node and node["file_type"] not in VALID_FILE_TYPES:
|
||||
errors.append(
|
||||
f"Node {i} (id={node.get('id', '?')!r}) has invalid file_type "
|
||||
f"'{node['file_type']}' — must be one of {sorted(VALID_FILE_TYPES)}"
|
||||
f"'{node['file_type']}' - must be one of {sorted(VALID_FILE_TYPES)}"
|
||||
)
|
||||
|
||||
# Edges
|
||||
@@ -53,7 +53,7 @@ def validate_extraction(data: dict) -> list[str]:
|
||||
if "confidence" in edge and edge["confidence"] not in VALID_CONFIDENCES:
|
||||
errors.append(
|
||||
f"Edge {i} has invalid confidence '{edge['confidence']}' "
|
||||
f"— must be one of {sorted(VALID_CONFIDENCES)}"
|
||||
f"- must be one of {sorted(VALID_CONFIDENCES)}"
|
||||
)
|
||||
if "source" in edge and node_ids and edge["source"] not in node_ids:
|
||||
errors.append(f"Edge {i} source '{edge['source']}' does not match any node id")
|
||||
|
||||
+101
-7
@@ -1,5 +1,6 @@
|
||||
# monitor a folder and auto-trigger --update when files change
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
@@ -11,20 +12,100 @@ _WATCHED_EXTENSIONS = {
|
||||
".png", ".jpg", ".jpeg", ".webp", ".gif", ".svg",
|
||||
}
|
||||
|
||||
_CODE_EXTENSIONS = {
|
||||
".py", ".ts", ".js", ".go", ".rs", ".java", ".cpp", ".c", ".rb", ".swift", ".kt",
|
||||
".cs", ".scala", ".php", ".cc", ".cxx", ".hpp", ".h", ".kts",
|
||||
}
|
||||
|
||||
def _run_update(watch_path: Path) -> None:
|
||||
"""Write a flag file and print a notification when files change."""
|
||||
flag = watch_path / ".graphify" / "needs_update"
|
||||
|
||||
def _rebuild_code(watch_path: Path) -> bool:
|
||||
"""Re-run AST extraction + build + cluster + report for code files. No LLM needed.
|
||||
|
||||
Returns True on success, False on error.
|
||||
"""
|
||||
try:
|
||||
from graphify.extract import collect_files, extract
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
|
||||
from graphify.report import generate
|
||||
from graphify.export import to_json
|
||||
|
||||
code_files = []
|
||||
for ext in _CODE_EXTENSIONS:
|
||||
code_files.extend(watch_path.rglob(f"*{ext}"))
|
||||
code_files = [
|
||||
f for f in code_files
|
||||
if not any(part.startswith(".") for part in f.parts)
|
||||
and "graphify-out" not in f.parts
|
||||
and "__pycache__" not in f.parts
|
||||
]
|
||||
|
||||
if not code_files:
|
||||
print("[graphify watch] No code files found - nothing to rebuild.")
|
||||
return False
|
||||
|
||||
result = extract(code_files)
|
||||
|
||||
detection = {
|
||||
"files": {"code": [str(f) for f in code_files], "document": [], "paper": [], "image": []},
|
||||
"total_files": len(code_files),
|
||||
"total_words": sum(len(f.read_text(errors="ignore").split()) for f in code_files),
|
||||
}
|
||||
|
||||
G = build_from_json(result)
|
||||
communities = cluster(G)
|
||||
cohesion = score_all(G, communities)
|
||||
gods = god_nodes(G)
|
||||
surprises = surprising_connections(G, communities)
|
||||
labels = {cid: "Community " + str(cid) for cid in communities}
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
out = watch_path / "graphify-out"
|
||||
out.mkdir(exist_ok=True)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection,
|
||||
{"input": 0, "output": 0}, str(watch_path), suggested_questions=questions)
|
||||
(out / "GRAPH_REPORT.md").write_text(report)
|
||||
to_json(G, communities, str(out / "graph.json"))
|
||||
|
||||
# clear stale needs_update flag if present
|
||||
flag = out / "needs_update"
|
||||
if flag.exists():
|
||||
flag.unlink()
|
||||
|
||||
print(f"[graphify watch] Rebuilt: {G.number_of_nodes()} nodes, "
|
||||
f"{G.number_of_edges()} edges, {len(communities)} communities")
|
||||
print(f"[graphify watch] graph.json and GRAPH_REPORT.md updated in {out}")
|
||||
return True
|
||||
|
||||
except Exception as exc:
|
||||
print(f"[graphify watch] Rebuild failed: {exc}")
|
||||
return False
|
||||
|
||||
|
||||
def _notify_only(watch_path: Path) -> None:
|
||||
"""Write a flag file and print a notification (fallback for non-code-only corpora)."""
|
||||
flag = watch_path / "graphify-out" / "needs_update"
|
||||
flag.parent.mkdir(parents=True, exist_ok=True)
|
||||
flag.write_text("1")
|
||||
print(f"\n[graphify watch] New or changed files detected in {watch_path}")
|
||||
print("[graphify watch] Non-code files changed - semantic re-extraction requires LLM.")
|
||||
print("[graphify watch] Run `/graphify --update` in Claude Code to update the graph.")
|
||||
print(f"[graphify watch] Flag written to {flag}")
|
||||
|
||||
|
||||
def _has_non_code(changed_paths: list[Path]) -> bool:
|
||||
return any(p.suffix.lower() not in _CODE_EXTENSIONS for p in changed_paths)
|
||||
|
||||
|
||||
def watch(watch_path: Path, debounce: float = 3.0) -> None:
|
||||
"""
|
||||
Watch watch_path for new or modified files and re-run graphify --update.
|
||||
Watch watch_path for new or modified files and auto-update the graph.
|
||||
|
||||
For code-only changes: re-runs AST extraction + rebuild immediately (no LLM).
|
||||
For doc/paper/image changes: writes a needs_update flag and notifies the user
|
||||
to run /graphify --update (LLM extraction required).
|
||||
|
||||
debounce: seconds to wait after the last change before triggering (avoids
|
||||
running on every keystroke when many files are saved at once).
|
||||
@@ -37,6 +118,7 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
|
||||
|
||||
last_trigger: float = 0.0
|
||||
pending: bool = False
|
||||
changed: list[Path] = []
|
||||
|
||||
class Handler(FileSystemEventHandler):
|
||||
def on_any_event(self, event):
|
||||
@@ -48,23 +130,35 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
|
||||
return
|
||||
if any(part.startswith(".") for part in path.parts):
|
||||
return
|
||||
if "graphify-out" in path.parts:
|
||||
return
|
||||
last_trigger = time.monotonic()
|
||||
pending = True
|
||||
if path not in changed:
|
||||
changed.append(path)
|
||||
|
||||
handler = Handler()
|
||||
observer = Observer()
|
||||
observer.schedule(handler, str(watch_path), recursive=True)
|
||||
observer.start()
|
||||
|
||||
print(f"[graphify watch] Watching {watch_path.resolve()} — press Ctrl+C to stop")
|
||||
print(f"[graphify watch] Debounce: {debounce}s — will update {debounce}s after last change")
|
||||
print(f"[graphify watch] Watching {watch_path.resolve()} - press Ctrl+C to stop")
|
||||
print(f"[graphify watch] Code changes rebuild graph automatically. "
|
||||
f"Doc/image changes require /graphify --update.")
|
||||
print(f"[graphify watch] Debounce: {debounce}s")
|
||||
|
||||
try:
|
||||
while True:
|
||||
time.sleep(0.5)
|
||||
if pending and (time.monotonic() - last_trigger) >= debounce:
|
||||
pending = False
|
||||
_run_update(watch_path)
|
||||
batch = list(changed)
|
||||
changed.clear()
|
||||
print(f"\n[graphify watch] {len(batch)} file(s) changed")
|
||||
if _has_non_code(batch):
|
||||
_notify_only(watch_path)
|
||||
else:
|
||||
_rebuild_code(watch_path)
|
||||
except KeyboardInterrupt:
|
||||
print("\n[graphify watch] Stopped.")
|
||||
finally:
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
# Wiki export - Wikipedia-style markdown articles from the knowledge graph
|
||||
# Generates an agent-crawlable wiki: index.md + one article per community + god node articles
|
||||
from __future__ import annotations
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
|
||||
|
||||
def _safe_filename(name: str) -> str:
|
||||
return name.replace("/", "-").replace(" ", "_").replace(":", "-")
|
||||
|
||||
|
||||
def _cross_community_links(G: nx.Graph, nodes: list[str], own_cid: int, labels: dict[int, str]) -> list[tuple[str, int]]:
|
||||
"""Return (community_label, edge_count) pairs for cross-community connections, sorted descending."""
|
||||
counts: dict[str, int] = Counter()
|
||||
for nid in nodes:
|
||||
for neighbor in G.neighbors(nid):
|
||||
nd = G.nodes[neighbor]
|
||||
ncid = nd.get("community")
|
||||
if ncid is not None and ncid != own_cid:
|
||||
counts[labels.get(ncid, f"Community {ncid}")] += 1
|
||||
return sorted(counts.items(), key=lambda x: -x[1])
|
||||
|
||||
|
||||
def _community_article(
|
||||
G: nx.Graph,
|
||||
cid: int,
|
||||
nodes: list[str],
|
||||
label: str,
|
||||
labels: dict[int, str],
|
||||
cohesion: float | None,
|
||||
) -> str:
|
||||
top_nodes = sorted(nodes, key=lambda n: G.degree(n), reverse=True)[:25]
|
||||
cross = _cross_community_links(G, nodes, cid, labels)
|
||||
|
||||
# Edge confidence breakdown
|
||||
conf_counts: Counter = Counter()
|
||||
for nid in nodes:
|
||||
for neighbor in G.neighbors(nid):
|
||||
ed = G.edges[nid, neighbor]
|
||||
conf_counts[ed.get("confidence", "EXTRACTED")] += 1
|
||||
total_edges = sum(conf_counts.values()) or 1
|
||||
|
||||
sources = sorted({G.nodes[n].get("source_file", "") for n in nodes} - {""})
|
||||
|
||||
lines: list[str] = []
|
||||
lines += [f"# {label}", ""]
|
||||
|
||||
meta_parts = [f"{len(nodes)} nodes"]
|
||||
if cohesion is not None:
|
||||
meta_parts.append(f"cohesion {cohesion:.2f}")
|
||||
lines += [f"> {' · '.join(meta_parts)}", ""]
|
||||
|
||||
lines += ["## Key Concepts", ""]
|
||||
for nid in top_nodes:
|
||||
d = G.nodes[nid]
|
||||
node_label = d.get("label", nid)
|
||||
src = d.get("source_file", "")
|
||||
degree = G.degree(nid)
|
||||
src_str = f" — `{src}`" if src else ""
|
||||
lines.append(f"- **{node_label}** ({degree} connections){src_str}")
|
||||
remaining = len(nodes) - len(top_nodes)
|
||||
if remaining > 0:
|
||||
lines.append(f"- *... and {remaining} more nodes in this community*")
|
||||
lines.append("")
|
||||
|
||||
lines += ["## Relationships", ""]
|
||||
if cross:
|
||||
for other_label, count in cross[:12]:
|
||||
lines.append(f"- [[{other_label}]] ({count} shared connections)")
|
||||
else:
|
||||
lines.append("- No strong cross-community connections detected")
|
||||
lines.append("")
|
||||
|
||||
if sources:
|
||||
lines += ["## Source Files", ""]
|
||||
for src in sources[:20]:
|
||||
lines.append(f"- `{src}`")
|
||||
lines.append("")
|
||||
|
||||
lines += ["## Audit Trail", ""]
|
||||
for conf in ("EXTRACTED", "INFERRED", "AMBIGUOUS"):
|
||||
n = conf_counts.get(conf, 0)
|
||||
pct = round(n / total_edges * 100)
|
||||
lines.append(f"- {conf}: {n} ({pct}%)")
|
||||
lines.append("")
|
||||
|
||||
lines += ["---", "", "*Part of the graphify knowledge wiki. See [[index]] to navigate.*"]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _god_node_article(G: nx.Graph, nid: str, labels: dict[int, str]) -> str:
|
||||
d = G.nodes[nid]
|
||||
node_label = d.get("label", nid)
|
||||
src = d.get("source_file", "")
|
||||
cid = d.get("community")
|
||||
community_name = labels.get(cid, f"Community {cid}") if cid is not None else None
|
||||
|
||||
lines: list[str] = []
|
||||
lines += [f"# {node_label}", ""]
|
||||
lines += [f"> God node · {G.degree(nid)} connections · `{src}`", ""]
|
||||
|
||||
if community_name:
|
||||
lines += [f"**Community:** [[{community_name}]]", ""]
|
||||
|
||||
# Group neighbors by relation type
|
||||
by_relation: dict[str, list[str]] = {}
|
||||
for neighbor in sorted(G.neighbors(nid), key=lambda n: G.degree(n), reverse=True):
|
||||
nd = G.nodes[neighbor]
|
||||
ed = G.edges[nid, neighbor]
|
||||
rel = ed.get("relation", "related")
|
||||
neighbor_label = nd.get("label", neighbor)
|
||||
conf = ed.get("confidence", "")
|
||||
conf_str = f" `{conf}`" if conf else ""
|
||||
by_relation.setdefault(rel, []).append(f"[[{neighbor_label}]]{conf_str}")
|
||||
|
||||
lines += ["## Connections by Relation", ""]
|
||||
for rel, targets in sorted(by_relation.items()):
|
||||
lines.append(f"### {rel}")
|
||||
for t in targets[:20]:
|
||||
lines.append(f"- {t}")
|
||||
lines.append("")
|
||||
|
||||
lines += ["---", "", "*Part of the graphify knowledge wiki. See [[index]] to navigate.*"]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _index_md(
|
||||
communities: dict[int, list[str]],
|
||||
labels: dict[int, str],
|
||||
god_nodes_data: list[dict],
|
||||
total_nodes: int,
|
||||
total_edges: int,
|
||||
) -> str:
|
||||
lines: list[str] = [
|
||||
"# Knowledge Graph Index",
|
||||
"",
|
||||
"> Auto-generated by graphify. Start here — read community articles for context, then drill into god nodes for detail.",
|
||||
"",
|
||||
f"**{total_nodes} nodes · {total_edges} edges · {len(communities)} communities**",
|
||||
"",
|
||||
"---",
|
||||
"",
|
||||
"## Communities",
|
||||
"(sorted by size, largest first)",
|
||||
"",
|
||||
]
|
||||
|
||||
for cid, nodes in sorted(communities.items(), key=lambda x: -len(x[1])):
|
||||
label = labels.get(cid, f"Community {cid}")
|
||||
lines.append(f"- [[{label}]] — {len(nodes)} nodes")
|
||||
lines.append("")
|
||||
|
||||
if god_nodes_data:
|
||||
lines += ["## God Nodes", "(most connected concepts — the load-bearing abstractions)", ""]
|
||||
for node in god_nodes_data:
|
||||
lines.append(f"- [[{node['label']}]] — {node['edges']} connections")
|
||||
lines.append("")
|
||||
|
||||
lines += [
|
||||
"---",
|
||||
"",
|
||||
"*Generated by [graphify](https://github.com/safishamsi/graphify)*",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def to_wiki(
|
||||
G: nx.Graph,
|
||||
communities: dict[int, list[str]],
|
||||
output_dir: str | Path,
|
||||
community_labels: dict[int, str] | None = None,
|
||||
cohesion: dict[int, float] | None = None,
|
||||
god_nodes_data: list[dict] | None = None,
|
||||
) -> int:
|
||||
"""Generate a Wikipedia-style wiki from the graph.
|
||||
|
||||
Writes:
|
||||
- index.md — agent entry point, catalog of all articles
|
||||
- <CommunityName>.md — one article per community
|
||||
- <GodNodeLabel>.md — one article per god node
|
||||
|
||||
Returns the number of articles written (excluding index.md).
|
||||
"""
|
||||
out = Path(output_dir)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
labels = community_labels or {cid: f"Community {cid}" for cid in communities}
|
||||
cohesion = cohesion or {}
|
||||
god_nodes_data = god_nodes_data or []
|
||||
|
||||
count = 0
|
||||
|
||||
# Community articles
|
||||
for cid, nodes in communities.items():
|
||||
label = labels.get(cid, f"Community {cid}")
|
||||
article = _community_article(G, cid, nodes, label, labels, cohesion.get(cid))
|
||||
(out / f"{_safe_filename(label)}.md").write_text(article)
|
||||
count += 1
|
||||
|
||||
# God node articles
|
||||
for node_data in god_nodes_data:
|
||||
nid = node_data.get("id")
|
||||
if nid and nid in G:
|
||||
article = _god_node_article(G, nid, labels)
|
||||
(out / f"{_safe_filename(node_data['label'])}.md").write_text(article)
|
||||
count += 1
|
||||
|
||||
# Index
|
||||
(out / "index.md").write_text(
|
||||
_index_md(communities, labels, god_nodes_data, G.number_of_nodes(), G.number_of_edges())
|
||||
)
|
||||
|
||||
return count
|
||||
+11
-6
@@ -3,16 +3,15 @@ requires = ["setuptools>=68"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "graphify"
|
||||
version = "0.1.1"
|
||||
description = "Turn any codebase, docs, or images into a queryable knowledge graph"
|
||||
name = "graphifyy"
|
||||
version = "0.2.2"
|
||||
description = "Claude Code skill - turn any folder of code, docs, papers, images, or tweets into a queryable knowledge graph"
|
||||
readme = "README.md"
|
||||
license = { text = "MIT" }
|
||||
keywords = ["claude", "claude-code", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"networkx",
|
||||
"graspologic",
|
||||
"pyvis",
|
||||
"tree-sitter",
|
||||
"tree-sitter-python",
|
||||
"tree-sitter-javascript",
|
||||
@@ -29,12 +28,18 @@ dependencies = [
|
||||
"tree-sitter-php",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/safishamsi/graphify"
|
||||
Repository = "https://github.com/safishamsi/graphify"
|
||||
Issues = "https://github.com/safishamsi/graphify/issues"
|
||||
|
||||
[project.optional-dependencies]
|
||||
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"
|
||||
|
||||
+298
-130
@@ -14,20 +14,21 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify # full pipeline on current directory → Obsidian vault
|
||||
/graphify <path> # full pipeline on specific path
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental — re-extract only new/changed files
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
/graphify <path> --no-viz # skip visualization, just report + JSON
|
||||
/graphify <path> --html # also export graph.html (pyvis, browser-based)
|
||||
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
|
||||
/graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
|
||||
/graphify <path> --neo4j # generate .graphify/cypher.txt for Neo4j
|
||||
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
|
||||
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
|
||||
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
|
||||
/graphify <path> --mcp # start MCP stdio server for agent access
|
||||
/graphify <path> --watch # watch folder, notify when files change
|
||||
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
|
||||
/graphify add <url> # fetch URL, save to ./raw, update graph
|
||||
/graphify add <url> --author "Name" # tag who wrote it
|
||||
/graphify add <url> --contributor "Name" # tag who added it to the corpus
|
||||
/graphify query "<question>" # BFS traversal — broad context
|
||||
/graphify query "<question>" --dfs # DFS — trace a specific path
|
||||
/graphify query "<question>" # BFS traversal - broad context
|
||||
/graphify query "<question>" --dfs # DFS - trace a specific path
|
||||
/graphify query "<question>" --budget 1500 # cap answer at N tokens
|
||||
/graphify path "AuthModule" "Database" # shortest path between two concepts
|
||||
/graphify explain "SwinTransformer" # plain-language explanation of a node
|
||||
@@ -35,12 +36,12 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
## What graphify is for
|
||||
|
||||
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder — papers, tweets, screenshots, code, notes — and get a structured knowledge graph that shows you what you didn't know was connected.
|
||||
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
|
||||
|
||||
Three things it does that Claude alone cannot:
|
||||
1. **Persistent graph** — relationships are stored in `.graphify/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
|
||||
2. **Honest audit trail** — every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
|
||||
3. **Cross-document surprise** — community detection finds connections between concepts in different files that you would never think to ask about directly.
|
||||
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
|
||||
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
|
||||
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
|
||||
|
||||
Use it for:
|
||||
- A codebase you're new to (understand architecture before touching anything)
|
||||
@@ -54,15 +55,15 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
|
||||
### Step 1 — Ensure graphify is installed
|
||||
### Step 1 - Ensure graphify is installed
|
||||
|
||||
```bash
|
||||
python3 -c "import graphify" 2>/dev/null || pip install graphify -q --break-system-packages 2>&1 | tail -3
|
||||
python3 -c "import graphify" 2>/dev/null || pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
|
||||
### Step 2 — Detect files
|
||||
### Step 2 - Detect files
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
@@ -74,7 +75,7 @@ print(json.dumps(result))
|
||||
" > .graphify_detect.json
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON — read it silently and present a clean summary instead:
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -88,17 +89,21 @@ Then act on it:
|
||||
- If `total_files` is 0: stop with "No supported files found in [path]."
|
||||
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
|
||||
- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.
|
||||
- Otherwise: proceed directly to Step 3 — no need to ask anything.
|
||||
- Otherwise: proceed directly to Step 3 - no need to ask anything.
|
||||
|
||||
### Step 3 — Extract entities and relationships
|
||||
### Step 3 - Extract entities and relationships
|
||||
|
||||
**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.
|
||||
**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).
|
||||
|
||||
#### Part A — Structural extraction for code files
|
||||
**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.**
|
||||
|
||||
For any code files detected, run AST extraction first:
|
||||
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 in parallel with Part B subagents:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
@@ -118,20 +123,23 @@ if code_files:
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
Path('.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
|
||||
print('No code files — skipping AST extraction')
|
||||
print('No code files - skipping AST extraction')
|
||||
"
|
||||
```
|
||||
|
||||
#### Part B — Semantic extraction (parallel subagents)
|
||||
#### Part B - Semantic extraction (parallel subagents)
|
||||
|
||||
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden — it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
|
||||
**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do.
|
||||
|
||||
Before dispatching subagents, print a cost estimate:
|
||||
- Load `total_words` from `.graphify_detect.json`
|
||||
- Estimate: ~(total_words / 750) input tokens per file on average, output ~20% of that
|
||||
- Print: "Semantic extraction: ~N files, estimated ~X input tokens"
|
||||
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
|
||||
|
||||
**Step B0 — Check extraction cache first**
|
||||
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"
|
||||
|
||||
**Step B0 - Check extraction cache first**
|
||||
|
||||
Before dispatching any subagents, check which files already have cached extraction results:
|
||||
|
||||
@@ -155,13 +163,13 @@ print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files n
|
||||
|
||||
Only dispatch subagents for files listed in `.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
|
||||
|
||||
**Step B1 — Split into chunks**
|
||||
**Step B1 - Split into chunks**
|
||||
|
||||
Load files from `.graphify_uncached.txt`. Split into chunks of 12-15 files each. Each image gets its own chunk (vision needs separate context).
|
||||
Load files from `.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context).
|
||||
|
||||
**Step B2 — Dispatch ALL subagents in a single message**
|
||||
**Step B2 - Dispatch ALL subagents in a single message**
|
||||
|
||||
Call the Agent tool multiple times IN THE SAME RESPONSE — one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.
|
||||
Call the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.
|
||||
|
||||
Concrete example for 3 chunks:
|
||||
```
|
||||
@@ -175,7 +183,7 @@ Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL
|
||||
|
||||
```
|
||||
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
|
||||
Output ONLY valid JSON matching the schema below — no explanation, no markdown fences, no preamble.
|
||||
Output ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble.
|
||||
|
||||
Files (chunk CHUNK_NUM of TOTAL_CHUNKS):
|
||||
FILE_LIST
|
||||
@@ -183,12 +191,12 @@ FILE_LIST
|
||||
Rules:
|
||||
- EXTRACTED: relationship explicit in source (import, call, citation, "see §3.2")
|
||||
- INFERRED: reasonable inference (shared data structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain — flag for review, do not omit
|
||||
- AMBIGUOUS: uncertain - flag for review, do not omit
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports — AST already has those.
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations.
|
||||
Image files: use vision to understand what the image IS — do not just OCR.
|
||||
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.
|
||||
Tweet/post: claim as node, author, concepts mentioned.
|
||||
@@ -196,21 +204,40 @@ Image files: use vision to understand what the image IS — do not just OCR.
|
||||
Research figure: what it demonstrates, method, result.
|
||||
Handwritten/whiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS.
|
||||
|
||||
DEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges — indirect deps,
|
||||
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**
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
|
||||
Wait for all subagents. For each result:
|
||||
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
|
||||
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk — do not abort
|
||||
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
|
||||
|
||||
If more than half the chunks failed, stop and tell the user.
|
||||
|
||||
@@ -252,12 +279,12 @@ merged = {
|
||||
'output_tokens': new.get('output_tokens', 0),
|
||||
}
|
||||
Path('.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
|
||||
print(f'Extraction complete — {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
|
||||
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
|
||||
"
|
||||
```
|
||||
Clean up temp files: `rm -f .graphify_cached.json .graphify_uncached.txt .graphify_semantic_new.json`
|
||||
|
||||
#### Part C — Merge AST + semantic into final extraction
|
||||
#### Part C - Merge AST + semantic into final extraction
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
@@ -289,10 +316,10 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
"
|
||||
```
|
||||
|
||||
### Step 4 — Build graph, cluster, analyze, generate outputs
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
```bash
|
||||
mkdir -p .graphify
|
||||
mkdir -p graphify-out
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
@@ -312,12 +339,12 @@ tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('
|
||||
gods = god_nodes(G)
|
||||
surprises = surprising_connections(G, communities)
|
||||
labels = {cid: 'Community ' + str(cid) for cid in communities}
|
||||
# Placeholder questions — regenerated with real labels in Step 5
|
||||
# Placeholder questions - regenerated with real labels in Step 5
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
Path('.graphify/GRAPH_REPORT.md').write_text(report)
|
||||
to_json(G, communities, '.graphify/graph.json')
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
to_json(G, communities, 'graphify-out/graph.json')
|
||||
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -328,18 +355,18 @@ analysis = {
|
||||
}
|
||||
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
if G.number_of_nodes() == 0:
|
||||
print('ERROR: Graph is empty — extraction produced no nodes.')
|
||||
print('ERROR: Graph is empty - extraction produced no nodes.')
|
||||
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
|
||||
raise SystemExit(1)
|
||||
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
|
||||
"
|
||||
```
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened — do not proceed to labeling or visualization.
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
|
||||
### Step 5 — Label communities
|
||||
### Step 5 - Label communities
|
||||
|
||||
Read `.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
|
||||
|
||||
@@ -363,14 +390,14 @@ communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
|
||||
# LABELS — replace these with the names you chose above
|
||||
# LABELS - replace these with the names you chose above
|
||||
labels = LABELS_DICT
|
||||
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
Path('.graphify/GRAPH_REPORT.md').write_text(report)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
|
||||
print('Report updated with community labels')
|
||||
"
|
||||
@@ -379,9 +406,9 @@ 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 (default) + optional HTML
|
||||
|
||||
**Always generate the Obsidian vault** — it is the primary visualization. Skip only if `--no-viz`.
|
||||
**Always generate the Obsidian vault and HTML** - they are the primary visualizations. Skip both if `--no-viz` (report + JSON only).
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
@@ -399,26 +426,26 @@ communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
labels = {int(k): v for k, v in labels_raw.items()}
|
||||
|
||||
n = to_obsidian(G, communities, '.graphify/obsidian', community_labels=labels or None, cohesion=cohesion)
|
||||
print(f'Obsidian vault: {n} notes in .graphify/obsidian/')
|
||||
n = to_obsidian(G, communities, 'graphify-out/obsidian', community_labels=labels or None, cohesion=cohesion)
|
||||
print(f'Obsidian vault: {n} notes in graphify-out/obsidian/')
|
||||
|
||||
to_canvas(G, communities, '.graphify/obsidian/graph.canvas', community_labels=labels or None)
|
||||
print('Canvas: .graphify/obsidian/graph.canvas — open in Obsidian for structured community layout')
|
||||
to_canvas(G, communities, 'graphify-out/obsidian/graph.canvas', community_labels=labels or None)
|
||||
print('Canvas: graphify-out/obsidian/graph.canvas - open in Obsidian for structured community layout')
|
||||
print()
|
||||
print('Open .graphify/obsidian/ as a vault in Obsidian.')
|
||||
print(' Graph view — nodes colored by community (set automatically)')
|
||||
print(' graph.canvas — structured layout with communities as groups')
|
||||
print(' _COMMUNITY_* — overview notes with cohesion scores and dataview queries')
|
||||
print('Open graphify-out/obsidian/ as a vault in Obsidian.')
|
||||
print(' Graph view - nodes colored by community (set automatically)')
|
||||
print(' graph.canvas - structured layout with communities as groups')
|
||||
print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries')
|
||||
"
|
||||
```
|
||||
|
||||
**Only if `--html` flag was passed**, also generate pyvis HTML:
|
||||
Also generate the HTML graph (always, unless `--no-viz`):
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import generate_html
|
||||
from graphify.export import to_html
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
@@ -430,16 +457,16 @@ communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
labels = {int(k): v for k, v in labels_raw.items()}
|
||||
|
||||
if G.number_of_nodes() > 5000:
|
||||
print(f'Graph has {G.number_of_nodes()} nodes — too large for pyvis. Use Obsidian vault instead.')
|
||||
print(f'Graph has {G.number_of_nodes()} nodes - too large for HTML viz. Use Obsidian vault instead.')
|
||||
else:
|
||||
generate_html(G, communities, '.graphify/graph.html', community_labels=labels or None)
|
||||
print('graph.html written')
|
||||
to_html(G, communities, 'graphify-out/graph.html', community_labels=labels or None)
|
||||
print('graph.html written - open in any browser, no server needed')
|
||||
"
|
||||
```
|
||||
|
||||
### Step 7 — Neo4j export (only if --neo4j or --neo4j-push flag)
|
||||
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
|
||||
|
||||
**If `--neo4j`** — generate a Cypher file for manual import:
|
||||
**If `--neo4j`** - generate a Cypher file for manual import:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
@@ -449,12 +476,12 @@ from graphify.export import to_cypher
|
||||
from pathlib import Path
|
||||
|
||||
G = build_from_json(json.loads(Path('.graphify_extract.json').read_text()))
|
||||
to_cypher(G, '.graphify/cypher.txt')
|
||||
print('cypher.txt written — import with: cypher-shell < .graphify/cypher.txt')
|
||||
to_cypher(G, 'graphify-out/cypher.txt')
|
||||
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:
|
||||
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
@@ -474,9 +501,9 @@ print(f'Pushed to Neo4j: {result[\"nodes\"]} nodes, {result[\"edges\"]} edges')
|
||||
"
|
||||
```
|
||||
|
||||
Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE — safe to re-run without creating duplicates.
|
||||
Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.
|
||||
|
||||
### Step 7b — SVG export (only if --svg flag)
|
||||
### Step 7b - SVG export (only if --svg flag)
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
@@ -493,19 +520,35 @@ G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
labels = {int(k): v for k, v in labels_raw.items()}
|
||||
|
||||
to_svg(G, communities, '.graphify/graph.svg', community_labels=labels or None)
|
||||
print('graph.svg written — embeds in Obsidian, Notion, GitHub READMEs')
|
||||
to_svg(G, communities, 'graphify-out/graph.svg', community_labels=labels or None)
|
||||
print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
|
||||
"
|
||||
```
|
||||
|
||||
### Step 7c — SVG export already covered in Step 7b above
|
||||
|
||||
_(No separate --obsidian flag — Obsidian vault is always generated in Step 6 by default.)_
|
||||
|
||||
### Step 7d — MCP server (only if --mcp flag)
|
||||
### Step 7c - GraphML export (only if --graphml flag)
|
||||
|
||||
```bash
|
||||
python3 -m graphify.serve .graphify/graph.json
|
||||
python3 -c "
|
||||
import json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_graphml
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
|
||||
to_graphml(G, communities, 'graphify-out/graph.graphml')
|
||||
print('graph.graphml written - open in Gephi, yEd, or any GraphML tool')
|
||||
"
|
||||
```
|
||||
|
||||
### Step 7d - MCP server (only if --mcp flag)
|
||||
|
||||
```bash
|
||||
python3 -m graphify.serve graphify-out/graph.json
|
||||
```
|
||||
|
||||
This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live.
|
||||
@@ -516,13 +559,33 @@ To configure in Claude Desktop, add to `claude_desktop_config.json`:
|
||||
"mcpServers": {
|
||||
"graphify": {
|
||||
"command": "python3",
|
||||
"args": ["-m", "graphify.serve", "/absolute/path/to/.graphify/graph.json"]
|
||||
"args": ["-m", "graphify.serve", "/absolute/path/to/graphify-out/graph.json"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 8 — Save manifest, update cost tracker, clean up, and report
|
||||
### Step 8 - Token reduction benchmark (only if total_words > 5000)
|
||||
|
||||
If `total_words` from `.graphify_detect.json` is greater than 5,000, run:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
import json
|
||||
from graphify.benchmark import run_benchmark, print_benchmark
|
||||
from pathlib import Path
|
||||
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
result = run_benchmark('graphify-out/graph.json', corpus_words=detection['total_words'])
|
||||
print_benchmark(result)
|
||||
"
|
||||
```
|
||||
|
||||
Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora.
|
||||
|
||||
---
|
||||
|
||||
### Step 9 - Save manifest, update cost tracker, clean up, and report
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
@@ -540,7 +603,7 @@ extract = json.loads(Path('.graphify_extract.json').read_text())
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
output_tok = extract.get('output_tokens', 0)
|
||||
|
||||
cost_path = Path('.graphify/cost.json')
|
||||
cost_path = Path('graphify-out/cost.json')
|
||||
if cost_path.exists():
|
||||
cost = json.loads(cost_path.read_text())
|
||||
else:
|
||||
@@ -560,32 +623,49 @@ 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/.needs_update 2>/dev/null || true
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Tell the user:
|
||||
```
|
||||
Graph complete. Outputs in .graphify/
|
||||
Graph complete. Outputs are in a hidden folder called graphify-out/ inside the directory you ran this on.
|
||||
|
||||
obsidian/ — open this folder as a vault in Obsidian to explore interactively
|
||||
GRAPH_REPORT.md — full audit report (also readable here in Claude)
|
||||
graph.json — persistent graph, queryable in future sessions with /graphify query
|
||||
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
|
||||
|
||||
To explore: open Obsidian → File → Open Vault → select .graphify/obsidian/
|
||||
What's inside:
|
||||
graphify-out/obsidian/ - open this folder as a vault in Obsidian (File > Open Vault)
|
||||
graphify-out/GRAPH_REPORT.md - full audit report, also readable here in Claude
|
||||
graphify-out/graph.json - persistent graph, query it later with /graphify query "..."
|
||||
|
||||
Full path: PATH_TO_DIR/graphify-out/
|
||||
```
|
||||
|
||||
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
|
||||
|
||||
Then paste these sections from GRAPH_REPORT.md directly into the chat:
|
||||
- God Nodes
|
||||
- Surprising Connections
|
||||
- Suggested Questions
|
||||
|
||||
Do NOT paste the full report — just those three sections. Keep it concise.
|
||||
Do NOT paste the full report - just those three sections. Keep it concise.
|
||||
|
||||
Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:
|
||||
|
||||
> "The most interesting question this graph can answer: **[question]**. Want me to trace it?"
|
||||
|
||||
If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report.
|
||||
|
||||
The graph is the map. Your job after the pipeline is to be the guide.
|
||||
|
||||
---
|
||||
|
||||
## For --update (incremental re-extraction)
|
||||
|
||||
Use when you've added or modified files since the last run. Only re-extracts changed files — saves tokens and time.
|
||||
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
@@ -596,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)
|
||||
@@ -603,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 "
|
||||
@@ -615,7 +716,7 @@ import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
# Load existing graph
|
||||
existing_data = json.loads(Path('.graphify/graph.json').read_text())
|
||||
existing_data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
G_existing = json_graph.node_link_graph(existing_data, edges='links')
|
||||
|
||||
# Load new extraction
|
||||
@@ -625,11 +726,6 @@ G_new = build_from_json(new_extraction)
|
||||
# Merge: new nodes/edges into existing graph
|
||||
G_existing.update(G_new)
|
||||
print(f'Merged: {G_existing.number_of_nodes()} nodes, {G_existing.number_of_edges()} edges')
|
||||
|
||||
# Save manifest so next --update knows what changed
|
||||
from graphify.detect import save_manifest, detect
|
||||
detect_result = json.loads(Path('.graphify_detect.json').read_text())
|
||||
save_manifest(detect_result['files'])
|
||||
"
|
||||
```
|
||||
|
||||
@@ -662,14 +758,14 @@ if old_data:
|
||||
"
|
||||
```
|
||||
|
||||
Before the merge step, save the old graph: `cp .graphify/graph.json .graphify_old.json`
|
||||
Before the merge step, save the old graph: `cp graphify-out/graph.json .graphify_old.json`
|
||||
Clean up after: `rm -f .graphify_old.json`
|
||||
|
||||
---
|
||||
|
||||
## For --cluster-only
|
||||
|
||||
Skip Steps 1–3. Load the existing graph from `.graphify/graph.json` and re-run clustering:
|
||||
Skip Steps 1–3. Load the existing graph from `graphify-out/graph.json` and re-run clustering:
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
@@ -682,7 +778,7 @@ from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('.graphify/graph.json').read_text())
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None,
|
||||
@@ -696,8 +792,8 @@ surprises = surprising_connections(G, communities)
|
||||
labels = {cid: 'Community ' + str(cid) for cid in communities}
|
||||
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, '.')
|
||||
Path('.graphify/GRAPH_REPORT.md').write_text(report)
|
||||
to_json(G, communities, '.graphify/graph.json')
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
to_json(G, communities, 'graphify-out/graph.json')
|
||||
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -710,26 +806,37 @@ print(f'Re-clustered: {len(communities)} communities')
|
||||
"
|
||||
```
|
||||
|
||||
Then run Steps 5–8 as normal (label communities, generate viz, clean up, report).
|
||||
Then run Steps 5–9 as normal (label communities, generate viz, benchmark, clean up, report).
|
||||
|
||||
---
|
||||
|
||||
## For /graphify query
|
||||
|
||||
Two traversal modes — choose based on the question:
|
||||
Two traversal modes - choose based on the question:
|
||||
|
||||
| Mode | Flag | Best for |
|
||||
|------|------|----------|
|
||||
| BFS (default) | _(none)_ | "What is X connected to?" — broad context, nearest neighbors first |
|
||||
| DFS | `--dfs` | "How does X reach Y?" — trace a specific chain or dependency path |
|
||||
| BFS (default) | _(none)_ | "What is X connected to?" - broad context, nearest neighbors first |
|
||||
| DFS | `--dfs` | "How does X reach Y?" - trace a specific chain or dependency path |
|
||||
|
||||
Load `.graphify/graph.json`, then:
|
||||
First check the graph exists:
|
||||
```bash
|
||||
python3 -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
raise SystemExit(1)
|
||||
"
|
||||
```
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
Load `graphify-out/graph.json`, then:
|
||||
|
||||
1. Find the 1-3 nodes whose label best matches key terms in the question.
|
||||
2. Run the appropriate traversal from each starting node.
|
||||
3. Read the subgraph — node labels, edge relations, confidence tags, source locations.
|
||||
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
|
||||
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
|
||||
5. If the graph lacks enough information, say so — do not hallucinate edges.
|
||||
5. If the graph lacks enough information, say so - do not hallucinate edges.
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
@@ -738,7 +845,7 @@ from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('.graphify/graph.json').read_text())
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
question = 'QUESTION'
|
||||
@@ -813,7 +920,7 @@ for u, v in subgraph_edges:
|
||||
|
||||
output = '\n'.join(lines)
|
||||
if len(output) > char_budget:
|
||||
output = output[:char_budget] + f'\n... (truncated at ~{token_budget} token budget — use --budget N for more)'
|
||||
output = output[:char_budget] + f'\n... (truncated at ~{token_budget} token budget - use --budget N for more)'
|
||||
print(output)
|
||||
"
|
||||
```
|
||||
@@ -829,11 +936,11 @@ from pathlib import Path
|
||||
save_query_result(
|
||||
question='QUESTION',
|
||||
answer='ANSWER',
|
||||
memory_dir=Path('.graphify/memory'),
|
||||
memory_dir=Path('graphify-out/memory'),
|
||||
query_type='query',
|
||||
source_nodes=SOURCE_NODES, # list of node labels cited, or []
|
||||
)
|
||||
print('Query result saved to .graphify/memory/')
|
||||
print('Query result saved to graphify-out/memory/')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -845,6 +952,17 @@ Replace `QUESTION` with the question, `ANSWER` with your full answer text, `SOUR
|
||||
|
||||
Find the shortest path between two named concepts in the graph.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
python3 -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
raise SystemExit(1)
|
||||
"
|
||||
```
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
import json, sys
|
||||
@@ -852,7 +970,7 @@ import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('.graphify/graph.json').read_text())
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
a_term = 'NODE_A'
|
||||
@@ -893,7 +1011,7 @@ except nx.NodeNotFound as e:
|
||||
"
|
||||
```
|
||||
|
||||
Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then explain the path in plain language — what each hop means, why it's significant.
|
||||
Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then explain the path in plain language - what each hop means, why it's significant.
|
||||
|
||||
After writing the explanation, save it back:
|
||||
|
||||
@@ -904,11 +1022,11 @@ from pathlib import Path
|
||||
save_query_result(
|
||||
question='Path from NODE_A to NODE_B',
|
||||
answer='ANSWER',
|
||||
memory_dir=Path('.graphify/memory'),
|
||||
memory_dir=Path('graphify-out/memory'),
|
||||
query_type='path_query',
|
||||
source_nodes=PATH_NODES, # list of node labels on the path
|
||||
)
|
||||
print('Path result saved to .graphify/memory/')
|
||||
print('Path result saved to graphify-out/memory/')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -916,7 +1034,18 @@ print('Path result saved to .graphify/memory/')
|
||||
|
||||
## For /graphify explain
|
||||
|
||||
Give a plain-language explanation of a single node — everything connected to it.
|
||||
Give a plain-language explanation of a single node - everything connected to it.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
python3 -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
raise SystemExit(1)
|
||||
"
|
||||
```
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
python3 -c "
|
||||
@@ -925,7 +1054,7 @@ import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('.graphify/graph.json').read_text())
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
term = 'NODE_NAME'
|
||||
@@ -970,11 +1099,11 @@ from pathlib import Path
|
||||
save_query_result(
|
||||
question='Explain NODE_NAME',
|
||||
answer='ANSWER',
|
||||
memory_dir=Path('.graphify/memory'),
|
||||
memory_dir=Path('graphify-out/memory'),
|
||||
query_type='explain',
|
||||
source_nodes=['NODE_NAME'],
|
||||
)
|
||||
print('Explanation saved to .graphify/memory/')
|
||||
print('Explanation saved to graphify-out/memory/')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -1002,7 +1131,7 @@ except RuntimeError as e:
|
||||
"
|
||||
```
|
||||
|
||||
Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong — do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph.
|
||||
Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph.
|
||||
|
||||
Supported URL types (auto-detected):
|
||||
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
|
||||
@@ -1015,15 +1144,54 @@ Supported URL types (auto-detected):
|
||||
|
||||
## For --watch
|
||||
|
||||
Start a background watcher that monitors a folder and auto-reruns `--update` when files change.
|
||||
Start a background watcher that monitors a folder and auto-updates the graph when files change.
|
||||
|
||||
```bash
|
||||
python3 -m graphify.watch INPUT_PATH --debounce 3
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the folder to watch. Every time a supported file is added or modified, graphify waits `debounce` seconds (default 3) after the last change, then runs the `--update` pipeline automatically. Press Ctrl+C to stop.
|
||||
Replace INPUT_PATH with the folder to watch. Behavior depends on what changed:
|
||||
|
||||
For the personal inspo use case: leave this running in a terminal. Drop tweets, screenshots, papers, and notes into the folder throughout the day — the graph updates itself.
|
||||
- **Code files only (.py, .ts, .go, etc.):** re-runs AST extraction + rebuild + cluster immediately, no LLM needed. `graph.json` and `GRAPH_REPORT.md` are updated automatically.
|
||||
- **Docs, papers, or images:** writes a `graphify-out/needs_update` flag and prints a notification to run `/graphify --update` (LLM semantic re-extraction required).
|
||||
|
||||
Debounce (default 3s): waits until file activity stops before triggering, so a wave of parallel agent writes doesn't trigger a rebuild per file.
|
||||
|
||||
Press Ctrl+C to stop.
|
||||
|
||||
For agentic workflows: run `--watch` in a background terminal. Code changes from agent waves are picked up automatically between waves. If agents are also writing docs or notes, you'll need a manual `/graphify --update` after those waves.
|
||||
|
||||
---
|
||||
|
||||
## For git commit hook
|
||||
|
||||
Install a post-commit hook that auto-rebuilds the graph after every commit. No background process needed - triggers once per commit, works with any editor.
|
||||
|
||||
```bash
|
||||
graphify hook install # install
|
||||
graphify hook uninstall # remove
|
||||
graphify hook status # check
|
||||
```
|
||||
|
||||
After every `git commit`, the hook detects which code files changed (via `git diff HEAD~1`), re-runs AST extraction on those files, and rebuilds `graph.json` and `GRAPH_REPORT.md`. Doc/image changes are ignored by the hook - run `/graphify --update` manually for those.
|
||||
|
||||
If a post-commit hook already exists, graphify appends to it rather than replacing it.
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -1032,5 +1200,5 @@ For the personal inspo use case: leave this running in a terminal. Drop tweets,
|
||||
- Never invent an edge. If unsure, use AMBIGUOUS.
|
||||
- Never skip the corpus check warning.
|
||||
- Always show token cost in the report.
|
||||
- Never hide cohesion scores behind symbols — show the raw number.
|
||||
- Never run pyvis on a graph with more than 5,000 nodes without warning the user.
|
||||
- Never hide cohesion scores behind symbols - show the raw number.
|
||||
- Never run HTML viz on a graph with more than 5,000 nodes without warning the user.
|
||||
@@ -1,62 +0,0 @@
|
||||
# Graph Report — /home/safi/graphify_test/httpx (2026-04-03)
|
||||
|
||||
## Corpus Check
|
||||
- 6 files · ~2,800 words
|
||||
- Verdict: corpus is large enough that graph structure adds value.
|
||||
|
||||
---
|
||||
> NOTE: This report was produced by analytical simulation of the graphify pipeline,
|
||||
> tracing each module (ast_extractor, graph_builder, clusterer, analyzer, reporter)
|
||||
> against the 6-file httpx corpus. Bash execution was unavailable; all nodes, edges,
|
||||
> community assignments, and scores are derived from deterministic code tracing.
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
- ~95 nodes · ~130 edges · 4 communities detected (estimated)
|
||||
- Extraction: ~100% EXTRACTED · 0% INFERRED · 0% AMBIGUOUS
|
||||
- Token cost: 0 input · 0 output
|
||||
|
||||
## God Nodes (most connected — your core abstractions)
|
||||
|
||||
1. `client.py` — ~28 edges
|
||||
2. `models.py` — ~22 edges
|
||||
3. `transport.py` — ~20 edges
|
||||
4. `exceptions.py` — ~18 edges
|
||||
5. `BaseClient` — ~15 edges
|
||||
6. `auth.py` — ~14 edges
|
||||
7. `Response` — ~12 edges
|
||||
8. `Client` — ~10 edges
|
||||
9. `AsyncClient` — ~10 edges
|
||||
10. `utils.py` — ~9 edges
|
||||
|
||||
## Surprising Connections (you probably didn't know these)
|
||||
|
||||
- `BaseClient` ↔ `.auth_flow()` [EXTRACTED]
|
||||
/home/safi/graphify_test/httpx/client.py ↔ /home/safi/graphify_test/httpx/auth.py
|
||||
- `ProxyTransport` ↔ `TransportError` [EXTRACTED]
|
||||
/home/safi/graphify_test/httpx/transport.py ↔ /home/safi/graphify_test/httpx/exceptions.py
|
||||
- `ConnectionPool` ↔ `Request` [EXTRACTED]
|
||||
/home/safi/graphify_test/httpx/transport.py ↔ /home/safi/graphify_test/httpx/models.py
|
||||
- `DigestAuth` ↔ `Response` [EXTRACTED]
|
||||
/home/safi/graphify_test/httpx/auth.py ↔ /home/safi/graphify_test/httpx/models.py
|
||||
- `utils.py` ↔ `Cookies` [EXTRACTED]
|
||||
/home/safi/graphify_test/httpx/utils.py ↔ /home/safi/graphify_test/httpx/models.py
|
||||
|
||||
## Communities
|
||||
|
||||
### Community 0 — "Core HTTP Client"
|
||||
Cohesion: 0.14
|
||||
Nodes (12): client.py, BaseClient, Client, AsyncClient, .send(), .request(), .get(), .post(), .close(), .aclose(), Timeout, Limits
|
||||
|
||||
### Community 1 — "Request/Response Models"
|
||||
Cohesion: 0.18
|
||||
Nodes (10): models.py, Request, Response, URL, Headers, Cookies, .read(), .json(), .raise_for_status(), .cookies
|
||||
|
||||
### Community 2 — "Exception Hierarchy"
|
||||
Cohesion: 0.10
|
||||
Nodes (20): exceptions.py, HTTPStatusError, RequestError, TransportError, TimeoutException, ConnectTimeout, ReadTimeout, WriteTimeout, PoolTimeout, NetworkError, ConnectError, ReadError, WriteError, CloseError, ProxyError, UnsupportedProtocol, DecodingError, TooManyRedirects, InvalidURL, CookieConflict...
|
||||
|
||||
### Community 3 — "Transport & Auth"
|
||||
Cohesion: 0.08
|
||||
Nodes (18): transport.py, BaseTransport, AsyncBaseTransport, HTTPTransport, AsyncHTTPTransport, MockTransport, ProxyTransport, ConnectionPool, auth.py, Auth, BasicAuth, DigestAuth, BearerAuth, NetRCAuth, .handle_request(), .auth_flow(), utils.py, .obfuscate_sensitive_headers()...
|
||||
@@ -1,147 +0,0 @@
|
||||
"""
|
||||
Graphify evaluation script — Transformer/Attention paper corpus.
|
||||
Runs the full pipeline with a simulated Claude extraction JSON.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
# Make sure we can import graphify from src/
|
||||
sys.path.insert(0, str(Path(__file__).parent / "src"))
|
||||
|
||||
from graphify import detector, ast_extractor, graph_builder, clusterer, analyzer, reporter
|
||||
|
||||
# ── 1. Detection ──────────────────────────────────────────────────────────────
|
||||
RAW = Path("/home/safi/graphify_test/raw")
|
||||
detection = detector.detect(RAW)
|
||||
print("=== Detection ===")
|
||||
print(json.dumps(detection, indent=2))
|
||||
|
||||
# ── 2. AST extraction from .py files ─────────────────────────────────────────
|
||||
py_files = [Path(f) for f in detection["files"].get("code", [])]
|
||||
ast_result = ast_extractor.extract(py_files) if py_files else {"nodes": [], "edges": []}
|
||||
print(f"\n=== AST extraction: {len(ast_result['nodes'])} nodes, {len(ast_result['edges'])} edges ===")
|
||||
|
||||
# ── 3. Simulated Claude extraction (realistic paper knowledge graph) ──────────
|
||||
SOURCE_MD = str(RAW / "attention_notes.md")
|
||||
SOURCE_CFG = str(RAW / "config.md")
|
||||
|
||||
simulated_extraction = {
|
||||
"nodes": [
|
||||
# Core architecture concepts
|
||||
{"id": "transformer", "label": "Transformer", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3"},
|
||||
{"id": "encoder_layer", "label": "EncoderLayer", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3.1"},
|
||||
{"id": "decoder_layer", "label": "DecoderLayer", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3.1"},
|
||||
# Attention mechanism
|
||||
{"id": "multi_head_attention", "label": "MultiHeadAttention", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3.2"},
|
||||
{"id": "scaled_dot_product", "label": "ScaledDotProductAttention", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3.2.1"},
|
||||
# Sub-components
|
||||
{"id": "feed_forward", "label": "FeedForward", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3.3"},
|
||||
{"id": "layer_norm", "label": "LayerNorm", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3.1"},
|
||||
{"id": "positional_encoding", "label": "PositionalEncoding", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3.5"},
|
||||
# Hyperparameters — from config.md
|
||||
{"id": "d_model", "label": "d_model", "file_type": "document", "source_file": SOURCE_CFG, "source_location": "L3"},
|
||||
{"id": "num_heads", "label": "num_heads", "file_type": "document", "source_file": SOURCE_CFG, "source_location": "L4"},
|
||||
{"id": "dropout", "label": "dropout", "file_type": "document", "source_file": SOURCE_CFG, "source_location": "L7"},
|
||||
],
|
||||
"edges": [
|
||||
# Transformer contains encoder and decoder stacks
|
||||
{"source": "transformer", "target": "encoder_layer", "relation": "contains", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
|
||||
{"source": "transformer", "target": "decoder_layer", "relation": "contains", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
|
||||
# EncoderLayer uses multi-head attention and feed-forward
|
||||
{"source": "encoder_layer", "target": "multi_head_attention", "relation": "uses", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
|
||||
{"source": "encoder_layer", "target": "feed_forward", "relation": "uses", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
|
||||
{"source": "encoder_layer", "target": "layer_norm", "relation": "applies", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
|
||||
# DecoderLayer uses multi-head attention (self + cross) and feed-forward
|
||||
{"source": "decoder_layer", "target": "multi_head_attention", "relation": "uses", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
|
||||
{"source": "decoder_layer", "target": "feed_forward", "relation": "uses", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
|
||||
{"source": "decoder_layer", "target": "layer_norm", "relation": "applies", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
|
||||
# MultiHeadAttention implements ScaledDotProduct internally
|
||||
{"source": "multi_head_attention", "target": "scaled_dot_product", "relation": "implements", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
|
||||
# Hyperparameter relationships — from config.md to architecture nodes
|
||||
{"source": "multi_head_attention", "target": "d_model", "relation": "parameterized_by", "confidence": "EXTRACTED", "source_file": SOURCE_CFG, "weight": 1.0},
|
||||
{"source": "multi_head_attention", "target": "num_heads", "relation": "parameterized_by", "confidence": "EXTRACTED", "source_file": SOURCE_CFG, "weight": 1.0},
|
||||
{"source": "scaled_dot_product", "target": "d_model", "relation": "scales_by", "confidence": "INFERRED", "source_file": SOURCE_MD, "weight": 0.8},
|
||||
{"source": "feed_forward", "target": "d_model", "relation": "parameterized_by", "confidence": "EXTRACTED", "source_file": SOURCE_CFG, "weight": 1.0},
|
||||
# Positional encoding connects to transformer input (cross-community link)
|
||||
{"source": "positional_encoding", "target": "transformer", "relation": "feeds_into", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
|
||||
{"source": "positional_encoding", "target": "d_model", "relation": "dimensioned_by", "confidence": "INFERRED", "source_file": SOURCE_MD, "weight": 0.8},
|
||||
# Dropout applied across sub-layers — ambiguous which specific sublayer
|
||||
{"source": "dropout", "target": "multi_head_attention", "relation": "regularizes", "confidence": "AMBIGUOUS", "source_file": SOURCE_CFG, "weight": 0.6},
|
||||
{"source": "dropout", "target": "feed_forward", "relation": "regularizes", "confidence": "AMBIGUOUS", "source_file": SOURCE_CFG, "weight": 0.6},
|
||||
# Cross-community bridge: LayerNorm and PositionalEncoding both affect d_model scale
|
||||
{"source": "layer_norm", "target": "positional_encoding", "relation": "operates_at_same_scale_as", "confidence": "INFERRED", "source_file": SOURCE_MD, "weight": 0.7},
|
||||
# Encoder-Decoder cross-attention: DecoderLayer attends to encoder output
|
||||
{"source": "decoder_layer", "target": "encoder_layer", "relation": "cross_attends_to", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
|
||||
],
|
||||
"input_tokens": 3200,
|
||||
"output_tokens": 820,
|
||||
}
|
||||
|
||||
# ── 4. Merge AST + simulated Claude extraction ────────────────────────────────
|
||||
all_extractions = [simulated_extraction]
|
||||
if ast_result["nodes"]:
|
||||
all_extractions.append(ast_result)
|
||||
|
||||
G = graph_builder.build(all_extractions)
|
||||
print(f"\n=== Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges ===")
|
||||
|
||||
# ── 5. Community detection ────────────────────────────────────────────────────
|
||||
communities = clusterer.cluster(G)
|
||||
cohesion = clusterer.score_all(G, communities)
|
||||
print(f"\n=== Communities: {len(communities)} detected ===")
|
||||
for cid, nodes in communities.items():
|
||||
node_labels = [G.nodes[n].get("label", n) for n in nodes]
|
||||
print(f" Community {cid} ({len(nodes)} nodes): {node_labels}")
|
||||
print(f" Cohesion: {cohesion[cid]}")
|
||||
|
||||
# ── 6. Analysis ───────────────────────────────────────────────────────────────
|
||||
god_node_list = analyzer.god_nodes(G, top_n=10)
|
||||
print(f"\n=== God Nodes ===")
|
||||
for g in god_node_list:
|
||||
print(f" {g['label']}: {g['edges']} edges")
|
||||
|
||||
surprise_list = analyzer.surprising_connections(G, communities=communities, top_n=5)
|
||||
print(f"\n=== Surprising Connections: {len(surprise_list)} found ===")
|
||||
for s in surprise_list:
|
||||
print(f" {s['source']} <-> {s['target']} [{s['confidence']}]: {s['relation']}")
|
||||
print(f" Note: {s.get('note', 'cross-file')}")
|
||||
|
||||
# ── 7. Community labels (hand-crafted for accuracy) ───────────────────────────
|
||||
# We label based on which nodes ended up in which community
|
||||
community_labels = {}
|
||||
for cid, nodes in communities.items():
|
||||
node_labels_set = {G.nodes[n].get("label", n) for n in nodes}
|
||||
if "MultiHeadAttention" in node_labels_set or "ScaledDotProductAttention" in node_labels_set:
|
||||
community_labels[cid] = "Attention Mechanism"
|
||||
elif "Transformer" in node_labels_set or "EncoderLayer" in node_labels_set:
|
||||
community_labels[cid] = "Encoder-Decoder Architecture"
|
||||
elif "d_model" in node_labels_set or "num_heads" in node_labels_set or "dropout" in node_labels_set:
|
||||
community_labels[cid] = "Hyperparameters & Configuration"
|
||||
elif "PositionalEncoding" in node_labels_set:
|
||||
community_labels[cid] = "Positional Encoding & Embedding"
|
||||
elif any(label.endswith(".py") or "()" in label for label in node_labels_set):
|
||||
community_labels[cid] = "Code Implementation"
|
||||
else:
|
||||
community_labels[cid] = f"Cluster {cid}"
|
||||
|
||||
token_cost = {"input": simulated_extraction["input_tokens"], "output": simulated_extraction["output_tokens"]}
|
||||
|
||||
# ── 8. Report ─────────────────────────────────────────────────────────────────
|
||||
report = reporter.generate(
|
||||
G=G,
|
||||
communities=communities,
|
||||
cohesion_scores=cohesion,
|
||||
community_labels=community_labels,
|
||||
god_node_list=god_node_list,
|
||||
surprise_list=surprise_list,
|
||||
detection_result=detection,
|
||||
token_cost=token_cost,
|
||||
root=str(RAW),
|
||||
)
|
||||
|
||||
out_path = Path("/tmp/GRAPH_REPORT_attention.md")
|
||||
out_path.write_text(report)
|
||||
print(f"\n=== Report written to {out_path} ===")
|
||||
print(report)
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "sample", "label": "sample.ts", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L1"}, {"id": "sample_httpclient", "label": "HttpClient", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L3"}, {"id": "sample_httpclient_constructor", "label": ".constructor()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L6"}, {"id": "sample_httpclient_get", "label": ".get()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L10"}, {"id": "sample_httpclient_post", "label": ".post()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L14"}, {"id": "sample_buildheaders", "label": "buildHeaders()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L19"}], "edges": [{"source": "sample", "target": "models", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L1", "weight": 1.0}, {"source": "sample", "target": "sample_httpclient", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L3", "weight": 1.0}, {"source": "sample_httpclient", "target": "sample_httpclient_constructor", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L6", "weight": 1.0}, {"source": "sample_httpclient", "target": "sample_httpclient_get", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L10", "weight": 1.0}, {"source": "sample_httpclient", "target": "sample_httpclient_post", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L14", "weight": 1.0}, {"source": "sample", "target": "sample_buildheaders", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L19", "weight": 1.0}, {"source": "sample_httpclient_post", "target": "sample_httpclient_get", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L15", "weight": 0.8}]}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "sample", "label": "sample.go", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L1"}, {"id": "sample_server", "label": "Server", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L8"}, {"id": "sample_newserver", "label": "NewServer()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L12"}, {"id": "sample_server_start", "label": ".Start()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L16"}, {"id": "sample_server_stop", "label": ".Stop()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L20"}, {"id": "sample_main", "label": "main()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L24"}], "edges": [{"source": "sample", "target": "fmt", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L4", "weight": 1.0}, {"source": "sample", "target": "http", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L5", "weight": 1.0}, {"source": "sample", "target": "sample_server", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L8", "weight": 1.0}, {"source": "sample", "target": "sample_newserver", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L12", "weight": 1.0}, {"source": "sample_server", "target": "sample_server_start", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L16", "weight": 1.0}, {"source": "sample_server", "target": "sample_server_stop", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L20", "weight": 1.0}, {"source": "sample", "target": "sample_main", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L24", "weight": 1.0}, {"source": "sample_main", "target": "sample_newserver", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L25", "weight": 0.8}, {"source": "sample_main", "target": "sample_server_start", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L26", "weight": 0.8}]}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "sample_calls", "label": "sample_calls.py", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L1"}, {"id": "sample_calls_compute_score", "label": "compute_score()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L4"}, {"id": "sample_calls_normalize", "label": "normalize()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L8"}, {"id": "sample_calls_run_analysis", "label": "run_analysis()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L12"}, {"id": "sample_calls_analyzer", "label": "Analyzer", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L17"}, {"id": "sample_calls_analyzer_process", "label": ".process()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L18"}, {"id": "sample_calls_analyzer_score", "label": ".score()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L21"}, {"id": "sample_calls_analyzer_full_pipeline", "label": ".full_pipeline()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L24"}], "edges": [{"source": "sample_calls", "target": "sample_calls_compute_score", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L4", "weight": 1.0}, {"source": "sample_calls", "target": "sample_calls_normalize", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L8", "weight": 1.0}, {"source": "sample_calls", "target": "sample_calls_run_analysis", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L12", "weight": 1.0}, {"source": "sample_calls", "target": "sample_calls_analyzer", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L17", "weight": 1.0}, {"source": "sample_calls_analyzer", "target": "sample_calls_analyzer_process", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L18", "weight": 1.0}, {"source": "sample_calls_analyzer", "target": "sample_calls_analyzer_score", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L21", "weight": 1.0}, {"source": "sample_calls_analyzer", "target": "sample_calls_analyzer_full_pipeline", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L24", "weight": 1.0}, {"source": "sample_calls_run_analysis", "target": "sample_calls_compute_score", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L13", "weight": 0.8}, {"source": "sample_calls_run_analysis", "target": "sample_calls_normalize", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L14", "weight": 0.8}, {"source": "sample_calls_analyzer_process", "target": "sample_calls_run_analysis", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L19", "weight": 0.8}, {"source": "sample_calls_analyzer_score", "target": "sample_calls_compute_score", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L22", "weight": 0.8}, {"source": "sample_calls_analyzer_full_pipeline", "target": "sample_calls_analyzer_score", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L25", "weight": 0.8}, {"source": "sample_calls_analyzer_full_pipeline", "target": "sample_calls_normalize", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L26", "weight": 0.8}]}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "sample", "label": "sample.rs", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L1"}, {"id": "sample_graph", "label": "Graph", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L3"}, {"id": "sample_graph_new", "label": ".new()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L8"}, {"id": "sample_graph_add_node", "label": ".add_node()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L12"}, {"id": "sample_graph_add_edge", "label": ".add_edge()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L16"}, {"id": "sample_build_graph", "label": "build_graph()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L21"}], "edges": [{"source": "sample", "target": "hashmap", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L1", "weight": 1.0}, {"source": "sample", "target": "sample_graph", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L3", "weight": 1.0}, {"source": "sample_graph", "target": "sample_graph_new", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L8", "weight": 1.0}, {"source": "sample_graph", "target": "sample_graph_add_node", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L12", "weight": 1.0}, {"source": "sample_graph", "target": "sample_graph_add_edge", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L16", "weight": 1.0}, {"source": "sample", "target": "sample_build_graph", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L21", "weight": 1.0}, {"source": "sample_build_graph", "target": "sample_graph_new", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L22", "weight": 0.8}, {"source": "sample_build_graph", "target": "sample_graph_add_edge", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L24", "weight": 0.8}]}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"nodes": [{"id": "sample", "label": "sample.py", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.py", "source_location": "L1"}, {"id": "sample_transformer", "label": "Transformer", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.py", "source_location": "L1"}, {"id": "sample_transformer_init", "label": ".__init__()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.py", "source_location": "L2"}, {"id": "sample_transformer_forward", "label": ".forward()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.py", "source_location": "L5"}], "edges": [{"source": "sample", "target": "sample_transformer", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.py", "source_location": "L1", "weight": 1.0}, {"source": "sample_transformer", "target": "sample_transformer_init", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.py", "source_location": "L2", "weight": 1.0}, {"source": "sample_transformer", "target": "sample_transformer_forward", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.py", "source_location": "L5", "weight": 1.0}]}
|
||||
Vendored
+1
-1
@@ -1,4 +1,4 @@
|
||||
"""Fixture: functions and methods that call each other — for call-graph extraction tests."""
|
||||
"""Fixture: functions and methods that call each other - for call-graph extraction tests."""
|
||||
|
||||
|
||||
def compute_score(data):
|
||||
|
||||
+51
-7
@@ -4,7 +4,7 @@ import networkx as nx
|
||||
from pathlib import Path
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster
|
||||
from graphify.analyze import god_nodes, surprising_connections, _is_concept_node, graph_diff
|
||||
from graphify.analyze import god_nodes, surprising_connections, _is_concept_node, graph_diff, _surprise_score, _file_category
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
@@ -85,14 +85,58 @@ def test_surprising_connections_single_file_uses_community_bridges():
|
||||
assert len(surprises) > 0
|
||||
|
||||
|
||||
def test_surprising_connections_ambiguous_first():
|
||||
def test_surprising_connections_ambiguous_scores_higher_than_extracted():
|
||||
"""AMBIGUOUS edge should score higher than an otherwise identical EXTRACTED edge."""
|
||||
G = nx.Graph()
|
||||
for nid, label, src in [
|
||||
("a", "Alpha", "repo1/model.py"),
|
||||
("b", "Beta", "repo2/train.py"),
|
||||
("c", "Gamma", "repo1/data.py"),
|
||||
("d", "Delta", "repo2/eval.py"),
|
||||
]:
|
||||
G.add_node(nid, label=label, source_file=src, file_type="code")
|
||||
G.add_edge("a", "b", relation="calls", confidence="AMBIGUOUS", weight=1.0, source_file="repo1/model.py")
|
||||
G.add_edge("c", "d", relation="calls", confidence="EXTRACTED", weight=1.0, source_file="repo1/data.py")
|
||||
communities = {0: ["a", "c"], 1: ["b", "d"]}
|
||||
nc = {"a": 0, "c": 0, "b": 1, "d": 1}
|
||||
score_amb, _ = _surprise_score(G, "a", "b", G.edges["a", "b"], nc, "repo1/model.py", "repo2/train.py")
|
||||
score_ext, _ = _surprise_score(G, "c", "d", G.edges["c", "d"], nc, "repo1/data.py", "repo2/eval.py")
|
||||
assert score_amb > score_ext
|
||||
|
||||
|
||||
def test_surprising_connections_cross_type_scores_higher():
|
||||
"""Code↔paper edge should score higher than code↔code edge."""
|
||||
G = nx.Graph()
|
||||
for nid, label, src in [
|
||||
("a", "Transformer", "code/model.py"),
|
||||
("b", "FlashAttn", "papers/flash.pdf"),
|
||||
("c", "Trainer", "code/train.py"),
|
||||
("d", "Dataset", "code/data.py"),
|
||||
]:
|
||||
G.add_node(nid, label=label, source_file=src, file_type="code")
|
||||
G.add_edge("a", "b", relation="references", confidence="EXTRACTED", weight=1.0, source_file="code/model.py")
|
||||
G.add_edge("c", "d", relation="calls", confidence="EXTRACTED", weight=1.0, source_file="code/train.py")
|
||||
nc = {"a": 0, "b": 1, "c": 0, "d": 0}
|
||||
score_cross, reasons_cross = _surprise_score(G, "a", "b", G.edges["a", "b"], nc, "code/model.py", "papers/flash.pdf")
|
||||
score_same, _ = _surprise_score(G, "c", "d", G.edges["c", "d"], nc, "code/train.py", "code/data.py")
|
||||
assert score_cross > score_same
|
||||
assert any("code" in r and "paper" in r for r in reasons_cross)
|
||||
|
||||
|
||||
def test_surprising_connections_have_why_field():
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
surprises = surprising_connections(G, communities)
|
||||
if len(surprises) >= 2:
|
||||
order = {"AMBIGUOUS": 0, "INFERRED": 1, "EXTRACTED": 2}
|
||||
confidences = [order[s["confidence"]] for s in surprises]
|
||||
assert confidences == sorted(confidences)
|
||||
for s in surprising_connections(G, communities):
|
||||
assert "why" in s
|
||||
assert isinstance(s["why"], str)
|
||||
assert len(s["why"]) > 0
|
||||
|
||||
|
||||
def test_file_category():
|
||||
assert _file_category("model.py") == "code"
|
||||
assert _file_category("flash.pdf") == "paper"
|
||||
assert _file_category("diagram.png") == "image"
|
||||
assert _file_category("notes.md") == "doc"
|
||||
|
||||
|
||||
def test_is_concept_node_empty_source():
|
||||
|
||||
+3
-3
@@ -67,8 +67,8 @@ def test_cached_files(tmp_path, cache_root):
|
||||
|
||||
|
||||
def test_clear_cache(tmp_file, cache_root):
|
||||
"""clear_cache removes all .json files from .graphify/cache/."""
|
||||
"""clear_cache removes all .json files from graphify-out/cache/."""
|
||||
save_cached(tmp_file, {"nodes": [], "edges": []}, root=cache_root)
|
||||
assert len(list((cache_root / ".graphify" / "cache").glob("*.json"))) > 0
|
||||
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) > 0
|
||||
clear_cache(cache_root)
|
||||
assert len(list((cache_root / ".graphify" / "cache").glob("*.json"))) == 0
|
||||
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) == 0
|
||||
@@ -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}"
|
||||
)
|
||||
+74
-1
@@ -3,7 +3,7 @@ import tempfile
|
||||
from pathlib import Path
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster
|
||||
from graphify.export import to_json, to_cypher
|
||||
from graphify.export import to_json, to_cypher, to_graphml, to_html
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
@@ -52,3 +52,76 @@ def test_to_cypher_contains_merge_statements():
|
||||
to_cypher(G, str(out))
|
||||
content = out.read_text()
|
||||
assert "MERGE" in content
|
||||
|
||||
def test_to_graphml_creates_file():
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.graphml"
|
||||
to_graphml(G, communities, str(out))
|
||||
assert out.exists()
|
||||
|
||||
def test_to_graphml_valid_xml():
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.graphml"
|
||||
to_graphml(G, communities, str(out))
|
||||
content = out.read_text()
|
||||
assert "<graphml" in content
|
||||
assert "<node" in content
|
||||
|
||||
def test_to_graphml_has_community_attribute():
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.graphml"
|
||||
to_graphml(G, communities, str(out))
|
||||
content = out.read_text()
|
||||
assert "community" in content
|
||||
|
||||
def test_to_html_creates_file():
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.html"
|
||||
to_html(G, communities, str(out))
|
||||
assert out.exists()
|
||||
|
||||
def test_to_html_contains_visjs():
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.html"
|
||||
to_html(G, communities, str(out))
|
||||
content = out.read_text()
|
||||
assert "vis-network" in content
|
||||
|
||||
def test_to_html_contains_search():
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.html"
|
||||
to_html(G, communities, str(out))
|
||||
content = out.read_text()
|
||||
assert "search" in content.lower()
|
||||
|
||||
def test_to_html_contains_legend_with_labels():
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
labels = {cid: f"Group {cid}" for cid in communities}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.html"
|
||||
to_html(G, communities, str(out), community_labels=labels)
|
||||
content = out.read_text()
|
||||
assert "Group 0" in content
|
||||
|
||||
def test_to_html_contains_nodes_and_edges():
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.html"
|
||||
to_html(G, communities, str(out))
|
||||
content = out.read_text()
|
||||
assert "RAW_NODES" in content
|
||||
assert "RAW_EDGES" in content
|
||||
@@ -106,7 +106,7 @@ def test_calls_no_self_loops():
|
||||
|
||||
|
||||
def test_run_analysis_calls_compute_score():
|
||||
"""run_analysis() calls compute_score() — must appear as a calls edge."""
|
||||
"""run_analysis() calls compute_score() - must appear as a calls edge."""
|
||||
result = extract_python(FIXTURES / "sample_calls.py")
|
||||
calls = {(e["source"], e["target"]) for e in result["edges"] if e["relation"] == "calls"}
|
||||
node_by_label = {n["label"]: n["id"] for n in result["nodes"]}
|
||||
@@ -127,7 +127,7 @@ def test_run_analysis_calls_normalize():
|
||||
|
||||
|
||||
def test_method_calls_module_function():
|
||||
"""Analyzer.process() calls run_analysis() — cross class→function calls edge."""
|
||||
"""Analyzer.process() calls run_analysis() - cross class→function calls edge."""
|
||||
result = extract_python(FIXTURES / "sample_calls.py")
|
||||
calls = {(e["source"], e["target"]) for e in result["edges"] if e["relation"] == "calls"}
|
||||
node_by_label = {n["label"]: n["id"] for n in result["nodes"]}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Tests for hooks.py - git hook install/uninstall."""
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from graphify.hooks import install, uninstall, status, _HOOK_MARKER, _CHECKOUT_MARKER
|
||||
|
||||
|
||||
def _make_git_repo(tmp_path: Path) -> Path:
|
||||
subprocess.run(["git", "init", str(tmp_path)], check=True, capture_output=True)
|
||||
return tmp_path
|
||||
|
||||
|
||||
def test_install_creates_hook(tmp_path):
|
||||
repo = _make_git_repo(tmp_path)
|
||||
result = install(repo)
|
||||
hook = repo / ".git" / "hooks" / "post-commit"
|
||||
assert hook.exists()
|
||||
assert _HOOK_MARKER in hook.read_text()
|
||||
assert "installed" in result
|
||||
|
||||
|
||||
def test_install_is_executable(tmp_path):
|
||||
repo = _make_git_repo(tmp_path)
|
||||
install(repo)
|
||||
hook = repo / ".git" / "hooks" / "post-commit"
|
||||
assert hook.stat().st_mode & 0o111 # executable bit set
|
||||
|
||||
|
||||
def test_install_idempotent(tmp_path):
|
||||
repo = _make_git_repo(tmp_path)
|
||||
install(repo)
|
||||
result = install(repo)
|
||||
assert "already installed" in result
|
||||
# marker appears only once
|
||||
hook = repo / ".git" / "hooks" / "post-commit"
|
||||
assert hook.read_text().count(_HOOK_MARKER) == 1
|
||||
|
||||
|
||||
def test_install_appends_to_existing_hook(tmp_path):
|
||||
repo = _make_git_repo(tmp_path)
|
||||
hook = repo / ".git" / "hooks" / "post-commit"
|
||||
hook.write_text("#!/bin/bash\necho existing\n")
|
||||
hook.chmod(0o755)
|
||||
install(repo)
|
||||
content = hook.read_text()
|
||||
assert "existing" in content
|
||||
assert _HOOK_MARKER in content
|
||||
|
||||
|
||||
def test_uninstall_removes_hook(tmp_path):
|
||||
repo = _make_git_repo(tmp_path)
|
||||
install(repo)
|
||||
result = uninstall(repo)
|
||||
hook = repo / ".git" / "hooks" / "post-commit"
|
||||
assert not hook.exists()
|
||||
assert "removed" in result.lower()
|
||||
|
||||
|
||||
def test_uninstall_no_hook(tmp_path):
|
||||
repo = _make_git_repo(tmp_path)
|
||||
result = uninstall(repo)
|
||||
assert "nothing to remove" in result
|
||||
|
||||
|
||||
def test_status_installed(tmp_path):
|
||||
repo = _make_git_repo(tmp_path)
|
||||
install(repo)
|
||||
result = status(repo)
|
||||
assert "installed" in result
|
||||
|
||||
|
||||
def test_status_not_installed(tmp_path):
|
||||
repo = _make_git_repo(tmp_path)
|
||||
result = status(repo)
|
||||
assert "not installed" in result
|
||||
|
||||
|
||||
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,158 @@
|
||||
"""
|
||||
End-to-end pipeline test: detect → extract → build → cluster → analyze → report → export.
|
||||
Uses the existing test fixtures (code + markdown). No LLM calls - AST extraction only.
|
||||
Catches regressions in how modules connect, not just individual module behaviour.
|
||||
"""
|
||||
import json
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify.detect import detect
|
||||
from graphify.extract import collect_files, extract
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
|
||||
from graphify.report import generate
|
||||
from graphify.export import to_json, to_html, to_obsidian
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
|
||||
def run_pipeline(tmp_path: Path) -> dict:
|
||||
"""Run the full pipeline on the fixtures directory. Returns a dict of outputs."""
|
||||
# Step 1: detect
|
||||
detection = detect(FIXTURES)
|
||||
assert detection["total_files"] > 0
|
||||
# fixtures corpus is intentionally small (< 5k words), so needs_graph may be False
|
||||
assert "files" in detection
|
||||
|
||||
# Step 2: extract (AST only - no LLM)
|
||||
code_files = [Path(f) for f in detection["files"].get("code", [])]
|
||||
assert len(code_files) > 0
|
||||
extraction = extract(code_files)
|
||||
assert len(extraction["nodes"]) > 0
|
||||
assert len(extraction["edges"]) > 0
|
||||
|
||||
# Step 3: build
|
||||
G = build_from_json(extraction)
|
||||
assert G.number_of_nodes() > 0
|
||||
assert G.number_of_edges() > 0
|
||||
|
||||
# Step 4: cluster
|
||||
communities = cluster(G)
|
||||
assert len(communities) > 0
|
||||
cohesion = score_all(G, communities)
|
||||
assert len(cohesion) == len(communities)
|
||||
for score in cohesion.values():
|
||||
assert 0.0 <= score <= 1.0
|
||||
|
||||
# Step 5: analyze
|
||||
gods = god_nodes(G)
|
||||
assert len(gods) > 0
|
||||
assert all("id" in g and "edges" in g for g in gods)
|
||||
|
||||
surprises = surprising_connections(G, communities)
|
||||
assert isinstance(surprises, list)
|
||||
|
||||
labels = {cid: f"Group {cid}" for cid in communities}
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
assert isinstance(questions, list)
|
||||
|
||||
# Step 6: report
|
||||
tokens = {"input": 0, "output": 0}
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, str(FIXTURES), suggested_questions=questions)
|
||||
assert "God Nodes" in report
|
||||
assert "Communities" in report
|
||||
assert len(report) > 100
|
||||
|
||||
# Step 7: export - JSON
|
||||
json_path = tmp_path / "graph.json"
|
||||
to_json(G, communities, str(json_path))
|
||||
assert json_path.exists()
|
||||
data = json.loads(json_path.read_text())
|
||||
assert "nodes" in data and "links" in data
|
||||
assert all("community" in n for n in data["nodes"])
|
||||
|
||||
# Step 8: export - HTML
|
||||
html_path = tmp_path / "graph.html"
|
||||
to_html(G, communities, str(html_path), community_labels=labels)
|
||||
assert html_path.exists()
|
||||
html = html_path.read_text()
|
||||
assert "vis-network" in html
|
||||
assert "RAW_NODES" in html
|
||||
|
||||
# Step 9: export - Obsidian vault
|
||||
vault_path = tmp_path / "obsidian"
|
||||
n_notes = to_obsidian(G, communities, str(vault_path), community_labels=labels, cohesion=cohesion)
|
||||
assert n_notes > 0
|
||||
assert (vault_path / ".obsidian" / "graph.json").exists()
|
||||
md_files = list(vault_path.glob("*.md"))
|
||||
assert len(md_files) > 0
|
||||
|
||||
return {
|
||||
"detection": detection,
|
||||
"extraction": extraction,
|
||||
"graph": G,
|
||||
"communities": communities,
|
||||
"cohesion": cohesion,
|
||||
"gods": gods,
|
||||
"surprises": surprises,
|
||||
"questions": questions,
|
||||
"report": report,
|
||||
}
|
||||
|
||||
|
||||
def test_pipeline_runs_end_to_end(tmp_path):
|
||||
result = run_pipeline(tmp_path)
|
||||
assert result["graph"].number_of_nodes() > 0
|
||||
|
||||
|
||||
def test_pipeline_graph_has_edges(tmp_path):
|
||||
result = run_pipeline(tmp_path)
|
||||
assert result["graph"].number_of_edges() > 0
|
||||
|
||||
|
||||
def test_pipeline_all_nodes_have_community(tmp_path):
|
||||
result = run_pipeline(tmp_path)
|
||||
G = result["graph"]
|
||||
communities = result["communities"]
|
||||
all_community_nodes = {n for nodes in communities.values() for n in nodes}
|
||||
for node in G.nodes():
|
||||
assert node in all_community_nodes, f"Node {node!r} has no community"
|
||||
|
||||
|
||||
def test_pipeline_report_mentions_top_god_node(tmp_path):
|
||||
result = run_pipeline(tmp_path)
|
||||
top_god = result["gods"][0]["label"]
|
||||
assert top_god in result["report"]
|
||||
|
||||
|
||||
def test_pipeline_detection_finds_code_and_docs(tmp_path):
|
||||
result = run_pipeline(tmp_path)
|
||||
assert len(result["detection"]["files"].get("code", [])) > 0
|
||||
assert len(result["detection"]["files"].get("document", [])) > 0
|
||||
|
||||
|
||||
def test_pipeline_incremental_update(tmp_path):
|
||||
"""Second run on unchanged corpus should produce identical node/edge counts."""
|
||||
result1 = run_pipeline(tmp_path)
|
||||
result2 = run_pipeline(tmp_path)
|
||||
assert result1["graph"].number_of_nodes() == result2["graph"].number_of_nodes()
|
||||
assert result1["graph"].number_of_edges() == result2["graph"].number_of_edges()
|
||||
|
||||
|
||||
def test_pipeline_extraction_confidence_labels(tmp_path):
|
||||
result = run_pipeline(tmp_path)
|
||||
extraction = result["extraction"]
|
||||
valid = {"EXTRACTED", "INFERRED", "AMBIGUOUS"}
|
||||
for edge in extraction["edges"]:
|
||||
assert edge["confidence"] in valid, f"Invalid confidence: {edge['confidence']}"
|
||||
|
||||
|
||||
def test_pipeline_no_self_loops(tmp_path):
|
||||
result = run_pipeline(tmp_path)
|
||||
G = result["graph"]
|
||||
for u, v in G.edges():
|
||||
assert u != v, f"Self-loop found on node {u!r}"
|
||||
@@ -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)
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Tests for graphify/security.py — URL validation, safe fetch, path guards, label sanitisation."""
|
||||
"""Tests for graphify/security.py - URL validation, safe fetch, path guards, label sanitisation."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
@@ -47,7 +47,7 @@ def test_validate_url_rejects_empty_scheme():
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# safe_fetch — scheme and redirect guards (mocked network)
|
||||
# safe_fetch - scheme and redirect guards (mocked network)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_mock_response(content: bytes, status: int = 200):
|
||||
@@ -138,7 +138,7 @@ def test_safe_fetch_text_replaces_bad_bytes():
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_validate_graph_path_allows_inside_base(tmp_path):
|
||||
base = tmp_path / ".graphify"
|
||||
base = tmp_path / "graphify-out"
|
||||
base.mkdir()
|
||||
graph = base / "graph.json"
|
||||
graph.write_text("{}")
|
||||
@@ -146,19 +146,19 @@ def test_validate_graph_path_allows_inside_base(tmp_path):
|
||||
assert result == graph.resolve()
|
||||
|
||||
def test_validate_graph_path_blocks_traversal(tmp_path):
|
||||
base = tmp_path / ".graphify"
|
||||
base = tmp_path / "graphify-out"
|
||||
base.mkdir()
|
||||
evil = tmp_path / ".graphify" / ".." / "etc_passwd"
|
||||
evil = tmp_path / "graphify-out" / ".." / "etc_passwd"
|
||||
with pytest.raises(ValueError, match="escapes"):
|
||||
validate_graph_path(str(evil), base=base)
|
||||
|
||||
def test_validate_graph_path_requires_base_exists(tmp_path):
|
||||
base = tmp_path / ".graphify" # not created
|
||||
base = tmp_path / "graphify-out" # not created
|
||||
with pytest.raises(ValueError, match="does not exist"):
|
||||
validate_graph_path(str(base / "graph.json"), base=base)
|
||||
|
||||
def test_validate_graph_path_raises_if_file_missing(tmp_path):
|
||||
base = tmp_path / ".graphify"
|
||||
base = tmp_path / "graphify-out"
|
||||
base.mkdir()
|
||||
with pytest.raises(FileNotFoundError):
|
||||
validate_graph_path(str(base / "missing.json"), base=base)
|
||||
|
||||
@@ -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
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
"""Tests for serve.py — MCP graph query helpers (no mcp package required)."""
|
||||
"""Tests for serve.py - MCP graph query helpers (no mcp package required)."""
|
||||
import json
|
||||
import pytest
|
||||
import networkx as nx
|
||||
@@ -67,7 +67,7 @@ def test_score_nodes_no_match():
|
||||
|
||||
def test_score_nodes_source_file_partial():
|
||||
G = _make_graph()
|
||||
# "cluster.py" contains "cluster" — should score 0.5 for source match
|
||||
# "cluster.py" contains "cluster" - should score 0.5 for source match
|
||||
scored = _score_nodes(G, ["cluster"])
|
||||
nids = [nid for _, nid in scored]
|
||||
assert "n2" in nids
|
||||
@@ -150,7 +150,7 @@ def test_load_graph_roundtrip(tmp_path):
|
||||
assert G2.number_of_edges() == G.number_of_edges()
|
||||
|
||||
def test_load_graph_missing_file(tmp_path):
|
||||
graphify_dir = tmp_path / ".graphify"
|
||||
graphify_dir = tmp_path / "graphify-out"
|
||||
graphify_dir.mkdir()
|
||||
with pytest.raises(SystemExit):
|
||||
_load_graph(str(graphify_dir / "nonexistent.json"))
|
||||
+15
-15
@@ -1,29 +1,29 @@
|
||||
"""Tests for watch.py — file watcher helpers (no watchdog required)."""
|
||||
"""Tests for watch.py - file watcher helpers (no watchdog required)."""
|
||||
import time
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from graphify.watch import _run_update, _WATCHED_EXTENSIONS
|
||||
from graphify.watch import _notify_only, _WATCHED_EXTENSIONS
|
||||
|
||||
|
||||
# --- _run_update ---
|
||||
# --- _notify_only ---
|
||||
|
||||
def test_run_update_creates_flag(tmp_path):
|
||||
_run_update(tmp_path)
|
||||
flag = tmp_path / ".graphify" / "needs_update"
|
||||
def test_notify_only_creates_flag(tmp_path):
|
||||
_notify_only(tmp_path)
|
||||
flag = tmp_path / "graphify-out" / "needs_update"
|
||||
assert flag.exists()
|
||||
assert flag.read_text() == "1"
|
||||
|
||||
def test_run_update_creates_flag_dir(tmp_path):
|
||||
# .graphify dir does not exist yet
|
||||
assert not (tmp_path / ".graphify").exists()
|
||||
_run_update(tmp_path)
|
||||
assert (tmp_path / ".graphify").is_dir()
|
||||
def test_notify_only_creates_flag_dir(tmp_path):
|
||||
# graphify-out dir does not exist yet
|
||||
assert not (tmp_path / "graphify-out").exists()
|
||||
_notify_only(tmp_path)
|
||||
assert (tmp_path / "graphify-out").is_dir()
|
||||
|
||||
def test_run_update_idempotent(tmp_path):
|
||||
_run_update(tmp_path)
|
||||
_run_update(tmp_path)
|
||||
flag = tmp_path / ".graphify" / "needs_update"
|
||||
def test_notify_only_idempotent(tmp_path):
|
||||
_notify_only(tmp_path)
|
||||
_notify_only(tmp_path)
|
||||
flag = tmp_path / "graphify-out" / "needs_update"
|
||||
assert flag.read_text() == "1"
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Tests for graphify.wiki — Wikipedia-style article generation."""
|
||||
import pytest
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
from graphify.wiki import to_wiki, _index_md, _community_article, _god_node_article
|
||||
|
||||
|
||||
def _make_graph():
|
||||
G = nx.Graph()
|
||||
G.add_node("n1", label="parse", file_type="code", source_file="parser.py", community=0)
|
||||
G.add_node("n2", label="validate", file_type="code", source_file="parser.py", community=0)
|
||||
G.add_node("n3", label="render", file_type="code", source_file="renderer.py", community=1)
|
||||
G.add_node("n4", label="stream", file_type="code", source_file="renderer.py", community=1)
|
||||
G.add_edge("n1", "n2", relation="calls", confidence="EXTRACTED", weight=1.0)
|
||||
G.add_edge("n1", "n3", relation="references", confidence="INFERRED", weight=1.0)
|
||||
G.add_edge("n3", "n4", relation="calls", confidence="EXTRACTED", weight=1.0)
|
||||
return G
|
||||
|
||||
|
||||
COMMUNITIES = {0: ["n1", "n2"], 1: ["n3", "n4"]}
|
||||
LABELS = {0: "Parsing Layer", 1: "Rendering Layer"}
|
||||
COHESION = {0: 0.85, 1: 0.72}
|
||||
GOD_NODES = [{"id": "n1", "label": "parse", "edges": 2}]
|
||||
|
||||
|
||||
def test_to_wiki_writes_index(tmp_path):
|
||||
G = _make_graph()
|
||||
n = to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, cohesion=COHESION, god_nodes_data=GOD_NODES)
|
||||
assert (tmp_path / "index.md").exists()
|
||||
|
||||
|
||||
def test_to_wiki_returns_article_count(tmp_path):
|
||||
G = _make_graph()
|
||||
# 2 communities + 1 god node = 3
|
||||
n = to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, cohesion=COHESION, god_nodes_data=GOD_NODES)
|
||||
assert n == 3
|
||||
|
||||
|
||||
def test_to_wiki_community_articles_created(tmp_path):
|
||||
G = _make_graph()
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS)
|
||||
assert (tmp_path / "Parsing_Layer.md").exists()
|
||||
assert (tmp_path / "Rendering_Layer.md").exists()
|
||||
|
||||
|
||||
def test_to_wiki_god_node_article_created(tmp_path):
|
||||
G = _make_graph()
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, god_nodes_data=GOD_NODES)
|
||||
assert (tmp_path / "parse.md").exists()
|
||||
|
||||
|
||||
def test_index_links_all_communities(tmp_path):
|
||||
G = _make_graph()
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS)
|
||||
index = (tmp_path / "index.md").read_text()
|
||||
assert "[[Parsing Layer]]" in index
|
||||
assert "[[Rendering Layer]]" in index
|
||||
|
||||
|
||||
def test_index_lists_god_nodes(tmp_path):
|
||||
G = _make_graph()
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, god_nodes_data=GOD_NODES)
|
||||
index = (tmp_path / "index.md").read_text()
|
||||
assert "[[parse]]" in index
|
||||
assert "2 connections" in index
|
||||
|
||||
|
||||
def test_community_article_has_cross_links(tmp_path):
|
||||
G = _make_graph()
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS)
|
||||
parsing = (tmp_path / "Parsing_Layer.md").read_text()
|
||||
# n1 (parsing) references n3 (rendering) → cross-community link
|
||||
assert "[[Rendering Layer]]" in parsing
|
||||
|
||||
|
||||
def test_community_article_shows_cohesion(tmp_path):
|
||||
G = _make_graph()
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, cohesion=COHESION)
|
||||
parsing = (tmp_path / "Parsing_Layer.md").read_text()
|
||||
assert "cohesion 0.85" in parsing
|
||||
|
||||
|
||||
def test_community_article_has_audit_trail(tmp_path):
|
||||
G = _make_graph()
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS)
|
||||
parsing = (tmp_path / "Parsing_Layer.md").read_text()
|
||||
assert "EXTRACTED" in parsing
|
||||
assert "INFERRED" in parsing
|
||||
|
||||
|
||||
def test_god_node_article_has_connections(tmp_path):
|
||||
G = _make_graph()
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, god_nodes_data=GOD_NODES)
|
||||
article = (tmp_path / "parse.md").read_text()
|
||||
assert "[[validate]]" in article or "[[render]]" in article
|
||||
|
||||
|
||||
def test_god_node_article_links_community(tmp_path):
|
||||
G = _make_graph()
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, god_nodes_data=GOD_NODES)
|
||||
article = (tmp_path / "parse.md").read_text()
|
||||
assert "[[Parsing Layer]]" in article
|
||||
|
||||
|
||||
def test_to_wiki_skips_missing_god_node_ids(tmp_path):
|
||||
"""God node with bad ID should not crash."""
|
||||
G = _make_graph()
|
||||
bad_gods = [{"id": "nonexistent", "label": "ghost", "edges": 99}]
|
||||
n = to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, god_nodes_data=bad_gods)
|
||||
# 2 communities + 0 god nodes (nonexistent skipped) = 2
|
||||
assert n == 2
|
||||
|
||||
|
||||
def test_to_wiki_no_labels_uses_fallback(tmp_path):
|
||||
G = _make_graph()
|
||||
to_wiki(G, COMMUNITIES, tmp_path) # no labels
|
||||
assert (tmp_path / "Community_0.md").exists()
|
||||
assert (tmp_path / "Community_1.md").exists()
|
||||
|
||||
|
||||
def test_article_navigation_footer(tmp_path):
|
||||
G = _make_graph()
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS)
|
||||
article = (tmp_path / "Parsing_Layer.md").read_text()
|
||||
assert "[[index]]" in article
|
||||
|
||||
|
||||
def test_community_article_truncation_notice(tmp_path):
|
||||
"""Communities with more than 25 nodes show a truncation notice."""
|
||||
G = nx.Graph()
|
||||
nodes = [f"n{i}" for i in range(30)]
|
||||
for nid in nodes:
|
||||
G.add_node(nid, label=f"concept_{nid}", file_type="code", source_file="a.py", community=0)
|
||||
for i in range(len(nodes) - 1):
|
||||
G.add_edge(nodes[i], nodes[i + 1], relation="calls", confidence="EXTRACTED", weight=1.0)
|
||||
communities = {0: nodes}
|
||||
to_wiki(G, communities, tmp_path, community_labels={0: "Big Community"})
|
||||
article = (tmp_path / "Big_Community.md").read_text()
|
||||
assert "and 5 more nodes" in article
|
||||
@@ -0,0 +1,57 @@
|
||||
# Reproducible Example
|
||||
|
||||
A small document pipeline (parser, validator, processor, storage, API) with architecture notes and research notes. Six files, two languages, clear call relationships between modules.
|
||||
|
||||
Run graphify on it and you get a knowledge graph showing how the modules connect, which functions call which, and how the architecture notes relate to the code.
|
||||
|
||||
## Input files
|
||||
|
||||
```
|
||||
raw/
|
||||
├── parser.py reads files, detects format, kicks off the pipeline
|
||||
├── validator.py schema checks, calls processor for text normalization
|
||||
├── processor.py keyword extraction, cross-reference detection
|
||||
├── storage.py persists everything, maintains the index
|
||||
├── api.py HTTP handlers that orchestrate the above four modules
|
||||
├── architecture.md design decisions and module responsibilities
|
||||
└── notes.md open questions and tradeoffs, written informally
|
||||
```
|
||||
|
||||
## How to run it
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
Then open Claude Code in this directory and type:
|
||||
|
||||
```
|
||||
/graphify ./raw
|
||||
```
|
||||
|
||||
Takes under a minute. No PDF or image extraction, so it runs entirely on AST and markdown parsing with no token cost for semantic extraction.
|
||||
|
||||
## What to expect
|
||||
|
||||
The graph should show:
|
||||
|
||||
- api.py as a hub node connected to all four modules
|
||||
- parser.py calling validator.py and storage.py
|
||||
- validator.py calling processor.py for normalize_text
|
||||
- processor.py calling storage.py for load_index and save_processed
|
||||
- architecture.md and notes.md linked to the code modules they discuss
|
||||
|
||||
The community detection will likely cluster the four Python modules together and the two markdown files together, or split api.py into its own cluster given its high connectivity.
|
||||
|
||||
God nodes will be storage.py (everything reads and writes through it) and api.py (connects to everything at the top level).
|
||||
|
||||
## After it runs
|
||||
|
||||
Ask questions in Claude Code and it answers from the graph:
|
||||
|
||||
- "what calls storage directly?"
|
||||
- "what is the shortest path between parser and processor?"
|
||||
- "which module has the most connections?"
|
||||
- "what does the architecture doc say about the storage design?"
|
||||
|
||||
The graph lives in graphify-out/ and persists across sessions.
|
||||
@@ -0,0 +1,78 @@
|
||||
"""
|
||||
API module - exposes the document pipeline over HTTP.
|
||||
Thin layer over parser, validator, processor, and storage.
|
||||
"""
|
||||
from parser import batch_parse, parse_file
|
||||
from validator import validate_document, ValidationError
|
||||
from processor import process_and_save, enrich_document
|
||||
from storage import load_record, delete_record, list_records, load_index
|
||||
|
||||
|
||||
def handle_upload(paths: list) -> dict:
|
||||
"""
|
||||
Accept a list of file paths, run the full pipeline on each,
|
||||
and return a summary of what succeeded and what failed.
|
||||
"""
|
||||
results = batch_parse(paths)
|
||||
succeeded = [r for r in results if r["ok"]]
|
||||
failed = [r for r in results if not r["ok"]]
|
||||
return {
|
||||
"uploaded": len(succeeded),
|
||||
"failed": len(failed),
|
||||
"ids": [r["id"] for r in succeeded],
|
||||
"errors": failed,
|
||||
}
|
||||
|
||||
|
||||
def handle_get(record_id: str) -> dict:
|
||||
"""Fetch a document by ID and return it."""
|
||||
try:
|
||||
return load_record(record_id)
|
||||
except KeyError:
|
||||
return {"error": f"Record {record_id} not found"}
|
||||
|
||||
|
||||
def handle_delete(record_id: str) -> dict:
|
||||
"""Delete a document by ID."""
|
||||
deleted = delete_record(record_id)
|
||||
if deleted:
|
||||
return {"deleted": record_id}
|
||||
return {"error": f"Record {record_id} not found"}
|
||||
|
||||
|
||||
def handle_list() -> dict:
|
||||
"""List all document IDs in storage."""
|
||||
return {"records": list_records()}
|
||||
|
||||
|
||||
def handle_search(query: str) -> dict:
|
||||
"""
|
||||
Simple keyword search over the index.
|
||||
Returns documents whose keyword list overlaps with the query terms.
|
||||
"""
|
||||
terms = set(query.lower().split())
|
||||
index = load_index()
|
||||
matches = []
|
||||
for record_id, entry in index.items():
|
||||
keywords = set(entry.get("keywords", []))
|
||||
if terms & keywords:
|
||||
matches.append({
|
||||
"id": record_id,
|
||||
"title": entry.get("title", ""),
|
||||
"matched_keywords": list(terms & keywords),
|
||||
})
|
||||
return {"query": query, "results": matches}
|
||||
|
||||
|
||||
def handle_enrich(record_id: str) -> dict:
|
||||
"""Re-enrich a document to pick up new cross-references."""
|
||||
try:
|
||||
doc = load_record(record_id)
|
||||
except KeyError:
|
||||
return {"error": f"Record {record_id} not found"}
|
||||
try:
|
||||
validated = validate_document(doc)
|
||||
except ValidationError as e:
|
||||
return {"error": str(e)}
|
||||
enriched_id = process_and_save(validated)
|
||||
return {"enriched": enriched_id}
|
||||
@@ -0,0 +1,37 @@
|
||||
# Document Pipeline Architecture
|
||||
|
||||
This is a small document ingestion and search system. Files come in, get parsed and validated, keywords get extracted, cross-references get built, and everything ends up queryable via a simple API.
|
||||
|
||||
## How data flows
|
||||
|
||||
Raw files on disk go through four stages before they are searchable.
|
||||
|
||||
**Parsing** reads the file, detects the format (markdown, JSON, plaintext), and converts it into a structured dict. The parser handles each format differently. Markdown gets title, sections, and links extracted. JSON gets loaded directly. Plaintext gets split into paragraphs.
|
||||
|
||||
**Validation** checks that the parsed document has the required fields and a known format. It also normalizes text fields (lowercase, trim whitespace, strip control characters) using the processor before the document moves forward.
|
||||
|
||||
**Processing** enriches the validated document with a keyword index and cross-references. Cross-references are built by comparing the document's keywords against every other document already in the index. If they share three or more keywords they get linked.
|
||||
|
||||
**Storage** persists everything to disk as JSON files and maintains a flat index that maps record IDs to metadata. All other modules read and write through the storage interface so there is one source of truth.
|
||||
|
||||
## Module responsibilities
|
||||
|
||||
- parser.py: reads files, detects format, calls validate_document and save_parsed
|
||||
- validator.py: enforces schema, normalizes fields, calls normalize_text from processor
|
||||
- processor.py: extract_keywords, find_cross_references, calls load_index and save_processed
|
||||
- storage.py: load_index, save_parsed, save_processed, load_record, delete_record, list_records
|
||||
- api.py: HTTP handlers that orchestrate the above modules
|
||||
|
||||
## Design decisions
|
||||
|
||||
The pipeline is intentionally linear. Each stage has one job and calls the next stage explicitly. There is no event bus or dependency injection. This makes the call graph easy to follow and easy to test.
|
||||
|
||||
Storage is intentionally simple. A flat JSON index plus one file per document is enough at small scale. If the corpus grows past a few thousand documents this becomes the bottleneck and should be replaced with SQLite or a proper document store.
|
||||
|
||||
Cross-reference detection is intentionally naive. Keyword overlap of three is a reasonable threshold for short documents but will produce too many false positives on long ones. A real system would use TF-IDF or embedding similarity instead.
|
||||
|
||||
## Extending the pipeline
|
||||
|
||||
To add a new file format, add a branch in parser.py's parse_file function and a new parse_* function. The rest of the pipeline does not need to change.
|
||||
|
||||
To add a new enrichment step, add a function in processor.py and call it from enrich_document. Store the result in the document dict and add the field to the index in save_processed if you want it searchable.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Research Notes
|
||||
|
||||
Thoughts and open questions while building the document pipeline. Not polished, just a running log.
|
||||
|
||||
## On keyword extraction
|
||||
|
||||
The current approach strips stopwords and returns unique tokens. Simple and fast. The problem is it treats all keywords equally. "database" appearing once in a title carries more weight than "database" buried in a paragraph but the code doesn't know that.
|
||||
|
||||
TF-IDF would fix this. Term frequency times inverse document frequency gives higher scores to words that are distinctive to a document rather than common across the corpus. Worth switching once the index is big enough for IDF to be meaningful (probably 50+ documents).
|
||||
|
||||
Embedding-based similarity is the other option. Run each document through a sentence transformer, store the vector, do nearest-neighbor search at query time. Much better recall but adds a dependency and makes the index opaque. The keyword approach is at least debuggable.
|
||||
|
||||
## On cross-reference detection
|
||||
|
||||
Three shared keywords is arbitrary. Tuned it by hand on a small test set. On short documents (under 500 words) it produces reasonable results. On long documents everything shares keywords with everything else and the cross-reference graph becomes noise.
|
||||
|
||||
A per-document threshold based on document length would be better. Or weight by keyword specificity so rare keywords count more than common ones.
|
||||
|
||||
## On storage
|
||||
|
||||
Flat files work fine for now. The index fits in memory. Load times are under 10ms for a few hundred documents.
|
||||
|
||||
SQLite becomes worth it when you need range queries or you want to update individual fields without rewriting the whole record. The current save_processed rewrites the entire JSON file on every update which is wasteful.
|
||||
|
||||
One thing flat files do well: they are easy to inspect. Open the store directory and you can read every document directly. No tooling required. This matters for debugging.
|
||||
|
||||
## On the API layer
|
||||
|
||||
The API is a thin wrapper. Every handler does one thing: call the right combination of parser, validator, processor, storage. No business logic lives in api.py.
|
||||
|
||||
The risk is that this breaks down when you need transactions. Right now parse_and_save in parser.py calls validate_document and save_parsed in sequence. If save_parsed fails after validate_document succeeds you have a partially written record. Not a problem at small scale, becomes a problem under load.
|
||||
|
||||
## Open questions
|
||||
|
||||
Should validation happen in the parser or as a separate step? Currently it's separate which means the parser can return invalid documents. That feels wrong but keeping them separate makes each module easier to test.
|
||||
|
||||
Should cross-references be stored on the document or computed at query time? Storing them is fast to read but goes stale. Computing at query time is always fresh but slow for large indexes.
|
||||
|
||||
Is the storage interface the right abstraction? Right now parser, validator, and processor all import from storage directly. A repository pattern would centralize access but adds indirection. Probably not worth it until the storage backend needs to change.
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
Parser module - reads raw input documents and converts them into
|
||||
a structured format the rest of the pipeline can work with.
|
||||
"""
|
||||
from validator import validate_document
|
||||
from storage import save_parsed
|
||||
|
||||
|
||||
SUPPORTED_FORMATS = ["markdown", "plaintext", "json"]
|
||||
|
||||
|
||||
def parse_file(path: str) -> dict:
|
||||
"""Read a file from disk and return a structured document."""
|
||||
with open(path, "r") as f:
|
||||
raw = f.read()
|
||||
|
||||
ext = path.rsplit(".", 1)[-1].lower()
|
||||
if ext == "md":
|
||||
doc = parse_markdown(raw)
|
||||
elif ext == "json":
|
||||
doc = parse_json(raw)
|
||||
else:
|
||||
doc = parse_plaintext(raw)
|
||||
|
||||
doc["source"] = path
|
||||
return doc
|
||||
|
||||
|
||||
def parse_markdown(text: str) -> dict:
|
||||
"""Extract title, sections, and links from markdown."""
|
||||
lines = text.splitlines()
|
||||
title = ""
|
||||
sections = []
|
||||
links = []
|
||||
|
||||
for line in lines:
|
||||
if line.startswith("# ") and not title:
|
||||
title = line[2:].strip()
|
||||
elif line.startswith("## "):
|
||||
sections.append(line[3:].strip())
|
||||
elif "](http" in line:
|
||||
start = line.index("](") + 2
|
||||
end = line.index(")", start)
|
||||
links.append(line[start:end])
|
||||
|
||||
return {"title": title, "sections": sections, "links": links, "format": "markdown"}
|
||||
|
||||
|
||||
def parse_json(text: str) -> dict:
|
||||
"""Parse a JSON document into a structured dict."""
|
||||
import json
|
||||
data = json.loads(text)
|
||||
return {"data": data, "format": "json"}
|
||||
|
||||
|
||||
def parse_plaintext(text: str) -> dict:
|
||||
"""Split plaintext into paragraphs."""
|
||||
paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
|
||||
return {"paragraphs": paragraphs, "format": "plaintext"}
|
||||
|
||||
|
||||
def parse_and_save(path: str) -> str:
|
||||
"""Full pipeline: parse, validate, save. Returns the saved record ID."""
|
||||
doc = parse_file(path)
|
||||
validated = validate_document(doc)
|
||||
record_id = save_parsed(validated)
|
||||
return record_id
|
||||
|
||||
|
||||
def batch_parse(paths: list) -> list:
|
||||
"""Parse a list of files and return their record IDs."""
|
||||
results = []
|
||||
for path in paths:
|
||||
try:
|
||||
rid = parse_and_save(path)
|
||||
results.append({"path": path, "id": rid, "ok": True})
|
||||
except Exception as e:
|
||||
results.append({"path": path, "error": str(e), "ok": False})
|
||||
return results
|
||||
@@ -0,0 +1,71 @@
|
||||
"""
|
||||
Processor module - transforms validated documents into enriched records
|
||||
ready for storage and retrieval.
|
||||
"""
|
||||
import re
|
||||
from storage import load_index, save_processed
|
||||
|
||||
|
||||
STOPWORDS = {"the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "for", "of", "with"}
|
||||
|
||||
|
||||
def normalize_text(text: str) -> str:
|
||||
"""Lowercase, strip extra whitespace, remove control characters."""
|
||||
text = text.lower().strip()
|
||||
text = re.sub(r"\s+", " ", text)
|
||||
text = re.sub(r"[^\x20-\x7e]", "", text)
|
||||
return text
|
||||
|
||||
|
||||
def extract_keywords(text: str) -> list:
|
||||
"""Pull non-stopword tokens from text, deduplicated."""
|
||||
tokens = re.findall(r"\b[a-z]{3,}\b", normalize_text(text))
|
||||
seen = set()
|
||||
keywords = []
|
||||
for t in tokens:
|
||||
if t not in STOPWORDS and t not in seen:
|
||||
seen.add(t)
|
||||
keywords.append(t)
|
||||
return keywords
|
||||
|
||||
|
||||
def enrich_document(doc: dict) -> dict:
|
||||
"""Add keyword index and cross-references to a validated document."""
|
||||
text_blob = " ".join([
|
||||
doc.get("title", ""),
|
||||
" ".join(doc.get("sections", [])),
|
||||
" ".join(doc.get("paragraphs", [])),
|
||||
])
|
||||
doc["keywords"] = extract_keywords(text_blob)
|
||||
doc["cross_refs"] = find_cross_references(doc)
|
||||
return doc
|
||||
|
||||
|
||||
def find_cross_references(doc: dict) -> list:
|
||||
"""Look up the index and return IDs of related documents by keyword overlap."""
|
||||
index = load_index()
|
||||
keywords = set(doc.get("keywords", []))
|
||||
refs = []
|
||||
for record_id, entry in index.items():
|
||||
other_keywords = set(entry.get("keywords", []))
|
||||
overlap = keywords & other_keywords
|
||||
if len(overlap) >= 3:
|
||||
refs.append({"id": record_id, "shared_keywords": list(overlap)})
|
||||
return refs
|
||||
|
||||
|
||||
def process_and_save(doc: dict) -> str:
|
||||
"""Enrich a validated document and persist it. Returns the record ID."""
|
||||
enriched = enrich_document(doc)
|
||||
record_id = save_processed(enriched)
|
||||
return record_id
|
||||
|
||||
|
||||
def reprocess_all() -> int:
|
||||
"""Re-enrich all records in the index. Returns count of records updated."""
|
||||
index = load_index()
|
||||
count = 0
|
||||
for record_id, doc in index.items():
|
||||
process_and_save(doc)
|
||||
count += 1
|
||||
return count
|
||||
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
Storage module - persists documents to disk and maintains the search index.
|
||||
All other modules read and write through this interface.
|
||||
"""
|
||||
import json
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
STORAGE_DIR = Path(".graphify_store")
|
||||
INDEX_FILE = STORAGE_DIR / "index.json"
|
||||
|
||||
|
||||
def _ensure_storage() -> None:
|
||||
STORAGE_DIR.mkdir(exist_ok=True)
|
||||
if not INDEX_FILE.exists():
|
||||
INDEX_FILE.write_text(json.dumps({}))
|
||||
|
||||
|
||||
def load_index() -> dict:
|
||||
"""Load the full document index from disk."""
|
||||
_ensure_storage()
|
||||
return json.loads(INDEX_FILE.read_text())
|
||||
|
||||
|
||||
def save_index(index: dict) -> None:
|
||||
"""Persist the index to disk."""
|
||||
_ensure_storage()
|
||||
INDEX_FILE.write_text(json.dumps(index, indent=2))
|
||||
|
||||
|
||||
def save_parsed(doc: dict) -> str:
|
||||
"""Write a parsed document to storage. Returns the assigned record ID."""
|
||||
_ensure_storage()
|
||||
record_id = str(uuid.uuid4())[:8]
|
||||
path = STORAGE_DIR / f"{record_id}.json"
|
||||
path.write_text(json.dumps(doc, indent=2))
|
||||
|
||||
index = load_index()
|
||||
index[record_id] = {
|
||||
"source": doc.get("source", ""),
|
||||
"format": doc.get("format", ""),
|
||||
"title": doc.get("title", ""),
|
||||
}
|
||||
save_index(index)
|
||||
return record_id
|
||||
|
||||
|
||||
def save_processed(doc: dict) -> str:
|
||||
"""Write an enriched document to storage, updating the index with keywords."""
|
||||
_ensure_storage()
|
||||
record_id = doc.get("id") or str(uuid.uuid4())[:8]
|
||||
path = STORAGE_DIR / f"{record_id}_processed.json"
|
||||
path.write_text(json.dumps(doc, indent=2))
|
||||
|
||||
index = load_index()
|
||||
if record_id not in index:
|
||||
index[record_id] = {}
|
||||
index[record_id]["keywords"] = doc.get("keywords", [])
|
||||
index[record_id]["cross_refs"] = [r["id"] for r in doc.get("cross_refs", [])]
|
||||
save_index(index)
|
||||
return record_id
|
||||
|
||||
|
||||
def load_record(record_id: str) -> dict:
|
||||
"""Fetch a single document by ID."""
|
||||
_ensure_storage()
|
||||
path = STORAGE_DIR / f"{record_id}.json"
|
||||
if not path.exists():
|
||||
raise KeyError(f"No record found for ID: {record_id}")
|
||||
return json.loads(path.read_text())
|
||||
|
||||
|
||||
def delete_record(record_id: str) -> bool:
|
||||
"""Remove a document and its index entry. Returns True if it existed."""
|
||||
_ensure_storage()
|
||||
path = STORAGE_DIR / f"{record_id}.json"
|
||||
if not path.exists():
|
||||
return False
|
||||
path.unlink()
|
||||
index = load_index()
|
||||
index.pop(record_id, None)
|
||||
save_index(index)
|
||||
return True
|
||||
|
||||
|
||||
def list_records() -> list:
|
||||
"""Return all record IDs currently in storage."""
|
||||
return list(load_index().keys())
|
||||
@@ -0,0 +1,61 @@
|
||||
"""
|
||||
Validator module - checks that parsed documents meet schema requirements
|
||||
before they are allowed into storage.
|
||||
"""
|
||||
from processor import normalize_text
|
||||
|
||||
|
||||
REQUIRED_FIELDS = {"source", "format"}
|
||||
MAX_TITLE_LENGTH = 200
|
||||
ALLOWED_FORMATS = {"markdown", "plaintext", "json"}
|
||||
|
||||
|
||||
class ValidationError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def validate_document(doc: dict) -> dict:
|
||||
"""Run all validation checks on a parsed document. Raises ValidationError on failure."""
|
||||
check_required_fields(doc)
|
||||
check_format(doc)
|
||||
doc = normalize_fields(doc)
|
||||
return doc
|
||||
|
||||
|
||||
def check_required_fields(doc: dict) -> None:
|
||||
"""Raise if any required field is missing."""
|
||||
missing = REQUIRED_FIELDS - doc.keys()
|
||||
if missing:
|
||||
raise ValidationError(f"Missing required fields: {missing}")
|
||||
|
||||
|
||||
def check_format(doc: dict) -> None:
|
||||
"""Raise if the format is not in the allowed list."""
|
||||
fmt = doc.get("format", "")
|
||||
if fmt not in ALLOWED_FORMATS:
|
||||
raise ValidationError(f"Unknown format: {fmt}. Allowed: {ALLOWED_FORMATS}")
|
||||
|
||||
|
||||
def normalize_fields(doc: dict) -> dict:
|
||||
"""Clean up text fields using the processor."""
|
||||
if "title" in doc:
|
||||
doc["title"] = normalize_text(doc["title"])
|
||||
if len(doc["title"]) > MAX_TITLE_LENGTH:
|
||||
doc["title"] = doc["title"][:MAX_TITLE_LENGTH]
|
||||
if "paragraphs" in doc:
|
||||
doc["paragraphs"] = [normalize_text(p) for p in doc["paragraphs"]]
|
||||
if "sections" in doc:
|
||||
doc["sections"] = [normalize_text(s) for s in doc["sections"]]
|
||||
return doc
|
||||
|
||||
|
||||
def validate_batch(docs: list) -> tuple:
|
||||
"""Validate a list of documents. Returns (valid_docs, errors)."""
|
||||
valid = []
|
||||
errors = []
|
||||
for doc in docs:
|
||||
try:
|
||||
valid.append(validate_document(doc))
|
||||
except ValidationError as e:
|
||||
errors.append({"doc": doc.get("source", "unknown"), "error": str(e)})
|
||||
return valid, errors
|
||||
@@ -0,0 +1,78 @@
|
||||
# Graph Report - worked/httpx/raw (2026-04-05)
|
||||
|
||||
## Corpus Check
|
||||
- 6 files · ~2,047 words
|
||||
- Verdict: corpus is large enough that graph structure adds value.
|
||||
|
||||
## Summary
|
||||
- 144 nodes · 330 edges · 6 communities detected
|
||||
- Extraction: 53% EXTRACTED · 47% INFERRED · 0% AMBIGUOUS
|
||||
- Token cost: 0 input · 0 output
|
||||
|
||||
## God Nodes (most connected - your core abstractions)
|
||||
1. `Client` - 26 edges
|
||||
2. `AsyncClient` - 25 edges
|
||||
3. `Response` - 24 edges
|
||||
4. `Request` - 21 edges
|
||||
5. `BaseClient` - 18 edges
|
||||
6. `HTTPTransport` - 17 edges
|
||||
7. `BaseTransport` - 16 edges
|
||||
8. `AsyncHTTPTransport` - 15 edges
|
||||
9. `Headers` - 15 edges
|
||||
10. `Timeout` - 14 edges
|
||||
|
||||
## Surprising Connections (you probably didn't know these)
|
||||
- `Timeout` --uses--> `URL` [INFERRED]
|
||||
worked/httpx/raw/client.py → worked/httpx/raw/models.py
|
||||
- `Timeout` --uses--> `Headers` [INFERRED]
|
||||
worked/httpx/raw/client.py → worked/httpx/raw/models.py
|
||||
- `Timeout` --uses--> `Cookies` [INFERRED]
|
||||
worked/httpx/raw/client.py → worked/httpx/raw/models.py
|
||||
- `Timeout` --uses--> `BaseTransport` [INFERRED]
|
||||
worked/httpx/raw/client.py → worked/httpx/raw/transport.py
|
||||
- `Timeout` --uses--> `HTTPTransport` [INFERRED]
|
||||
worked/httpx/raw/client.py → worked/httpx/raw/transport.py
|
||||
|
||||
## Communities
|
||||
|
||||
### Community 0 - "Community 0"
|
||||
Cohesion: 0.11
|
||||
Nodes (8): ConnectError, AsyncBaseTransport, AsyncHTTPTransport, BaseTransport, ConnectionPool, HTTPTransport, MockTransport, ProxyTransport
|
||||
|
||||
### Community 1 - "Community 1"
|
||||
Cohesion: 0.13
|
||||
Nodes (9): Auth, BasicAuth, BearerAuth, DigestAuth, NetRCAuth, Limits, Timeout, Request (+1 more)
|
||||
|
||||
### Community 2 - "Community 2"
|
||||
Cohesion: 0.12
|
||||
Nodes (3): AsyncClient, BaseClient, Client
|
||||
|
||||
### Community 3 - "Community 3"
|
||||
Cohesion: 0.11
|
||||
Nodes (3): Cookies, Headers, URL
|
||||
|
||||
### Community 4 - "Community 4"
|
||||
Cohesion: 0.16
|
||||
Nodes (20): Exception, CloseError, ConnectTimeout, CookieConflict, DecodingError, HTTPError, HTTPStatusError, InvalidURL (+12 more)
|
||||
|
||||
### Community 5 - "Community 5"
|
||||
Cohesion: 0.28
|
||||
Nodes (3): build_url_with_params(), flatten_queryparams(), primitive_value_to_str()
|
||||
|
||||
## Suggested Questions
|
||||
_Questions this graph is uniquely positioned to answer:_
|
||||
|
||||
- **Why does `Client` connect `Community 2` to `Community 0`, `Community 1`, `Community 3`, `Community 4`?**
|
||||
_High betweenness centrality (0.177) - this node is a cross-community bridge._
|
||||
- **Why does `Response` connect `Community 1` to `Community 0`, `Community 2`, `Community 3`, `Community 4`?**
|
||||
_High betweenness centrality (0.168) - this node is a cross-community bridge._
|
||||
- **Why does `AsyncClient` connect `Community 2` to `Community 0`, `Community 1`, `Community 3`, `Community 4`?**
|
||||
_High betweenness centrality (0.165) - this node is a cross-community bridge._
|
||||
- **Are the 12 inferred relationships involving `Client` (e.g. with `Request` and `Response`) actually correct?**
|
||||
_`Client` has 12 INFERRED edges - model-reasoned connections that need verification._
|
||||
- **Are the 12 inferred relationships involving `AsyncClient` (e.g. with `Request` and `Response`) actually correct?**
|
||||
_`AsyncClient` has 12 INFERRED edges - model-reasoned connections that need verification._
|
||||
- **Are the 18 inferred relationships involving `Response` (e.g. with `Timeout` and `Limits`) actually correct?**
|
||||
_`Response` has 18 INFERRED edges - model-reasoned connections that need verification._
|
||||
- **Are the 18 inferred relationships involving `Request` (e.g. with `Timeout` and `Limits`) actually correct?**
|
||||
_`Request` has 18 INFERRED edges - model-reasoned connections that need verification._
|
||||
@@ -0,0 +1,44 @@
|
||||
# httpx Corpus Benchmark — How to Reproduce
|
||||
|
||||
A synthetic 6-file Python codebase modeled after httpx's architecture. Tests graphify
|
||||
on a realistic library codebase with clean layering: exceptions → models → auth/transport → client.
|
||||
|
||||
## Corpus (6 files)
|
||||
|
||||
All input files are in `raw/`:
|
||||
|
||||
```
|
||||
raw/
|
||||
├── exceptions.py — full HTTPError hierarchy (RequestError, TransportError, HTTPStatusError, etc.)
|
||||
├── models.py — URL, Headers, Cookies, Request, Response with raise_for_status
|
||||
├── auth.py — BasicAuth, BearerAuth, DigestAuth (challenge-response), NetRCAuth
|
||||
├── utils.py — header normalization, query param flattening, content-type parsing
|
||||
├── transport.py — ConnectionPool, HTTPTransport, AsyncHTTPTransport, MockTransport, ProxyTransport
|
||||
└── client.py — Timeout, Limits, BaseClient, Client (sync), AsyncClient
|
||||
```
|
||||
|
||||
## How to run
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
/graphify ./raw
|
||||
```
|
||||
|
||||
Or from the CLI directly:
|
||||
|
||||
```bash
|
||||
pip install graphifyy
|
||||
graphify ./raw
|
||||
```
|
||||
|
||||
## What to expect
|
||||
|
||||
- 144 nodes, 330 edges, 6 communities
|
||||
- God nodes: `Client`, `AsyncClient`, `Response`, `Request`, `BaseClient`, `HTTPTransport`
|
||||
- Surprising connections: `DigestAuth` ↔ `Response` (auth.py reads Response to parse WWW-Authenticate)
|
||||
- **~1x token reduction** — 6 files fits in a context window, so there's no compression win here
|
||||
|
||||
The graph value on a small corpus is structural, not compressive: you can see the full dependency graph, identify god nodes, and understand architecture at a glance. For token reduction to matter you need 20+ files. At 52 files (Karpathy repos benchmark) graphify achieves 71.5x.
|
||||
|
||||
Run `graphify benchmark worked/httpx/graph.json` to verify the numbers yourself.
|
||||
Actual output is already in this folder: `GRAPH_REPORT.md` (human-readable) and `graph.json` (full graph data).
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,114 @@
|
||||
"""
|
||||
Authentication handlers.
|
||||
Auth objects are callables that modify a request before it is sent.
|
||||
DigestAuth is the most interesting: it participates in a full request/response cycle,
|
||||
reading the 401 response to build the challenge before re-sending.
|
||||
"""
|
||||
import hashlib
|
||||
import time
|
||||
from models import Request, Response
|
||||
|
||||
|
||||
class Auth:
|
||||
"""Base class for all authentication handlers."""
|
||||
|
||||
def auth_flow(self, request: Request):
|
||||
"""Modify the request. May yield to inspect the response."""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class BasicAuth(Auth):
|
||||
"""HTTP Basic Authentication."""
|
||||
|
||||
def __init__(self, username: str, password: str):
|
||||
self.username = username
|
||||
self.password = password
|
||||
|
||||
def auth_flow(self, request: Request):
|
||||
import base64
|
||||
credentials = f"{self.username}:{self.password}".encode()
|
||||
encoded = base64.b64encode(credentials).decode()
|
||||
request.headers["Authorization"] = f"Basic {encoded}"
|
||||
yield request
|
||||
|
||||
|
||||
class BearerAuth(Auth):
|
||||
"""Bearer token authentication."""
|
||||
|
||||
def __init__(self, token: str):
|
||||
self.token = token
|
||||
|
||||
def auth_flow(self, request: Request):
|
||||
request.headers["Authorization"] = f"Bearer {self.token}"
|
||||
yield request
|
||||
|
||||
|
||||
class DigestAuth(Auth):
|
||||
"""
|
||||
HTTP Digest Authentication.
|
||||
Requires a full request/response cycle: sends the initial request,
|
||||
reads the 401 WWW-Authenticate header, then re-sends with credentials.
|
||||
This is the only auth handler that reads from Response.
|
||||
"""
|
||||
|
||||
def __init__(self, username: str, password: str):
|
||||
self.username = username
|
||||
self.password = password
|
||||
self._nonce_count = 0
|
||||
|
||||
def auth_flow(self, request: Request):
|
||||
yield request # first attempt, no credentials
|
||||
|
||||
# This handler must inspect the Response to continue
|
||||
response = yield
|
||||
|
||||
if response.status_code == 401:
|
||||
challenge = self._parse_challenge(response)
|
||||
credentials = self._build_credentials(request, challenge)
|
||||
request.headers["Authorization"] = credentials
|
||||
yield request
|
||||
|
||||
def _parse_challenge(self, response: Response) -> dict:
|
||||
"""Extract digest parameters from the WWW-Authenticate header."""
|
||||
header = response.headers.get("www-authenticate", "")
|
||||
params = {}
|
||||
for part in header.replace("Digest ", "").split(","):
|
||||
if "=" in part:
|
||||
key, _, value = part.strip().partition("=")
|
||||
params[key.strip()] = value.strip().strip('"')
|
||||
return params
|
||||
|
||||
def _build_credentials(self, request: Request, challenge: dict) -> str:
|
||||
"""Compute the Authorization header value for a digest challenge."""
|
||||
self._nonce_count += 1
|
||||
nc = f"{self._nonce_count:08x}"
|
||||
cnonce = hashlib.md5(str(time.time()).encode()).hexdigest()[:8]
|
||||
realm = challenge.get("realm", "")
|
||||
nonce = challenge.get("nonce", "")
|
||||
|
||||
ha1 = hashlib.md5(f"{self.username}:{realm}:{self.password}".encode()).hexdigest()
|
||||
ha2 = hashlib.md5(f"{request.method}:{request.url.path}".encode()).hexdigest()
|
||||
response_hash = hashlib.md5(f"{ha1}:{nonce}:{nc}:{cnonce}:auth:{ha2}".encode()).hexdigest()
|
||||
|
||||
return (
|
||||
f'Digest username="{self.username}", realm="{realm}", '
|
||||
f'nonce="{nonce}", uri="{request.url.path}", '
|
||||
f'nc={nc}, cnonce="{cnonce}", response="{response_hash}"'
|
||||
)
|
||||
|
||||
|
||||
class NetRCAuth(Auth):
|
||||
"""Load credentials from ~/.netrc based on the request host."""
|
||||
|
||||
def auth_flow(self, request: Request):
|
||||
import netrc
|
||||
try:
|
||||
credentials = netrc.netrc().authenticators(request.url.host)
|
||||
if credentials:
|
||||
username, _, password = credentials
|
||||
basic = BasicAuth(username, password)
|
||||
yield from basic.auth_flow(request)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
yield request
|
||||
@@ -0,0 +1,161 @@
|
||||
"""
|
||||
The main Client and AsyncClient classes.
|
||||
BaseClient holds all shared logic. Client and AsyncClient extend it for sync/async.
|
||||
This is the integration hub of the library - it imports from every other module.
|
||||
"""
|
||||
from models import Request, Response, URL, Headers, Cookies
|
||||
from auth import Auth, BasicAuth
|
||||
from transport import BaseTransport, HTTPTransport, AsyncHTTPTransport
|
||||
from exceptions import TooManyRedirects, InvalidURL
|
||||
from utils import build_url_with_params, obfuscate_sensitive_headers
|
||||
|
||||
|
||||
DEFAULT_MAX_REDIRECTS = 20
|
||||
|
||||
|
||||
class Timeout:
|
||||
def __init__(self, timeout=5.0, *, connect=None, read=None, write=None, pool=None):
|
||||
self.connect = connect or timeout
|
||||
self.read = read or timeout
|
||||
self.write = write or timeout
|
||||
self.pool = pool or timeout
|
||||
|
||||
|
||||
class Limits:
|
||||
def __init__(self, max_connections=100, max_keepalive_connections=20, keepalive_expiry=5.0):
|
||||
self.max_connections = max_connections
|
||||
self.max_keepalive_connections = max_keepalive_connections
|
||||
self.keepalive_expiry = keepalive_expiry
|
||||
|
||||
|
||||
class BaseClient:
|
||||
"""
|
||||
Shared implementation for Client and AsyncClient.
|
||||
Handles auth, redirects, cookies, and header defaults.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
auth=None,
|
||||
headers=None,
|
||||
cookies=None,
|
||||
timeout=Timeout(),
|
||||
max_redirects=DEFAULT_MAX_REDIRECTS,
|
||||
base_url="",
|
||||
):
|
||||
self._auth = auth
|
||||
self._headers = Headers(headers or {})
|
||||
self._cookies = Cookies(cookies or {})
|
||||
self._timeout = timeout
|
||||
self._max_redirects = max_redirects
|
||||
self._base_url = URL(base_url) if base_url else None
|
||||
|
||||
def _build_request(self, method: str, url: str, **kwargs) -> Request:
|
||||
if self._base_url:
|
||||
url = self._base_url.raw.rstrip("/") + "/" + url.lstrip("/")
|
||||
if kwargs.get("params"):
|
||||
url = build_url_with_params(url, kwargs.pop("params"))
|
||||
headers = Headers(kwargs.get("headers", {}))
|
||||
for k, v in self._headers.items():
|
||||
if k not in headers:
|
||||
headers[k] = v
|
||||
return Request(method, url, headers=headers, content=kwargs.get("content"), cookies=self._cookies)
|
||||
|
||||
def _merge_cookies(self, response: Response) -> None:
|
||||
for name, value in response.cookies.items():
|
||||
self._cookies.set(name, value)
|
||||
|
||||
|
||||
class Client(BaseClient):
|
||||
"""Synchronous HTTP client."""
|
||||
|
||||
def __init__(self, *, transport: BaseTransport = None, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self._transport = transport or HTTPTransport()
|
||||
|
||||
def request(self, method: str, url: str, **kwargs) -> Response:
|
||||
request = self._build_request(method, url, **kwargs)
|
||||
auth = kwargs.get("auth") or self._auth
|
||||
if auth:
|
||||
flow = auth.auth_flow(request)
|
||||
request = next(flow)
|
||||
response = self._transport.handle_request(request)
|
||||
self._merge_cookies(response)
|
||||
if auth:
|
||||
try:
|
||||
flow.send(response)
|
||||
except StopIteration:
|
||||
pass
|
||||
return response
|
||||
|
||||
def get(self, url: str, **kwargs) -> Response:
|
||||
return self.request("GET", url, **kwargs)
|
||||
|
||||
def post(self, url: str, **kwargs) -> Response:
|
||||
return self.request("POST", url, **kwargs)
|
||||
|
||||
def put(self, url: str, **kwargs) -> Response:
|
||||
return self.request("PUT", url, **kwargs)
|
||||
|
||||
def patch(self, url: str, **kwargs) -> Response:
|
||||
return self.request("PATCH", url, **kwargs)
|
||||
|
||||
def delete(self, url: str, **kwargs) -> Response:
|
||||
return self.request("DELETE", url, **kwargs)
|
||||
|
||||
def head(self, url: str, **kwargs) -> Response:
|
||||
return self.request("HEAD", url, **kwargs)
|
||||
|
||||
def send(self, request: Request) -> Response:
|
||||
return self._transport.handle_request(request)
|
||||
|
||||
def close(self) -> None:
|
||||
self._transport.close()
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
self.close()
|
||||
|
||||
|
||||
class AsyncClient(BaseClient):
|
||||
"""Asynchronous HTTP client."""
|
||||
|
||||
def __init__(self, *, transport=None, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self._transport = transport or AsyncHTTPTransport()
|
||||
|
||||
async def request(self, method: str, url: str, **kwargs) -> Response:
|
||||
request = self._build_request(method, url, **kwargs)
|
||||
response = await self._transport.handle_async_request(request)
|
||||
self._merge_cookies(response)
|
||||
return response
|
||||
|
||||
async def get(self, url: str, **kwargs) -> Response:
|
||||
return await self.request("GET", url, **kwargs)
|
||||
|
||||
async def post(self, url: str, **kwargs) -> Response:
|
||||
return await self.request("POST", url, **kwargs)
|
||||
|
||||
async def put(self, url: str, **kwargs) -> Response:
|
||||
return await self.request("PUT", url, **kwargs)
|
||||
|
||||
async def patch(self, url: str, **kwargs) -> Response:
|
||||
return await self.request("PATCH", url, **kwargs)
|
||||
|
||||
async def delete(self, url: str, **kwargs) -> Response:
|
||||
return await self.request("DELETE", url, **kwargs)
|
||||
|
||||
async def send(self, request: Request) -> Response:
|
||||
return await self._transport.handle_async_request(request)
|
||||
|
||||
async def aclose(self) -> None:
|
||||
await self._transport.aclose()
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
await self.aclose()
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
httpx-like exception hierarchy.
|
||||
All exceptions inherit from HTTPError at the top.
|
||||
"""
|
||||
|
||||
|
||||
class HTTPError(Exception):
|
||||
"""Base class for all httpx exceptions."""
|
||||
def __init__(self, message, *, request=None):
|
||||
self.request = request
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class RequestError(HTTPError):
|
||||
"""An error occurred while issuing a request."""
|
||||
|
||||
|
||||
class TransportError(RequestError):
|
||||
"""An error occurred at the transport layer."""
|
||||
|
||||
|
||||
class TimeoutException(TransportError):
|
||||
"""A timeout occurred."""
|
||||
|
||||
|
||||
class ConnectTimeout(TimeoutException):
|
||||
"""Timed out while connecting to the host."""
|
||||
|
||||
|
||||
class ReadTimeout(TimeoutException):
|
||||
"""Timed out while receiving data from the host."""
|
||||
|
||||
|
||||
class WriteTimeout(TimeoutException):
|
||||
"""Timed out while sending data to the host."""
|
||||
|
||||
|
||||
class PoolTimeout(TimeoutException):
|
||||
"""Timed out waiting to acquire a connection from the pool."""
|
||||
|
||||
|
||||
class NetworkError(TransportError):
|
||||
"""A network error occurred."""
|
||||
|
||||
|
||||
class ConnectError(NetworkError):
|
||||
"""Failed to establish a connection."""
|
||||
|
||||
|
||||
class ReadError(NetworkError):
|
||||
"""Failed to receive data from the network."""
|
||||
|
||||
|
||||
class WriteError(NetworkError):
|
||||
"""Failed to send data through the network."""
|
||||
|
||||
|
||||
class CloseError(NetworkError):
|
||||
"""Failed to close a connection."""
|
||||
|
||||
|
||||
class ProxyError(TransportError):
|
||||
"""An error occurred while establishing a proxy connection."""
|
||||
|
||||
|
||||
class ProtocolError(TransportError):
|
||||
"""A protocol was violated."""
|
||||
|
||||
|
||||
class DecodingError(RequestError):
|
||||
"""Decoding of the response failed."""
|
||||
|
||||
|
||||
class TooManyRedirects(RequestError):
|
||||
"""Too many redirects."""
|
||||
|
||||
|
||||
class HTTPStatusError(HTTPError):
|
||||
"""A 4xx or 5xx response was received."""
|
||||
def __init__(self, message, *, request, response):
|
||||
self.response = response
|
||||
super().__init__(message, request=request)
|
||||
|
||||
|
||||
class InvalidURL(Exception):
|
||||
"""URL is improperly formed or cannot be parsed."""
|
||||
|
||||
|
||||
class CookieConflict(Exception):
|
||||
"""Attempted to look up a cookie by name but multiple cookies exist."""
|
||||
@@ -0,0 +1,120 @@
|
||||
"""
|
||||
Core data models: URL, Headers, Cookies, Request, Response.
|
||||
These are the central data types that everything else in the library references.
|
||||
"""
|
||||
import json as _json
|
||||
from exceptions import HTTPStatusError
|
||||
|
||||
|
||||
class URL:
|
||||
def __init__(self, url: str):
|
||||
self.raw = url
|
||||
self.scheme, _, rest = url.partition("://")
|
||||
self.host, _, self.path = rest.partition("/")
|
||||
self.path = "/" + self.path
|
||||
|
||||
def copy_with(self, **kwargs) -> "URL":
|
||||
return URL(kwargs.get("url", self.raw))
|
||||
|
||||
def __str__(self):
|
||||
return self.raw
|
||||
|
||||
def __repr__(self):
|
||||
return f"URL({self.raw!r})"
|
||||
|
||||
|
||||
class Headers:
|
||||
def __init__(self, headers=None):
|
||||
self._store = {}
|
||||
for k, v in (headers or {}).items():
|
||||
self._store[k.lower()] = v
|
||||
|
||||
def get(self, key: str, default=None):
|
||||
return self._store.get(key.lower(), default)
|
||||
|
||||
def items(self):
|
||||
return self._store.items()
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
self._store[key.lower()] = value
|
||||
|
||||
def __getitem__(self, key):
|
||||
return self._store[key.lower()]
|
||||
|
||||
def __contains__(self, key):
|
||||
return key.lower() in self._store
|
||||
|
||||
|
||||
class Cookies:
|
||||
def __init__(self, cookies=None):
|
||||
self._jar = dict(cookies or {})
|
||||
|
||||
def set(self, name: str, value: str, domain: str = "") -> None:
|
||||
self._jar[name] = value
|
||||
|
||||
def get(self, name: str, default=None):
|
||||
return self._jar.get(name, default)
|
||||
|
||||
def delete(self, name: str) -> None:
|
||||
self._jar.pop(name, None)
|
||||
|
||||
def clear(self) -> None:
|
||||
self._jar.clear()
|
||||
|
||||
def items(self):
|
||||
return self._jar.items()
|
||||
|
||||
|
||||
class Request:
|
||||
def __init__(self, method: str, url, *, headers=None, content=None, cookies=None):
|
||||
self.method = method.upper()
|
||||
self.url = URL(url) if isinstance(url, str) else url
|
||||
self.headers = Headers(headers)
|
||||
self.content = content or b""
|
||||
self.cookies = Cookies(cookies)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Request [{self.method}]>"
|
||||
|
||||
|
||||
class Response:
|
||||
def __init__(self, status_code: int, *, headers=None, content=None, request=None):
|
||||
self.status_code = status_code
|
||||
self.headers = Headers(headers)
|
||||
self.content = content or b""
|
||||
self.request = request
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
return self.content.decode("utf-8", errors="replace")
|
||||
|
||||
def json(self):
|
||||
return _json.loads(self.content)
|
||||
|
||||
def read(self) -> bytes:
|
||||
return self.content
|
||||
|
||||
@property
|
||||
def is_success(self) -> bool:
|
||||
return 200 <= self.status_code < 300
|
||||
|
||||
@property
|
||||
def is_error(self) -> bool:
|
||||
return self.status_code >= 400
|
||||
|
||||
def raise_for_status(self) -> None:
|
||||
if self.is_error:
|
||||
message = f"{self.status_code} Error"
|
||||
raise HTTPStatusError(message, request=self.request, response=self)
|
||||
|
||||
@property
|
||||
def cookies(self) -> Cookies:
|
||||
jar = Cookies()
|
||||
for header in self.headers.get("set-cookie", "").split(","):
|
||||
if "=" in header:
|
||||
name, _, value = header.strip().partition("=")
|
||||
jar.set(name.strip(), value.split(";")[0].strip())
|
||||
return jar
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Response [{self.status_code}]>"
|
||||
@@ -0,0 +1,135 @@
|
||||
"""
|
||||
Transport layer: connection management and low-level HTTP sending.
|
||||
HTTPTransport wraps a connection pool. ProxyTransport sits in front of it.
|
||||
MockTransport is used in tests.
|
||||
"""
|
||||
from models import Request, Response
|
||||
from exceptions import TransportError, ConnectError, TimeoutException
|
||||
|
||||
|
||||
class BaseTransport:
|
||||
"""Sync transport interface."""
|
||||
|
||||
def handle_request(self, request: Request) -> Response:
|
||||
raise NotImplementedError
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class AsyncBaseTransport:
|
||||
"""Async transport interface."""
|
||||
|
||||
async def handle_async_request(self, request: Request) -> Response:
|
||||
raise NotImplementedError
|
||||
|
||||
async def aclose(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class ConnectionPool:
|
||||
"""
|
||||
Manages a pool of persistent HTTP connections.
|
||||
Keys connections by (scheme, host, port).
|
||||
"""
|
||||
|
||||
def __init__(self, max_connections=100, max_keepalive_connections=20):
|
||||
self.max_connections = max_connections
|
||||
self.max_keepalive_connections = max_keepalive_connections
|
||||
self._pool = {}
|
||||
|
||||
def _get_connection_key(self, request: Request) -> tuple:
|
||||
url = request.url
|
||||
port = 443 if url.scheme == "https" else 80
|
||||
return (url.scheme, url.host, port)
|
||||
|
||||
def get_connection(self, request: Request):
|
||||
key = self._get_connection_key(request)
|
||||
return self._pool.get(key)
|
||||
|
||||
def return_connection(self, request: Request, conn) -> None:
|
||||
key = self._get_connection_key(request)
|
||||
if len(self._pool) < self.max_keepalive_connections:
|
||||
self._pool[key] = conn
|
||||
|
||||
def close(self) -> None:
|
||||
self._pool.clear()
|
||||
|
||||
|
||||
class HTTPTransport(BaseTransport):
|
||||
"""
|
||||
The main sync HTTP transport.
|
||||
Uses a ConnectionPool for connection reuse.
|
||||
"""
|
||||
|
||||
def __init__(self, verify=True, cert=None, limits=None):
|
||||
self.verify = verify
|
||||
self.cert = cert
|
||||
self._pool = ConnectionPool()
|
||||
|
||||
def handle_request(self, request: Request) -> Response:
|
||||
conn = self._pool.get_connection(request)
|
||||
try:
|
||||
response = self._send(request, conn)
|
||||
self._pool.return_connection(request, conn)
|
||||
return response
|
||||
except TimeoutException:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectError(str(exc)) from exc
|
||||
|
||||
def _send(self, request: Request, conn) -> Response:
|
||||
# Simplified: in real httpx this does the actual socket I/O
|
||||
return Response(200, headers={}, content=b"", request=request)
|
||||
|
||||
def close(self) -> None:
|
||||
self._pool.close()
|
||||
|
||||
|
||||
class AsyncHTTPTransport(AsyncBaseTransport):
|
||||
"""The async variant of HTTPTransport."""
|
||||
|
||||
def __init__(self, verify=True, cert=None):
|
||||
self.verify = verify
|
||||
self.cert = cert
|
||||
|
||||
async def handle_async_request(self, request: Request) -> Response:
|
||||
return Response(200, headers={}, content=b"", request=request)
|
||||
|
||||
async def aclose(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class MockTransport(BaseTransport):
|
||||
"""
|
||||
A transport for testing that returns predefined responses.
|
||||
Pass a handler function that receives a Request and returns a Response.
|
||||
"""
|
||||
|
||||
def __init__(self, handler):
|
||||
self.handler = handler
|
||||
|
||||
def handle_request(self, request: Request) -> Response:
|
||||
return self.handler(request)
|
||||
|
||||
|
||||
class ProxyTransport(BaseTransport):
|
||||
"""
|
||||
Routes requests through an HTTP/HTTPS proxy.
|
||||
Wraps an inner transport and prepends proxy connection handling.
|
||||
"""
|
||||
|
||||
def __init__(self, proxy_url: str, *, inner: BaseTransport = None):
|
||||
self.proxy_url = proxy_url
|
||||
self._inner = inner or HTTPTransport()
|
||||
|
||||
def handle_request(self, request: Request) -> Response:
|
||||
try:
|
||||
return self._inner.handle_request(request)
|
||||
except TransportError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise TransportError(f"Proxy error: {exc}") from exc
|
||||
|
||||
def close(self) -> None:
|
||||
self._inner.close()
|
||||
@@ -0,0 +1,85 @@
|
||||
"""
|
||||
Utility functions shared across the library.
|
||||
Small helpers that don't belong in any one module.
|
||||
"""
|
||||
import re
|
||||
from models import Cookies
|
||||
|
||||
|
||||
SENSITIVE_HEADERS = {"authorization", "cookie", "set-cookie", "proxy-authorization"}
|
||||
|
||||
|
||||
def primitive_value_to_str(value) -> str:
|
||||
"""Convert a primitive value to its string representation."""
|
||||
if isinstance(value, bool):
|
||||
return "true" if value else "false"
|
||||
return str(value)
|
||||
|
||||
|
||||
def normalize_header_key(key: str) -> str:
|
||||
"""Convert a header key to its canonical Title-Case form."""
|
||||
return "-".join(word.capitalize() for word in key.split("-"))
|
||||
|
||||
|
||||
def flatten_queryparams(params: dict) -> list:
|
||||
"""
|
||||
Expand a params dict into a flat list of (key, value) pairs.
|
||||
List values become multiple pairs with the same key.
|
||||
"""
|
||||
result = []
|
||||
for key, value in params.items():
|
||||
if isinstance(value, list):
|
||||
for item in value:
|
||||
result.append((key, primitive_value_to_str(item)))
|
||||
else:
|
||||
result.append((key, primitive_value_to_str(value)))
|
||||
return result
|
||||
|
||||
|
||||
def parse_content_type(content_type: str) -> tuple:
|
||||
"""
|
||||
Parse a Content-Type header value.
|
||||
Returns (media_type, params_dict).
|
||||
Example: 'application/json; charset=utf-8' -> ('application/json', {'charset': 'utf-8'})
|
||||
"""
|
||||
parts = [p.strip() for p in content_type.split(";")]
|
||||
media_type = parts[0]
|
||||
params = {}
|
||||
for part in parts[1:]:
|
||||
if "=" in part:
|
||||
key, _, value = part.partition("=")
|
||||
params[key.strip()] = value.strip()
|
||||
return media_type, params
|
||||
|
||||
|
||||
def obfuscate_sensitive_headers(headers: dict) -> dict:
|
||||
"""Return a copy of headers with sensitive values replaced by [obfuscated]."""
|
||||
return {
|
||||
k: "[obfuscated]" if k.lower() in SENSITIVE_HEADERS else v
|
||||
for k, v in headers.items()
|
||||
}
|
||||
|
||||
|
||||
def unset_all_cookies(cookies: Cookies) -> None:
|
||||
"""Clear all cookies from a cookie jar in place."""
|
||||
cookies.clear()
|
||||
|
||||
|
||||
def is_known_encoding(encoding: str) -> bool:
|
||||
"""Check if a character encoding label is recognized by Python's codec system."""
|
||||
import codecs
|
||||
try:
|
||||
codecs.lookup(encoding)
|
||||
return True
|
||||
except LookupError:
|
||||
return False
|
||||
|
||||
|
||||
def build_url_with_params(base_url: str, params: dict) -> str:
|
||||
"""Append query parameters to a URL string."""
|
||||
if not params:
|
||||
return base_url
|
||||
pairs = flatten_queryparams(params)
|
||||
query = "&".join(f"{k}={v}" for k, v in pairs)
|
||||
separator = "&" if "?" in base_url else "?"
|
||||
return f"{base_url}{separator}{query}"
|
||||
@@ -1,6 +1,6 @@
|
||||
# Graphify Evaluation — httpx Corpus (2026-04-03)
|
||||
# Graphify Evaluation - httpx Corpus (2026-04-03)
|
||||
|
||||
**Evaluator:** Claude Sonnet 4.6 (analytical simulation — Bash execution unavailable)
|
||||
**Evaluator:** Claude Sonnet 4.6 (analytical simulation - Bash execution unavailable)
|
||||
**Corpus:** 6-file synthetic httpx-like Python codebase (~2,800 words)
|
||||
**Pipeline:** graphify AST extractor + graph_builder + Leiden clusterer + analyzer + reporter
|
||||
**Method:** Full deterministic code tracing of every graphify source module against
|
||||
@@ -12,7 +12,7 @@ exact Leiden partition is non-deterministic but the structural analysis is sound
|
||||
## Full GRAPH_REPORT.md Content
|
||||
|
||||
```markdown
|
||||
# Graph Report — /home/safi/graphify_test/httpx (2026-04-03)
|
||||
# Graph Report - /home/safi/graphify_test/httpx (2026-04-03)
|
||||
|
||||
## Corpus Check
|
||||
- 6 files · ~2,800 words
|
||||
@@ -23,17 +23,17 @@ exact Leiden partition is non-deterministic but the structural analysis is sound
|
||||
- Extraction: ~100% EXTRACTED · 0% INFERRED · 0% AMBIGUOUS
|
||||
- Token cost: 0 input · 0 output
|
||||
|
||||
## God Nodes (most connected — your core abstractions)
|
||||
1. `client.py` — ~28 edges
|
||||
2. `models.py` — ~22 edges
|
||||
3. `transport.py` — ~20 edges
|
||||
4. `exceptions.py` — ~18 edges
|
||||
5. `BaseClient` — ~15 edges
|
||||
6. `auth.py` — ~14 edges
|
||||
7. `Response` — ~12 edges
|
||||
8. `Client` — ~10 edges
|
||||
9. `AsyncClient` — ~10 edges
|
||||
10. `utils.py` — ~9 edges
|
||||
## God Nodes (most connected - your core abstractions)
|
||||
1. `client.py` - ~28 edges
|
||||
2. `models.py` - ~22 edges
|
||||
3. `transport.py` - ~20 edges
|
||||
4. `exceptions.py` - ~18 edges
|
||||
5. `BaseClient` - ~15 edges
|
||||
6. `auth.py` - ~14 edges
|
||||
7. `Response` - ~12 edges
|
||||
8. `Client` - ~10 edges
|
||||
9. `AsyncClient` - ~10 edges
|
||||
10. `utils.py` - ~9 edges
|
||||
|
||||
## Surprising Connections
|
||||
- `BaseClient` ↔ `.auth_flow()` [EXTRACTED]
|
||||
@@ -49,19 +49,19 @@ exact Leiden partition is non-deterministic but the structural analysis is sound
|
||||
|
||||
## Communities
|
||||
|
||||
### Community 0 — "Core HTTP Client"
|
||||
### Community 0 - "Core HTTP Client"
|
||||
Cohesion: 0.14
|
||||
Nodes (12): client.py, BaseClient, Client, AsyncClient, .send(), .request(), .get(), .post(), .close(), .aclose(), Timeout, Limits
|
||||
|
||||
### Community 1 — "Request/Response Models"
|
||||
### Community 1 - "Request/Response Models"
|
||||
Cohesion: 0.18
|
||||
Nodes (10): models.py, Request, Response, URL, Headers, Cookies, .read(), .json(), .raise_for_status(), .cookies
|
||||
|
||||
### Community 2 — "Exception Hierarchy"
|
||||
### Community 2 - "Exception Hierarchy"
|
||||
Cohesion: 0.10
|
||||
Nodes (20): exceptions.py, HTTPStatusError, RequestError, TransportError, TimeoutException, ...
|
||||
|
||||
### Community 3 — "Transport & Auth"
|
||||
### Community 3 - "Transport & Auth"
|
||||
Cohesion: 0.08
|
||||
Nodes (18): transport.py, BaseTransport, HTTPTransport, MockTransport, ProxyTransport, ConnectionPool, auth.py, Auth, BasicAuth, DigestAuth, BearerAuth, NetRCAuth, ...
|
||||
```
|
||||
@@ -70,7 +70,7 @@ Nodes (18): transport.py, BaseTransport, HTTPTransport, MockTransport, ProxyTran
|
||||
|
||||
## Evaluation Scores
|
||||
|
||||
### 1. Node/Edge Quality — Score: 6/10
|
||||
### 1. Node/Edge Quality - Score: 6/10
|
||||
|
||||
**What's captured well:**
|
||||
- File-level nodes for all 6 files (exceptions, models, auth, utils, client, transport) ✓
|
||||
@@ -78,42 +78,42 @@ Nodes (18): transport.py, BaseTransport, HTTPTransport, MockTransport, ProxyTran
|
||||
subclasses; URL, Headers, Cookies, Request, Response; Auth, BasicAuth, DigestAuth,
|
||||
BearerAuth, NetRCAuth; BaseClient, Client, AsyncClient; Timeout, Limits; BaseTransport,
|
||||
AsyncBaseTransport, HTTPTransport, AsyncHTTPTransport, MockTransport, ProxyTransport,
|
||||
ConnectionPool — all captured ✓
|
||||
ConnectionPool - all captured ✓
|
||||
- Module-level functions from utils.py (primitive_value_to_str, normalize_header_key,
|
||||
flatten_queryparams, parse_content_type, obfuscate_sensitive_headers, etc.) ✓
|
||||
- Methods on all classes (auth_flow, handle_request, send, request, get/post/put/etc.) ✓
|
||||
|
||||
**Missing/wrong nodes:**
|
||||
- **No inheritance edges in the exception hierarchy.** The extractor builds inheritance edges
|
||||
as `_make_id(stem, base_name)` — e.g. `RequestError` inheriting `Exception` produces target
|
||||
as `_make_id(stem, base_name)` - e.g. `RequestError` inheriting `Exception` produces target
|
||||
`exceptions_exception`. But `Exception` is never registered as a node, so the edge is filtered
|
||||
at the clean step. All 14 inheritance edges in exceptions.py are silently dropped. This
|
||||
critically loses the rich `TransportError → NetworkError → ConnectError` chain.
|
||||
- **No inheritance across files.** `BaseClient` inherits nothing in the graph. `Client(BaseClient)`
|
||||
produces `_make_id("client", "BaseClient")` = `"client_baseclient"`, but `BaseClient`'s node
|
||||
ID is `_make_id("client", "BaseClient")` = `"client_baseclient"` — this actually SHOULD work
|
||||
ID is `_make_id("client", "BaseClient")` = `"client_baseclient"` - this actually SHOULD work
|
||||
because both the class definition and the inheritance reference use the same stem ("client").
|
||||
**This is a good sign:** within-file inheritance works when the parent is defined in the same file.
|
||||
- **Cross-file inheritance is not captured.** `HTTPTransport(BaseTransport)` — `BaseTransport`
|
||||
- **Cross-file inheritance is not captured.** `HTTPTransport(BaseTransport)` - `BaseTransport`
|
||||
is defined in `transport.py`, so `_make_id("transport", "BaseTransport")` = `"transport_basetransport"`.
|
||||
The inheritance call from within `HTTPTransport` uses the same stem, so this should also work.
|
||||
- **Property methods lose their property decorator context.** `url`, `content`, `cookies`,
|
||||
`is_success`, `is_error`, etc. are extracted as ordinary methods — no semantic distinction.
|
||||
- **`build_auth_header` utility function in auth.py** — captured as a module-level function ✓
|
||||
`is_success`, `is_error`, etc. are extracted as ordinary methods - no semantic distinction.
|
||||
- **`build_auth_header` utility function in auth.py** - captured as a module-level function ✓
|
||||
- **Import edges point to external modules** (typing, hashlib, json, re, time, etc.) that are
|
||||
never registered as nodes. Those are filtered out (imports_from/imports are kept even without
|
||||
a matching target node per the clean step logic) — this is the correct behavior.
|
||||
a matching target node per the clean step logic) - this is the correct behavior.
|
||||
|
||||
**Summary:** ~85% of meaningful code entities are captured. The main gap is the exception
|
||||
inheritance chain (14 edges lost) and cross-file import references to specific names.
|
||||
|
||||
---
|
||||
|
||||
### 2. Edge Accuracy — Score: 5/10
|
||||
### 2. Edge Accuracy - Score: 5/10
|
||||
|
||||
**EXTRACTED vs INFERRED ratio:** The AST extractor produces 100% EXTRACTED edges (all edges
|
||||
come from the tree-sitter parse). There are 0 INFERRED edges. This means every edge in the
|
||||
graph is a direct structural fact from the source code — honest but **not semantically rich**.
|
||||
graph is a direct structural fact from the source code - honest but **not semantically rich**.
|
||||
|
||||
**What's right:**
|
||||
- `contains` edges from file nodes to their class/function children ✓
|
||||
@@ -124,19 +124,19 @@ graph is a direct structural fact from the source code — honest but **not sema
|
||||
**What's wrong or missing:**
|
||||
- **0% INFERRED edges.** The AST extractor only does structural extraction. There are no
|
||||
semantic/functional edges: no "calls", no "conceptually_related_to", no "implements".
|
||||
For example, `DigestAuth.auth_flow` calls `Response.status_code` — this relationship is
|
||||
For example, `DigestAuth.auth_flow` calls `Response.status_code` - this relationship is
|
||||
invisible. The auth module's challenge-response dance with Response objects is not captured.
|
||||
- **Inheritance chain edges dropped (14 edges).** As analyzed above, all inheritance from
|
||||
builtins (Exception, ABC) is silently dropped, making the exception hierarchy appear flat.
|
||||
- **Import edges are present but low-signal.** `client.py imports_from models` is correct but
|
||||
doesn't say WHICH classes — so the graph can't distinguish that `Client` specifically uses
|
||||
doesn't say WHICH classes - so the graph can't distinguish that `Client` specifically uses
|
||||
`Request` and `Response`, not just the whole models module.
|
||||
- **No "calls" relationships.** `Response.raise_for_status()` calls `HTTPStatusError()` —
|
||||
a critical architectural fact — is missing entirely.
|
||||
- **No "calls" relationships.** `Response.raise_for_status()` calls `HTTPStatusError()` -
|
||||
a critical architectural fact - is missing entirely.
|
||||
- **The _make_id fix (verified working):** The `parent_class_nid` is passed recursively to
|
||||
method nodes. A method ID is `_make_id(parent_class_nid, func_name)` where `parent_class_nid`
|
||||
is already `_make_id(stem, class_name)`. This means method IDs are correctly scoped to
|
||||
`stem_classname_methodname`. Edge cleanup checks `src in valid_ids` — since method nodes ARE
|
||||
`stem_classname_methodname`. Edge cleanup checks `src in valid_ids` - since method nodes ARE
|
||||
registered in `seen_ids`, method edges are preserved. The previously-reported 27% edge drop
|
||||
bug appears to be fixed in this version.
|
||||
|
||||
@@ -144,32 +144,32 @@ graph is a direct structural fact from the source code — honest but **not sema
|
||||
- Correct, present: ~115 edges (88%)
|
||||
- Silently dropped (inheritance from builtins): ~14 edges (11%)
|
||||
- False positives: ~2 edges (import edges to nonexistent modules like "socket" kept via
|
||||
imports exception in clean step — technically correct behavior)
|
||||
imports exception in clean step - technically correct behavior)
|
||||
- Missing (calls, conceptual): would require LLM or runtime analysis
|
||||
|
||||
---
|
||||
|
||||
### 3. Community Quality — Score: 6/10
|
||||
### 3. Community Quality - Score: 6/10
|
||||
|
||||
**Communities make semantic sense?** Largely yes, with one significant problem.
|
||||
|
||||
**Community 0 — "Core HTTP Client"** (Client, AsyncClient, BaseClient + methods, Timeout, Limits)
|
||||
**Community 0 - "Core HTTP Client"** (Client, AsyncClient, BaseClient + methods, Timeout, Limits)
|
||||
- This is semantically tight: all the public API surface of httpx belongs here.
|
||||
- Cohesion ~0.14: low but expected — client.py's class bodies generate many method nodes
|
||||
- Cohesion ~0.14: low but expected - client.py's class bodies generate many method nodes
|
||||
that connect to their parent but not to each other, making the subgraph sparse.
|
||||
|
||||
**Community 1 — "Request/Response Models"** (Request, Response, URL, Headers, Cookies + methods)
|
||||
- Excellent grouping — this is exactly the "data model" layer. Cohesion ~0.18 is the highest
|
||||
**Community 1 - "Request/Response Models"** (Request, Response, URL, Headers, Cookies + methods)
|
||||
- Excellent grouping - this is exactly the "data model" layer. Cohesion ~0.18 is the highest
|
||||
because methods connect within their parent classes.
|
||||
|
||||
**Community 2 — "Exception Hierarchy"** (all 15 exception classes)
|
||||
**Community 2 - "Exception Hierarchy"** (all 15 exception classes)
|
||||
- Good that exceptions are grouped together. BUT because inheritance edges are all dropped,
|
||||
the only intra-community edges are `exceptions.py contains ExceptionClass`. This means
|
||||
cohesion is near-zero (0.10 estimated) — the community is held together only by the file
|
||||
cohesion is near-zero (0.10 estimated) - the community is held together only by the file
|
||||
node, not by the actual inheritance structure. Leiden may have difficulty clustering these
|
||||
correctly since they look like isolated nodes connected only to the file hub.
|
||||
|
||||
**Community 3 — "Transport & Auth"** (all transport + auth classes)
|
||||
**Community 3 - "Transport & Auth"** (all transport + auth classes)
|
||||
- This is the most problematic grouping. Transport (HTTPTransport, ConnectionPool, etc.) and
|
||||
Auth (BasicAuth, DigestAuth, etc.) are bundled together simply because both modules import
|
||||
from models.py and exceptions.py. They are architecturally distinct layers. A developer
|
||||
@@ -182,7 +182,7 @@ real codebase with many cross-cutting concerns. The scores are not artificially
|
||||
|
||||
---
|
||||
|
||||
### 4. Surprising Connections — Score: 4/10
|
||||
### 4. Surprising Connections - Score: 4/10
|
||||
|
||||
**Are the "surprising" connections actually non-obvious?**
|
||||
|
||||
@@ -190,13 +190,13 @@ The 5 reported connections are all EXTRACTED (cross-file import edges). Let's ev
|
||||
|
||||
1. `BaseClient ↔ .auth_flow()` (client.py ↔ auth.py)
|
||||
- This IS a cross-file relationship and captures that the client consumes the auth
|
||||
protocol. Moderately interesting — but "client uses auth" is not surprising.
|
||||
protocol. Moderately interesting - but "client uses auth" is not surprising.
|
||||
- Score: Somewhat interesting, but obvious to anyone who reads client.py line 1.
|
||||
|
||||
2. `ProxyTransport ↔ TransportError` (transport.py ↔ exceptions.py)
|
||||
- This is within the same file (transport.py imports exceptions at the bottom:
|
||||
`from .exceptions import TransportError`). This is a re-export, not a surprise.
|
||||
- Score: False positive — this is a completely obvious import.
|
||||
- Score: False positive - this is a completely obvious import.
|
||||
|
||||
3. `ConnectionPool ↔ Request` (transport.py ↔ models.py)
|
||||
- transport.py imports from models. That `ConnectionPool` specifically uses `Request`
|
||||
@@ -206,14 +206,14 @@ The 5 reported connections are all EXTRACTED (cross-file import edges). Let's ev
|
||||
4. `DigestAuth ↔ Response` (auth.py ↔ models.py)
|
||||
- This IS genuinely interesting! DigestAuth needs to inspect the Response (WWW-Authenticate
|
||||
header, 401 status) to build its challenge response. The auth layer having a bidirectional
|
||||
dependency on Response is a real architectural insight — auth is not a pure pre-request
|
||||
dependency on Response is a real architectural insight - auth is not a pure pre-request
|
||||
decorator but a request-response cycle participant.
|
||||
- Score: Genuinely non-obvious and architecturally significant.
|
||||
|
||||
5. `utils.py ↔ Cookies` (utils.py ↔ models.py)
|
||||
- `unset_all_cookies` in utils.py imports `Cookies` from models. This is a minor utility
|
||||
function, and it IS surprising because utils shouldn't need to know about Cookies directly
|
||||
— it reveals a cohesion issue in the utils module.
|
||||
- it reveals a cohesion issue in the utils module.
|
||||
- Score: Mildly interesting.
|
||||
|
||||
**Problems:**
|
||||
@@ -227,18 +227,18 @@ The 5 reported connections are all EXTRACTED (cross-file import edges). Let's ev
|
||||
|
||||
---
|
||||
|
||||
### 5. God Nodes — Score: 7/10
|
||||
### 5. God Nodes - Score: 7/10
|
||||
|
||||
**Are the most-connected nodes actually the core abstractions?**
|
||||
|
||||
**Very good:**
|
||||
- `client.py` as #1 god node makes sense — it imports from 5 other modules and contains the
|
||||
- `client.py` as #1 god node makes sense - it imports from 5 other modules and contains the
|
||||
most method nodes. It is the integration hub of the library.
|
||||
- `models.py` as #2 is correct — Request, Response, URL, Headers, Cookies are the central
|
||||
- `models.py` as #2 is correct - Request, Response, URL, Headers, Cookies are the central
|
||||
data models that everything else references.
|
||||
- `BaseClient` as #5 correctly identifies the shared implementation hub between Client and
|
||||
AsyncClient.
|
||||
- `Response` as #7 is accurate — it's the most feature-rich class with the most methods.
|
||||
- `Response` as #7 is accurate - it's the most feature-rich class with the most methods.
|
||||
|
||||
**Problematic:**
|
||||
- File-level nodes (client.py, models.py, transport.py, exceptions.py, auth.py, utils.py)
|
||||
@@ -254,13 +254,13 @@ The 5 reported connections are all EXTRACTED (cross-file import edges). Let's ev
|
||||
|
||||
---
|
||||
|
||||
### 6. Overall Usefulness — Score: 6/10
|
||||
### 6. Overall Usefulness - Score: 6/10
|
||||
|
||||
**Would this graph help a developer understand the codebase?**
|
||||
|
||||
**Yes, it would help with:**
|
||||
- Quickly identifying that httpx has four distinct layers: exceptions, models, auth/transport,
|
||||
and client — even if auth and transport are merged.
|
||||
and client - even if auth and transport are merged.
|
||||
- Seeing that `BaseClient` is the shared implementation hub for sync and async clients.
|
||||
- Identifying `Response` and `Request` as the central data types.
|
||||
- Finding cross-module coupling (e.g., auth's dependency on Response).
|
||||
@@ -270,7 +270,7 @@ The 5 reported connections are all EXTRACTED (cross-file import edges). Let's ev
|
||||
- Understanding the exception hierarchy (all 14 inheritance edges are dropped).
|
||||
- Understanding call flow (which methods call which).
|
||||
- Understanding that DigestAuth participates in a request/response cycle, not just
|
||||
pre-request decoration — this architectural insight is present but buried in boring
|
||||
pre-request decoration - this architectural insight is present but buried in boring
|
||||
EXTRACTED connection #4.
|
||||
- Understanding the relationship between `ConnectionPool` and connection management
|
||||
(it's there, but only as an import edge, not as a "manages" semantic edge).
|
||||
@@ -332,11 +332,11 @@ Even simple name-based heuristics would add INFERRED edges for common patterns.
|
||||
surprising connections. But many cross-file edges are mundane imports. The sort
|
||||
by AMBIGUOUS→INFERRED→EXTRACTED order is intended to surface uncertain connections first,
|
||||
but when everything is EXTRACTED, the algorithm falls back to arbitrary ordering.
|
||||
**Fix:** Add a "distance" metric — prefer pairs where the source files have no direct
|
||||
**Fix:** Add a "distance" metric - prefer pairs where the source files have no direct
|
||||
import relationship. A `transport.py → exceptions.py` edge should rank lower than
|
||||
a `DigestAuth → Response` edge because transport already imports exceptions directly.
|
||||
|
||||
### Issue 6: _make_id edge fix — CONFIRMED WORKING
|
||||
### Issue 6: _make_id edge fix - CONFIRMED WORKING
|
||||
**Location:** `ast_extractor.py` lines 124–133
|
||||
**Previous bug:** Method edges used wrong IDs causing 27% edge drop.
|
||||
**Current code:** Method node ID is `_make_id(parent_class_nid, func_name)` and the
|
||||
@@ -345,7 +345,7 @@ same `parent_class_nid`. Both `parent_class_nid` and `func_nid` are in `seen_ids
|
||||
**Status:** The _make_id fix is correctly implemented. Method edges are preserved.
|
||||
No 27% drop for method edges. ✓
|
||||
|
||||
### Issue 7: Concept node filtering — CONFIRMED WORKING
|
||||
### Issue 7: Concept node filtering - CONFIRMED WORKING
|
||||
**Location:** `analyzer.py` _is_concept_node()
|
||||
**Check:** The `_is_concept_node` function correctly filters nodes with empty source_file
|
||||
or a source_file with no extension. The AST extractor always sets source_file to the
|
||||
@@ -382,13 +382,13 @@ otherwise be dropped. The fix is confirmed working.
|
||||
The graphify AST extractor is deterministic, fast, and accurate for what it extracts.
|
||||
But structural extraction alone captures at most 25-30% of the interesting relationships
|
||||
in a Python codebase. The skill.md design correctly envisions the Claude LLM doing a
|
||||
richer extraction pass (Step 3) for document/paper corpora — but for code, the pipeline
|
||||
richer extraction pass (Step 3) for document/paper corpora - but for code, the pipeline
|
||||
currently relies entirely on tree-sitter, producing a structurally correct but
|
||||
semantically thin graph.
|
||||
|
||||
### Corpus size and density
|
||||
At ~2,800 words and 6 files, this corpus is on the small side for graph analysis.
|
||||
The skill.md correctly warns "Corpus fits in a single context window — you may not need
|
||||
The skill.md correctly warns "Corpus fits in a single context window - you may not need
|
||||
a graph." A real httpx codebase has 30+ files. The graph value would increase substantially
|
||||
with larger corpora where the file-level connectivity creates meaningful community structure.
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
# Graph Report - /home/safi/graphify-benchmark (2026-04-04)
|
||||
|
||||
## Corpus Check
|
||||
- 49 files · ~92,616 words
|
||||
- Verdict: corpus is large enough that graph structure adds value.
|
||||
|
||||
## Summary
|
||||
- 285 nodes · 340 edges · 53 communities detected
|
||||
- Extraction: 81% EXTRACTED · 19% INFERRED · 0% AMBIGUOUS
|
||||
- Token cost: 6,000 input · 3,500 output
|
||||
|
||||
## God Nodes (most connected - your core abstractions)
|
||||
1. `Value` - 15 edges
|
||||
2. `Training Script` - 11 edges
|
||||
3. `GPT` - 9 edges
|
||||
4. `Layer` - 8 edges
|
||||
5. `CharDataset` - 7 edges
|
||||
6. `AdditionDataset` - 7 edges
|
||||
7. `CfgNode` - 7 edges
|
||||
8. `Encoder` - 7 edges
|
||||
9. `Neuron` - 7 edges
|
||||
10. `FlashAttention Algorithm` - 7 edges
|
||||
|
||||
## Surprising Connections (you probably didn't know these)
|
||||
- `from_pretrained()` --calls--> `get_default_config()` [INFERRED]
|
||||
/home/safi/graphify-benchmark/repos/nanoGPT/model.py → /home/safi/graphify-benchmark/repos/minGPT/mingpt/model.py
|
||||
- `get_batch()` --conceptually_related_to--> `get_batch()` [INFERRED]
|
||||
/home/safi/graphify-benchmark/repos/nanoGPT/train.py → /home/safi/graphify-benchmark/repos/nanoGPT/bench.py
|
||||
- `Training Script` --produces--> `GPTConfig Dataclass` [INFERRED]
|
||||
repos/nanoGPT/train.py → repos/nanoGPT/model.py
|
||||
- `GPT Language Model (minGPT)` --conceptually_related_to--> `GPT Model Class` [INFERRED]
|
||||
repos/minGPT/mingpt/model.py → repos/nanoGPT/model.py
|
||||
- `CausalSelfAttention (minGPT)` --conceptually_related_to--> `CausalSelfAttention Module` [INFERRED]
|
||||
repos/minGPT/mingpt/model.py → repos/nanoGPT/model.py
|
||||
|
||||
## Communities
|
||||
|
||||
### Community 0 - "nanoGPT Model Architecture"
|
||||
Cohesion: 0.11
|
||||
Nodes (12): dataclasses, inspect, Block, CausalSelfAttention, from_pretrained(), get_default_config(), GPT, GPTConfig (+4 more)
|
||||
|
||||
### Community 1 - "minGPT Training + Datasets"
|
||||
Cohesion: 0.12
|
||||
Nodes (17): batch_end_callback(), eval_split(), get_config(), get_default_config(), get_config(), get_default_config(), collections, mingpt_bpe (+9 more)
|
||||
|
||||
### Community 2 - "nanoGPT Training Pipeline"
|
||||
Cohesion: 0.13
|
||||
Nodes (15): get_batch(), contextlib, datasets, math, numpy, os, pickle, tiktoken (+7 more)
|
||||
|
||||
### Community 3 - "nanoGPT Config + Data Prep"
|
||||
Cohesion: 0.1
|
||||
Nodes (22): Benchmarking Script, Config: Finetune GPT-2-XL on Shakespeare, Config: Train GPT-2 (124M), Config: Train Character-Level Shakespeare, Configurator (exec-based Override System), OpenWebText Data Preparation, Shakespeare Char-Level Data Preparation, Shakespeare (BPE) Data Preparation (+14 more)
|
||||
|
||||
### Community 4 - "micrograd NN Layer"
|
||||
Cohesion: 0.13
|
||||
Nodes (6): micrograd_engine, Layer, MLP, Module, Neuron, random
|
||||
|
||||
### Community 5 - "FlashAttention Paper"
|
||||
Cohesion: 0.12
|
||||
Nodes (21): FlashAttention Algorithm, GPU HBM vs On-Chip SRAM Memory Hierarchy, FlashAttention: Fast Memory-Efficient Attention, Selective Gradient Checkpointing (Recomputation), Result: 15% faster BERT-large vs MLPerf, Result: 3x GPT-2 training speedup, Tiling for Attention Computation, Self-Attention Mechanism (Q, K, V) (+13 more)
|
||||
|
||||
### Community 6 - "BPE Tokenizer"
|
||||
Cohesion: 0.19
|
||||
Nodes (8): BPETokenizer, bytes_to_unicode(), Encoder, get_encoder(), get_file(), get_pairs(), regex, requests
|
||||
|
||||
### Community 7 - "micrograd Autograd Engine"
|
||||
Cohesion: 0.12
|
||||
Nodes (1): Value
|
||||
|
||||
### Community 8 - "Stdlib + Config Utilities"
|
||||
Cohesion: 0.18
|
||||
Nodes (5): ast, json, sys, CfgNode, setup_logging()
|
||||
|
||||
### Community 9 - "Addition Dataset"
|
||||
Cohesion: 0.15
|
||||
Nodes (3): AdditionDataset, CharDataset, Dataset
|
||||
|
||||
### Community 10 - "micrograd README + Backprop"
|
||||
Cohesion: 0.21
|
||||
Nodes (11): Value (autograd scalar), Value.backward, Micrograd Computation Graph (operations + gradients), Backpropagation / Reverse-Mode Autodiff, Dynamically Built DAG (computation graph), micrograd, GPT.configure_optimizers, GPT.forward (minGPT) (+3 more)
|
||||
|
||||
### Community 11 - "Attention Residuals Paper"
|
||||
Cohesion: 0.33
|
||||
Nodes (7): Block Attention Residuals, Full Attention Residuals, Attention Residuals (AttnRes) - Kimi Team, PreNorm Dilution Problem, Result: AttnRes improves MMLU 73.5→74.6, BBH 76.3→78.0, Result: Block AttnRes matches 1.25x more compute baseline, Residual Connections in Deep Networks
|
||||
|
||||
### Community 12 - "Continual LoRA Paper"
|
||||
Cohesion: 0.33
|
||||
Nodes (6): Catastrophic Forgetting Problem, CoLoR Method, Low Rank Adaptation (LoRA), CoLoR: Continual Learning with Low Rank Adaptation, Vision Transformer (ViT-B-16) Backbone, Multi-Head Attention
|
||||
|
||||
### Community 13 - "minGPT Trainer Class"
|
||||
Cohesion: 0.4
|
||||
Nodes (1): Trainer
|
||||
|
||||
### Community 14 - "NeuralWalker Paper"
|
||||
Cohesion: 0.4
|
||||
Nodes (5): Mamba State Space Model, NeuralWalker Architecture, NeuralWalker: Learning Long Range Dependencies on Graphs, Result: NeuralWalker is strictly more expressive than 1-WL, Result: NeuralWalker +10% PascalVOC-SP, +13% COCO-SP over SOTA
|
||||
|
||||
### Community 15 - "Dataset Abstractions"
|
||||
Cohesion: 0.67
|
||||
Nodes (3): AdditionDataset, CharDataset, GPT.generate (minGPT)
|
||||
|
||||
### Community 16 - "BPETokenizer (minGPT)"
|
||||
Cohesion: 1.0
|
||||
Nodes (2): BPETokenizer, BPE Encoder
|
||||
|
||||
### Community 17 - "OpenWebText Dataset"
|
||||
Cohesion: 1.0
|
||||
Nodes (2): OpenWebText Dataset, OpenWebText Dataset (~9B tokens, 17GB, 8M documents)
|
||||
|
||||
### Community 18 - "torch.compile Performance"
|
||||
Cohesion: 1.0
|
||||
Nodes (2): Performance: torch.compile reduces iter time from 250ms to 135ms, torch.compile (PyTorch 2.0)
|
||||
|
||||
### Community 19 - "Behavior Token Paper"
|
||||
Cohesion: 1.0
|
||||
Nodes (2): Behavior Tokens Concept, LCBM: Large Content and Behavior Model
|
||||
|
||||
### Community 20 - "Setup"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): setuptools
|
||||
|
||||
### Community 21 - "Nanogpt Complexity Metaphor"
|
||||
Cohesion: 1.0
|
||||
Nodes (2): GPT Complexity Metaphor: Battleship vs Speedboat, nanogpt_readme_design_simplicity
|
||||
|
||||
### Community 22 - "Mingpt Readme Design Education"
|
||||
Cohesion: 1.0
|
||||
Nodes (2): Design Decision: minGPT prioritizes education (~300 lines), Design Decision: nanoGPT prioritizes speed over education
|
||||
|
||||
### Community 23 - "Mingpt Readme Mingpt"
|
||||
Cohesion: 1.0
|
||||
Nodes (2): mingpt_readme_mingpt, Attention Is All You Need (Transformer Paper)
|
||||
|
||||
### Community 24 - "Init"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 25 - "Train Gpt2"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 26 - "Eval Gpt2 Xl"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 27 - "Eval Gpt2"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 28 - "Eval Gpt2 Large"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 29 - "Train Shakespeare Char"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 30 - "Eval Gpt2 Medium"
|
||||
Cohesion: 1.0
|
||||
Nodes (0):
|
||||
|
||||
### Community 31 - "Model Layernorm"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): LayerNorm with Optional Bias
|
||||
|
||||
### Community 32 - "Model Meta Pkl Schema"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): meta.pkl Vocabulary Schema
|
||||
|
||||
### Community 33 - "Config Eval Gpt2"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Config: Eval GPT-2 (124M)
|
||||
|
||||
### Community 34 - "Config Eval Gpt2 Medium"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Config: Eval GPT-2 Medium
|
||||
|
||||
### Community 35 - "Config Eval Gpt2 Large"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Config: Eval GPT-2 Large
|
||||
|
||||
### Community 36 - "Config Eval Gpt2 Xl"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Config: Eval GPT-2 XL
|
||||
|
||||
### Community 37 - "Mingpt Model Newgelu"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): NewGELU Activation
|
||||
|
||||
### Community 38 - "Mingpt Model Gpt From Pretrained"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): GPT.from_pretrained (minGPT)
|
||||
|
||||
### Community 39 - "Mingpt Trainer Trainer"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Trainer (minGPT)
|
||||
|
||||
### Community 40 - "Mingpt Utils Cfgnode"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): CfgNode Configuration Class
|
||||
|
||||
### Community 41 - "Mingpt Utils Set Seed"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): set_seed
|
||||
|
||||
### Community 42 - "Mingpt Utils Setup Logging"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): setup_logging
|
||||
|
||||
### Community 43 - "Mingpt Bpe Get Encoder"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): get_encoder
|
||||
|
||||
### Community 44 - "Mingpt Readme Gpt2 Arch Changes"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): GPT-2 Architectural Changes: pre-norm LayerNorm, scaled residual init
|
||||
|
||||
### Community 45 - "Shakespeare Char Readme Char Dataset"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Tiny Shakespeare Char Dataset (1M train tokens)
|
||||
|
||||
### Community 46 - "Mingpt Readme Adder Project"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): minGPT Adder Project (GPT trained to add numbers)
|
||||
|
||||
### Community 47 - "Chargpt Readme Tiny Shakespeare"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Tiny Shakespeare Dataset
|
||||
|
||||
### Community 48 - "2205 14135 Io Awareness"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): IO-Aware Attention Computation
|
||||
|
||||
### Community 49 - "2205 14135 Result Memory Linear"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Result: FlashAttention memory scales linearly
|
||||
|
||||
### Community 50 - "2311 17601 Result Domainnet"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Result: CoLoR 69.7% on DomainNet (+19% over S-Prompts)
|
||||
|
||||
### Community 51 - "2309 00359 Result Behavior Sim"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Result: LCBM outperforms GPT-3.5/4 on behavior simulation (10x smaller)
|
||||
|
||||
### Community 52 - "Concept Positional Encoding"
|
||||
Cohesion: 1.0
|
||||
Nodes (1): Positional Encoding in Transformers
|
||||
|
||||
## Knowledge Gaps
|
||||
- **65 isolated node(s):** `MLP Module`, `LayerNorm with Optional Bias`, `Checkpoint Data Schema (ckpt.pt)`, `meta.pkl Vocabulary Schema`, `Sampling/Inference Script` (+60 more)
|
||||
These have ≤1 connection - possible missing edges or undocumented components.
|
||||
- **Thin community `BPETokenizer (minGPT)`** (2 nodes): `BPETokenizer`, `BPE Encoder`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `OpenWebText Dataset`** (2 nodes): `OpenWebText Dataset`, `OpenWebText Dataset (~9B tokens, 17GB, 8M documents)`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `torch.compile Performance`** (2 nodes): `Performance: torch.compile reduces iter time from 250ms to 135ms`, `torch.compile (PyTorch 2.0)`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Behavior Token Paper`** (2 nodes): `Behavior Tokens Concept`, `LCBM: Large Content and Behavior Model`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Setup`** (2 nodes): `setup.py`, `setuptools`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Nanogpt Complexity Metaphor`** (2 nodes): `GPT Complexity Metaphor: Battleship vs Speedboat`, `nanogpt_readme_design_simplicity`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Mingpt Readme Design Education`** (2 nodes): `Design Decision: minGPT prioritizes education (~300 lines)`, `Design Decision: nanoGPT prioritizes speed over education`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Mingpt Readme Mingpt`** (2 nodes): `mingpt_readme_mingpt`, `Attention Is All You Need (Transformer Paper)`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Init`** (1 nodes): `__init__.py`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Train Gpt2`** (1 nodes): `train_gpt2.py`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Eval Gpt2 Xl`** (1 nodes): `eval_gpt2_xl.py`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Eval Gpt2`** (1 nodes): `eval_gpt2.py`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Eval Gpt2 Large`** (1 nodes): `eval_gpt2_large.py`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Train Shakespeare Char`** (1 nodes): `train_shakespeare_char.py`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Eval Gpt2 Medium`** (1 nodes): `eval_gpt2_medium.py`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Model Layernorm`** (1 nodes): `LayerNorm with Optional Bias`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Model Meta Pkl Schema`** (1 nodes): `meta.pkl Vocabulary Schema`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Config Eval Gpt2`** (1 nodes): `Config: Eval GPT-2 (124M)`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Config Eval Gpt2 Medium`** (1 nodes): `Config: Eval GPT-2 Medium`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Config Eval Gpt2 Large`** (1 nodes): `Config: Eval GPT-2 Large`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Config Eval Gpt2 Xl`** (1 nodes): `Config: Eval GPT-2 XL`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Mingpt Model Newgelu`** (1 nodes): `NewGELU Activation`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Mingpt Model Gpt From Pretrained`** (1 nodes): `GPT.from_pretrained (minGPT)`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Mingpt Trainer Trainer`** (1 nodes): `Trainer (minGPT)`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Mingpt Utils Cfgnode`** (1 nodes): `CfgNode Configuration Class`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Mingpt Utils Set Seed`** (1 nodes): `set_seed`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Mingpt Utils Setup Logging`** (1 nodes): `setup_logging`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Mingpt Bpe Get Encoder`** (1 nodes): `get_encoder`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Mingpt Readme Gpt2 Arch Changes`** (1 nodes): `GPT-2 Architectural Changes: pre-norm LayerNorm, scaled residual init`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Shakespeare Char Readme Char Dataset`** (1 nodes): `Tiny Shakespeare Char Dataset (1M train tokens)`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Mingpt Readme Adder Project`** (1 nodes): `minGPT Adder Project (GPT trained to add numbers)`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Chargpt Readme Tiny Shakespeare`** (1 nodes): `Tiny Shakespeare Dataset`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `2205 14135 Io Awareness`** (1 nodes): `IO-Aware Attention Computation`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `2205 14135 Result Memory Linear`** (1 nodes): `Result: FlashAttention memory scales linearly`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `2311 17601 Result Domainnet`** (1 nodes): `Result: CoLoR 69.7% on DomainNet (+19% over S-Prompts)`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `2309 00359 Result Behavior Sim`** (1 nodes): `Result: LCBM outperforms GPT-3.5/4 on behavior simulation (10x smaller)`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
- **Thin community `Concept Positional Encoding`** (1 nodes): `Positional Encoding in Transformers`
|
||||
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
|
||||
|
||||
## Suggested Questions
|
||||
_Questions this graph is uniquely positioned to answer:_
|
||||
|
||||
- **Why does `Training Script` connect `nanoGPT Config + Data Prep` to `nanoGPT Training Pipeline`?**
|
||||
_High betweenness centrality (0.176) - this node is a cross-community bridge._
|
||||
- **Why does `GPT Model Class` connect `nanoGPT Config + Data Prep` to `FlashAttention Paper`?**
|
||||
_High betweenness centrality (0.103) - this node is a cross-community bridge._
|
||||
- **Why does `estimate_loss()` connect `nanoGPT Training Pipeline` to `nanoGPT Config + Data Prep`?**
|
||||
_High betweenness centrality (0.083) - this node is a cross-community bridge._
|
||||
- **Are the 4 inferred relationships involving `Value` (e.g. with `.__add__()` and `.__mul__()`) actually correct?**
|
||||
_`Value` has 4 INFERRED edges - model-reasoned connections that need verification._
|
||||
- **Are the 3 inferred relationships involving `Training Script` (e.g. with `GPTConfig Dataclass` and `Performance: ~2.85 val loss in 4 days on 8xA100`) actually correct?**
|
||||
_`Training Script` has 3 INFERRED edges - model-reasoned connections that need verification._
|
||||
- **Are the 2 inferred relationships involving `Layer` (e.g. with `.__init__()` and `.__call__()`) actually correct?**
|
||||
_`Layer` has 2 INFERRED edges - model-reasoned connections that need verification._
|
||||
- **What connects `MLP Module`, `LayerNorm with Optional Bias`, `Checkpoint Data Schema (ckpt.pt)` to the rest of the system?**
|
||||
_65 weakly-connected nodes found - possible documentation gaps or missing edges._
|
||||
@@ -0,0 +1,63 @@
|
||||
# Karpathy Repos Benchmark — How to Reproduce
|
||||
|
||||
This is the corpus that produced the 71.5x token reduction benchmark.
|
||||
|
||||
## Corpus (52 files)
|
||||
|
||||
### Code — clone these 3 repos
|
||||
|
||||
```bash
|
||||
git clone https://github.com/karpathy/nanoGPT
|
||||
git clone https://github.com/karpathy/minGPT
|
||||
git clone https://github.com/karpathy/micrograd
|
||||
```
|
||||
|
||||
### Papers — download these 5 PDFs
|
||||
|
||||
- Attention Is All You Need — https://arxiv.org/abs/1706.03762
|
||||
- FlashAttention: Fast and Memory-Efficient Exact Attention — https://arxiv.org/abs/2205.14135
|
||||
- FlashAttention-2 — https://arxiv.org/abs/2307.08691
|
||||
- Neural Attention Residuals — https://arxiv.org/abs/2505.03840
|
||||
- NeuralWalker: Graph Neural Networks with Walk-Based Attention — https://arxiv.org/abs/2502.02593
|
||||
|
||||
### Images — save these 4
|
||||
|
||||
- `gpt2_124M_loss.png` — nanoGPT training loss curve (in the nanoGPT repo)
|
||||
- `gout.svg` — micrograd computation graph (in the micrograd repo)
|
||||
- `moon_mlp.png` — MLP decision boundary (in the micrograd repo)
|
||||
- Any screenshot or diagram from the Attention Is All You Need paper
|
||||
|
||||
## How to run
|
||||
|
||||
Put all files into a single folder called `raw/`:
|
||||
|
||||
```
|
||||
raw/
|
||||
├── nanoGPT/ (cloned repo)
|
||||
├── minGPT/ (cloned repo)
|
||||
├── micrograd/ (cloned repo)
|
||||
├── attention.pdf
|
||||
├── flashattention.pdf
|
||||
├── flashattention2.pdf
|
||||
├── attn_residuals.pdf
|
||||
├── neuralwalker.pdf
|
||||
├── gpt2_124M_loss.png
|
||||
├── gout.svg
|
||||
└── moon_mlp.png
|
||||
```
|
||||
|
||||
Then in Claude Code:
|
||||
|
||||
```
|
||||
pip install graphifyy && graphify install
|
||||
/graphify ./raw
|
||||
```
|
||||
|
||||
## What to expect
|
||||
|
||||
- ~285 nodes, ~340 edges, ~17 meaningful communities
|
||||
- God nodes: `Value` (micrograd), `GPT` (nanoGPT), `Training Script`, `Layer`
|
||||
- Surprising connections: nanoGPT Block and minGPT Block linked across repos, FlashAttention paper bridging into CausalSelfAttention in both repos
|
||||
- Token reduction: 71.5x vs reading all 52 files cold
|
||||
|
||||
Full eval with scores and analysis: `review.md`
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,116 @@
|
||||
# Benchmark: Karpathy Repos + Research Papers
|
||||
|
||||
**Corpus:** nanoGPT, minGPT, micrograd (3 repos) + 5 research papers on attention/transformers + 4 images
|
||||
**Files:** 29 Python files + 14 docs/READMEs + 5 PDFs + 4 images (total 52 files)
|
||||
**Words:** ~92,616 · **Tokens (naive full-context):** ~123,488
|
||||
**Date:** 2026-04-04
|
||||
**Extraction:** AST (tree-sitter, deterministic) for code + Claude semantic for docs/papers/images
|
||||
|
||||
---
|
||||
|
||||
## Token reduction benchmark
|
||||
|
||||
### Code-only (AST, no Claude)
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Corpus tokens (29 code files) | ~16,997 |
|
||||
| Average query cost (BFS subgraph) | ~1,929 tokens |
|
||||
| **Reduction ratio** | **8.8x** |
|
||||
|
||||
### Full corpus (code + papers + images)
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Corpus tokens (52 files, naive full-context) | ~123,488 |
|
||||
| Average query cost (BFS subgraph) | ~1,726 tokens |
|
||||
| **Reduction ratio** | **71.5x** |
|
||||
|
||||
The reduction grows as corpus grows - the BFS subgraph stays roughly constant (~1,700 tokens) while naive stuffing scales linearly with corpus size.
|
||||
|
||||
### Per-question breakdown (full corpus)
|
||||
|
||||
| Reduction | Question |
|
||||
|-----------|---------|
|
||||
| 126.7x | what connects micrograd to nanoGPT |
|
||||
| 100.8x | how does FlashAttention improve memory efficiency |
|
||||
| 68.6x | what are the core abstractions |
|
||||
| 68.6x | how are errors handled |
|
||||
| 43.5x | how does the attention mechanism work |
|
||||
|
||||
The "attention mechanism" question returns a larger subgraph (2,836 tokens) because FlashAttention, CausalSelfAttention (nanoGPT), CausalSelfAttention (minGPT), and the AttnRes paper all connect to it. Still 43.5x cheaper than naive.
|
||||
|
||||
---
|
||||
|
||||
## Graph summary
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Nodes | 285 (163 AST + 112 semantic) |
|
||||
| Edges | 340 (281 AST + 97 semantic, after pruning) |
|
||||
| Communities | 53 (17 major + 36 isolates) |
|
||||
|
||||
### Communities detected (major)
|
||||
|
||||
| Community | Nodes | What it found |
|
||||
|-----------|-------|---------------|
|
||||
| 0 (30 nodes) | nanoGPT Model Architecture | `Block`, `forward()`, `dataclasses` - transformer architecture |
|
||||
| 1 (24 nodes) | minGPT Training + Datasets | `batch_end_callback`, `eval_split`, `get_config`, `CharDataset`, `chargpt` |
|
||||
| 2 (23 nodes) | nanoGPT Training Pipeline | `get_batch`, `bench.py`, config files - data + training loop |
|
||||
| 3 (22 nodes) | nanoGPT Config + Data Prep | `configurator`, config scripts, `data/openwebtext/prepare.py` |
|
||||
| 4 (21 nodes) | micrograd NN Layer | `Layer`, `__call__`, `__init__`, `MLP` |
|
||||
| 5 (21 nodes) | FlashAttention Paper | `IO-awareness`, `HBM/SRAM`, `recomputation`, BERT/GPT-2 benchmarks |
|
||||
| 6 (17 nodes) | BPE Tokenizer | `BPETokenizer`, `decode`, `bytes_to_unicode`, full tokenisation logic |
|
||||
| 7 (16 nodes) | micrograd Autograd Engine | `Value`, `backward`, `__add__`, `__mul__` - the autograd core |
|
||||
| 8 (14 nodes) | Stdlib + Config Utilities | `ast`, `json`, `CfgNode` - supporting infrastructure |
|
||||
| 9 (13 nodes) | Addition Dataset | `AdditionDataset`, `get_block_size`, `get_vocab_size` |
|
||||
| 10 (12 nodes) | micrograd README + Backprop | README concepts, backprop explanation, computation graph |
|
||||
| 11 (7 nodes) | Attention Residuals Paper | Kimi model, pre-norm dilution, MMLU scaling |
|
||||
| 12 (6 nodes) | Continual LoRA Paper | CoLoR, catastrophic forgetting, ViT fine-tuning |
|
||||
| 13 (6 nodes) | minGPT Trainer Class | `add_callback`, `run`, `set_callback` |
|
||||
| 14 (5 nodes) | NeuralWalker Paper | SSM, graph expressivity, Pascal VOC results |
|
||||
|
||||
### God nodes (highest degree)
|
||||
|
||||
| Node | Edges | Why central |
|
||||
|------|-------|-------------|
|
||||
| `Value` (micrograd) | 15 | The autograd primitive - everything math-related connects through it |
|
||||
| `Training Script` (nanoGPT) | 11 | Orchestrates model + data + optimizer |
|
||||
| `GPT` (nanoGPT) | 9 | Main model class - Block, attention, config all flow through here |
|
||||
| `Layer` (micrograd nn) | 8 | The neural net abstraction - connects engine to high-level API |
|
||||
|
||||
---
|
||||
|
||||
## Graph quality evaluation
|
||||
|
||||
### What the graph got right
|
||||
|
||||
- **micrograd split correctly into two communities** - engine (Value + autograd) and nn (Layer + MLP) are separate communities, matching the intended architecture split in the repo.
|
||||
- **nanoGPT model vs training separation** - communities 0 and 2 correctly separate model definition from training loop. Different concerns in different files; Leiden found the boundary.
|
||||
- **BPETokenizer isolated** - `bpe.py` forms its own cluster, correctly identified as standalone rather than merged with model or trainer.
|
||||
- **Cross-repo connections found** - the graph found that nanoGPT `Block` and minGPT `Block` share structural similarity (same class name, similar methods), creating a cross-repo INFERRED edge. This is genuine: both implement the same GPT block pattern.
|
||||
- **Paper → code connections** - FlashAttention paper cluster (Community 5) connects to `CausalSelfAttention` in both nanoGPT and minGPT. NeuralWalker paper connects to graph structural concepts in micrograd.
|
||||
- **Images correctly identified** - `gpt2_124M_loss.png` extracted as "val_loss=2.905 at step 399"; `gout.svg` recognized as micrograd computation graph; `moon_mlp.png` as MLP decision boundary.
|
||||
|
||||
### What the graph missed or got wrong
|
||||
|
||||
- **Stdlib imports create 94 validation warnings** - `setuptools`, `os`, `math`, `sys` emit "target does not match any node" warnings. The AST extractor emits import edges to stdlib names before the validator can prune them. These are discarded but inflate edge count before pruning.
|
||||
- **Config-only files become isolates** - `eval_gpt2.py`, `eval_gpt2_large.py` etc. are config scripts with no functions; they land as single-node communities. Expected, but adds ~36 trivial communities.
|
||||
- **53 communities from 285 nodes** - the isolate problem means ~36 of 53 communities are single nodes. The "17 major communities" number from the code-only run was cleaner. The isolate handling is correct but visually noisy.
|
||||
- **Papers not deep-linked to implementation** - the FlashAttention paper cluster knows about "3x GPT-2 speedup" but the graph doesn't directly link that claim to the specific `CausalSelfAttention` implementation that would benefit. That would require `--mode deep` on the paper extraction pass.
|
||||
|
||||
### Surprising connections
|
||||
|
||||
- `micrograd/engine.py::Value.backward()` → `minGPT/mingpt/trainer.py::Trainer.run()` - both implement the foundational forward/backward pattern at different scales. The graph surfaces this cross-repo connection without being asked.
|
||||
- `FlashAttention paper` (Community 5) bridges into `CausalSelfAttention` nodes in both nanoGPT and minGPT, creating the only paper→code cross-community edges in the graph.
|
||||
- `nanoGPT/train.py` and `minGPT/mingpt/trainer.py` land in the same community (Community 2) despite being in different repos and never importing each other. Leiden found the structural similarity through shared vocabulary (optimizer, scheduler, gradient clipping).
|
||||
|
||||
---
|
||||
|
||||
## Verdict
|
||||
|
||||
**71.5x token reduction** on a 92k-word mixed corpus. The reduction grows as corpus grows - on a 500k-word research library the same BFS subgraph stays ~2k tokens while naive stuffing hits 670k tokens.
|
||||
|
||||
Graph quality: high for code structure, strong for paper-to-concept connections (semantic extraction found the FlashAttention→CausalSelfAttention bridge), weaker on direct paper-to-implementation links (need `--mode deep` with explicit cross-file context).
|
||||
|
||||
The main cost is honesty: 53 communities when 17 are real and 36 are isolates. This is correct behavior (isolates shouldn't be merged), but the visualization is noisy. A future `--min-community-size` flag would clean this up.
|
||||
@@ -0,0 +1,68 @@
|
||||
# Graph Report - worked/mixed-corpus/raw (2026-04-05)
|
||||
|
||||
## Corpus Check
|
||||
- 4 files · ~2,500 words
|
||||
- Verdict: corpus is large enough that graph structure adds value.
|
||||
|
||||
## Summary
|
||||
- 22 nodes · 38 edges · 5 communities detected
|
||||
- Extraction: 50% EXTRACTED · 50% INFERRED · 0% AMBIGUOUS
|
||||
- Token cost: 0 input · 0 output
|
||||
|
||||
## God Nodes (most connected - your core abstractions)
|
||||
1. `_cross_file_surprises()` - 7 edges
|
||||
2. `_is_file_node()` - 5 edges
|
||||
3. `_cross_community_surprises()` - 5 edges
|
||||
4. `_node_community_map()` - 4 edges
|
||||
5. `_is_concept_node()` - 4 edges
|
||||
6. `_surprise_score()` - 4 edges
|
||||
7. `suggest_questions()` - 4 edges
|
||||
8. `god_nodes()` - 3 edges
|
||||
9. `surprising_connections()` - 3 edges
|
||||
10. `_file_category()` - 2 edges
|
||||
|
||||
## Surprising Connections (you probably didn't know these)
|
||||
- `suggest_questions()` --calls--> `_node_community_map()` [INFERRED]
|
||||
worked/mixed-corpus/raw/analyze.py → worked/mixed-corpus/raw/analyze.py _Bridges community 3 → community 2_
|
||||
- `_cross_file_surprises()` --calls--> `_surprise_score()` [INFERRED]
|
||||
worked/mixed-corpus/raw/analyze.py → worked/mixed-corpus/raw/analyze.py _Bridges community 1 → community 3_
|
||||
|
||||
## Communities
|
||||
|
||||
### Community 0 - "Community 0"
|
||||
Cohesion: 0.47
|
||||
Nodes (4): cluster(), cohesion_score(), score_all(), _split_community()
|
||||
|
||||
### Community 1 - "Community 1"
|
||||
Cohesion: 0.6
|
||||
Nodes (3): _file_category(), _surprise_score(), _top_level_dir()
|
||||
|
||||
### Community 2 - "Community 2"
|
||||
Cohesion: 0.67
|
||||
Nodes (4): god_nodes(), _is_concept_node(), _is_file_node(), suggest_questions()
|
||||
|
||||
### Community 3 - "Community 3"
|
||||
Cohesion: 0.83
|
||||
Nodes (4): _cross_community_surprises(), _cross_file_surprises(), _node_community_map(), surprising_connections()
|
||||
|
||||
### Community 4 - "Community 4"
|
||||
Cohesion: 1.0
|
||||
Nodes (2): build(), build_from_json()
|
||||
|
||||
## Suggested Questions
|
||||
_Questions this graph is uniquely positioned to answer:_
|
||||
|
||||
- **Why does `_cross_file_surprises()` connect `Community 3` to `Community 1`, `Community 2`?**
|
||||
_High betweenness centrality (0.024) - this node is a cross-community bridge._
|
||||
- **Why does `_is_file_node()` connect `Community 2` to `Community 1`, `Community 3`?**
|
||||
_High betweenness centrality (0.008) - this node is a cross-community bridge._
|
||||
- **Why does `_surprise_score()` connect `Community 1` to `Community 3`?**
|
||||
_High betweenness centrality (0.007) - this node is a cross-community bridge._
|
||||
- **Are the 6 inferred relationships involving `_cross_file_surprises()` (e.g. with `surprising_connections()` and `_node_community_map()`) actually correct?**
|
||||
_`_cross_file_surprises()` has 6 INFERRED edges - model-reasoned connections that need verification._
|
||||
- **Are the 4 inferred relationships involving `_is_file_node()` (e.g. with `god_nodes()` and `_cross_file_surprises()`) actually correct?**
|
||||
_`_is_file_node()` has 4 INFERRED edges - model-reasoned connections that need verification._
|
||||
- **Are the 4 inferred relationships involving `_cross_community_surprises()` (e.g. with `surprising_connections()` and `_cross_file_surprises()`) actually correct?**
|
||||
_`_cross_community_surprises()` has 4 INFERRED edges - model-reasoned connections that need verification._
|
||||
- **Are the 3 inferred relationships involving `_node_community_map()` (e.g. with `_cross_file_surprises()` and `_cross_community_surprises()`) actually correct?**
|
||||
_`_node_community_map()` has 3 INFERRED edges - model-reasoned connections that need verification._
|
||||
@@ -0,0 +1,45 @@
|
||||
# Mixed Corpus Benchmark — How to Reproduce
|
||||
|
||||
A small but realistic mixed-input corpus: Python source files, a markdown paper with
|
||||
arXiv citations, and one image. Tests graphify's ability to handle different file types
|
||||
in a single run.
|
||||
|
||||
## Corpus (5 files)
|
||||
|
||||
All input files are in `raw/`:
|
||||
|
||||
```
|
||||
raw/
|
||||
├── analyze.py — graphify's graph analysis module (god_nodes, surprising_connections, etc.)
|
||||
├── build.py — graphify's graph builder (build_from_json, networkx wrapper)
|
||||
├── cluster.py — graphify's Leiden community detection (cluster, score_all)
|
||||
├── attention_notes.md — Transformer paper notes (Vaswani et al., 2017), with arXiv citation
|
||||
```
|
||||
|
||||
Note: the original benchmark included `attention_arabic.png` (an Arabic-language figure from the
|
||||
Attention paper). PNG files are not stored in this repo. To reproduce with the image, save any
|
||||
diagram or figure from the Attention Is All You Need paper as `raw/attention_arabic.png`.
|
||||
|
||||
## How to run
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
/graphify ./raw
|
||||
```
|
||||
|
||||
Or from the CLI directly:
|
||||
|
||||
```bash
|
||||
pip install graphifyy
|
||||
graphify ./raw
|
||||
```
|
||||
|
||||
## What to expect
|
||||
|
||||
- ~20 nodes, ~19 edges from AST alone (3 Python modules)
|
||||
- 3 communities: Graph Analysis, Clustering & Scoring, Graph Building
|
||||
- God nodes: `analyze.py`, `cluster.py`, `build.py`
|
||||
- `attention_notes.md` classified as `paper` (arXiv heuristic fires on `1706.03762`)
|
||||
- If you include the image: 1 extra node describing the figure content via vision
|
||||
|
||||
Full eval with scores and analysis: `review.md`
|
||||
@@ -0,0 +1,603 @@
|
||||
{
|
||||
"directed": false,
|
||||
"multigraph": false,
|
||||
"graph": {},
|
||||
"nodes": [
|
||||
{
|
||||
"label": "analyze.py",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L1",
|
||||
"id": "analyze",
|
||||
"community": 1
|
||||
},
|
||||
{
|
||||
"label": "_node_community_map()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L6",
|
||||
"id": "analyze_node_community_map",
|
||||
"community": 3
|
||||
},
|
||||
{
|
||||
"label": "_is_file_node()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L11",
|
||||
"id": "analyze_is_file_node",
|
||||
"community": 2
|
||||
},
|
||||
{
|
||||
"label": "god_nodes()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L35",
|
||||
"id": "analyze_god_nodes",
|
||||
"community": 2
|
||||
},
|
||||
{
|
||||
"label": "surprising_connections()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L57",
|
||||
"id": "analyze_surprising_connections",
|
||||
"community": 3
|
||||
},
|
||||
{
|
||||
"label": "_is_concept_node()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L89",
|
||||
"id": "analyze_is_concept_node",
|
||||
"community": 2
|
||||
},
|
||||
{
|
||||
"label": "_file_category()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L114",
|
||||
"id": "analyze_file_category",
|
||||
"community": 1
|
||||
},
|
||||
{
|
||||
"label": "_top_level_dir()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L125",
|
||||
"id": "analyze_top_level_dir",
|
||||
"community": 1
|
||||
},
|
||||
{
|
||||
"label": "_surprise_score()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L130",
|
||||
"id": "analyze_surprise_score",
|
||||
"community": 1
|
||||
},
|
||||
{
|
||||
"label": "_cross_file_surprises()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L181",
|
||||
"id": "analyze_cross_file_surprises",
|
||||
"community": 3
|
||||
},
|
||||
{
|
||||
"label": "_cross_community_surprises()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L239",
|
||||
"id": "analyze_cross_community_surprises",
|
||||
"community": 3
|
||||
},
|
||||
{
|
||||
"label": "suggest_questions()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L321",
|
||||
"id": "analyze_suggest_questions",
|
||||
"community": 2
|
||||
},
|
||||
{
|
||||
"label": "graph_diff()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L438",
|
||||
"id": "analyze_graph_diff",
|
||||
"community": 1
|
||||
},
|
||||
{
|
||||
"label": "build.py",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/build.py",
|
||||
"source_location": "L1",
|
||||
"id": "build",
|
||||
"community": 4
|
||||
},
|
||||
{
|
||||
"label": "build_from_json()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/build.py",
|
||||
"source_location": "L8",
|
||||
"id": "build_build_from_json",
|
||||
"community": 4
|
||||
},
|
||||
{
|
||||
"label": "build()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/build.py",
|
||||
"source_location": "L31",
|
||||
"id": "build_build",
|
||||
"community": 4
|
||||
},
|
||||
{
|
||||
"label": "cluster.py",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/cluster.py",
|
||||
"source_location": "L1",
|
||||
"id": "cluster",
|
||||
"community": 0
|
||||
},
|
||||
{
|
||||
"label": "build_graph()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/cluster.py",
|
||||
"source_location": "L6",
|
||||
"id": "cluster_build_graph",
|
||||
"community": 0
|
||||
},
|
||||
{
|
||||
"label": "cluster()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/cluster.py",
|
||||
"source_location": "L27",
|
||||
"id": "cluster_cluster",
|
||||
"community": 0
|
||||
},
|
||||
{
|
||||
"label": "_split_community()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/cluster.py",
|
||||
"source_location": "L72",
|
||||
"id": "cluster_split_community",
|
||||
"community": 0
|
||||
},
|
||||
{
|
||||
"label": "cohesion_score()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/cluster.py",
|
||||
"source_location": "L92",
|
||||
"id": "cluster_cohesion_score",
|
||||
"community": 0
|
||||
},
|
||||
{
|
||||
"label": "score_all()",
|
||||
"file_type": "code",
|
||||
"source_file": "worked/mixed-corpus/raw/cluster.py",
|
||||
"source_location": "L103",
|
||||
"id": "cluster_score_all",
|
||||
"community": 0
|
||||
}
|
||||
],
|
||||
"links": [
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L6",
|
||||
"weight": 1.0,
|
||||
"_src": "analyze",
|
||||
"_tgt": "analyze_node_community_map",
|
||||
"source": "analyze",
|
||||
"target": "analyze_node_community_map"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L11",
|
||||
"weight": 1.0,
|
||||
"_src": "analyze",
|
||||
"_tgt": "analyze_is_file_node",
|
||||
"source": "analyze",
|
||||
"target": "analyze_is_file_node"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L35",
|
||||
"weight": 1.0,
|
||||
"_src": "analyze",
|
||||
"_tgt": "analyze_god_nodes",
|
||||
"source": "analyze",
|
||||
"target": "analyze_god_nodes"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L57",
|
||||
"weight": 1.0,
|
||||
"_src": "analyze",
|
||||
"_tgt": "analyze_surprising_connections",
|
||||
"source": "analyze",
|
||||
"target": "analyze_surprising_connections"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L89",
|
||||
"weight": 1.0,
|
||||
"_src": "analyze",
|
||||
"_tgt": "analyze_is_concept_node",
|
||||
"source": "analyze",
|
||||
"target": "analyze_is_concept_node"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L114",
|
||||
"weight": 1.0,
|
||||
"_src": "analyze",
|
||||
"_tgt": "analyze_file_category",
|
||||
"source": "analyze",
|
||||
"target": "analyze_file_category"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L125",
|
||||
"weight": 1.0,
|
||||
"_src": "analyze",
|
||||
"_tgt": "analyze_top_level_dir",
|
||||
"source": "analyze",
|
||||
"target": "analyze_top_level_dir"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L130",
|
||||
"weight": 1.0,
|
||||
"_src": "analyze",
|
||||
"_tgt": "analyze_surprise_score",
|
||||
"source": "analyze",
|
||||
"target": "analyze_surprise_score"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L181",
|
||||
"weight": 1.0,
|
||||
"_src": "analyze",
|
||||
"_tgt": "analyze_cross_file_surprises",
|
||||
"source": "analyze",
|
||||
"target": "analyze_cross_file_surprises"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L239",
|
||||
"weight": 1.0,
|
||||
"_src": "analyze",
|
||||
"_tgt": "analyze_cross_community_surprises",
|
||||
"source": "analyze",
|
||||
"target": "analyze_cross_community_surprises"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L321",
|
||||
"weight": 1.0,
|
||||
"_src": "analyze",
|
||||
"_tgt": "analyze_suggest_questions",
|
||||
"source": "analyze",
|
||||
"target": "analyze_suggest_questions"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L438",
|
||||
"weight": 1.0,
|
||||
"_src": "analyze",
|
||||
"_tgt": "analyze_graph_diff",
|
||||
"source": "analyze",
|
||||
"target": "analyze_graph_diff"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L195",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_cross_file_surprises",
|
||||
"_tgt": "analyze_node_community_map",
|
||||
"source": "analyze_node_community_map",
|
||||
"target": "analyze_cross_file_surprises"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L274",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_cross_community_surprises",
|
||||
"_tgt": "analyze_node_community_map",
|
||||
"source": "analyze_node_community_map",
|
||||
"target": "analyze_cross_community_surprises"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L333",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_suggest_questions",
|
||||
"_tgt": "analyze_node_community_map",
|
||||
"source": "analyze_node_community_map",
|
||||
"target": "analyze_suggest_questions"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L45",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_god_nodes",
|
||||
"_tgt": "analyze_is_file_node",
|
||||
"source": "analyze_is_file_node",
|
||||
"target": "analyze_god_nodes"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L204",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_cross_file_surprises",
|
||||
"_tgt": "analyze_is_file_node",
|
||||
"source": "analyze_is_file_node",
|
||||
"target": "analyze_cross_file_surprises"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L283",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_cross_community_surprises",
|
||||
"_tgt": "analyze_is_file_node",
|
||||
"source": "analyze_is_file_node",
|
||||
"target": "analyze_cross_community_surprises"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L353",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_suggest_questions",
|
||||
"_tgt": "analyze_is_file_node",
|
||||
"source": "analyze_is_file_node",
|
||||
"target": "analyze_suggest_questions"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L45",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_god_nodes",
|
||||
"_tgt": "analyze_is_concept_node",
|
||||
"source": "analyze_god_nodes",
|
||||
"target": "analyze_is_concept_node"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L84",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_surprising_connections",
|
||||
"_tgt": "analyze_cross_file_surprises",
|
||||
"source": "analyze_surprising_connections",
|
||||
"target": "analyze_cross_file_surprises"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L86",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_surprising_connections",
|
||||
"_tgt": "analyze_cross_community_surprises",
|
||||
"source": "analyze_surprising_connections",
|
||||
"target": "analyze_cross_community_surprises"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L202",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_cross_file_surprises",
|
||||
"_tgt": "analyze_is_concept_node",
|
||||
"source": "analyze_is_concept_node",
|
||||
"target": "analyze_cross_file_surprises"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L353",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_suggest_questions",
|
||||
"_tgt": "analyze_is_concept_node",
|
||||
"source": "analyze_is_concept_node",
|
||||
"target": "analyze_suggest_questions"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L151",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_surprise_score",
|
||||
"_tgt": "analyze_file_category",
|
||||
"source": "analyze_file_category",
|
||||
"target": "analyze_surprise_score"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L158",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_surprise_score",
|
||||
"_tgt": "analyze_top_level_dir",
|
||||
"source": "analyze_top_level_dir",
|
||||
"target": "analyze_surprise_score"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L213",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_cross_file_surprises",
|
||||
"_tgt": "analyze_surprise_score",
|
||||
"source": "analyze_surprise_score",
|
||||
"target": "analyze_cross_file_surprises"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/analyze.py",
|
||||
"source_location": "L236",
|
||||
"weight": 0.8,
|
||||
"_src": "analyze_cross_file_surprises",
|
||||
"_tgt": "analyze_cross_community_surprises",
|
||||
"source": "analyze_cross_file_surprises",
|
||||
"target": "analyze_cross_community_surprises"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/build.py",
|
||||
"source_location": "L8",
|
||||
"weight": 1.0,
|
||||
"_src": "build",
|
||||
"_tgt": "build_build_from_json",
|
||||
"source": "build",
|
||||
"target": "build_build_from_json"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/build.py",
|
||||
"source_location": "L31",
|
||||
"weight": 1.0,
|
||||
"_src": "build",
|
||||
"_tgt": "build_build",
|
||||
"source": "build",
|
||||
"target": "build_build"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/build.py",
|
||||
"source_location": "L39",
|
||||
"weight": 0.8,
|
||||
"_src": "build_build",
|
||||
"_tgt": "build_build_from_json",
|
||||
"source": "build_build_from_json",
|
||||
"target": "build_build"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/cluster.py",
|
||||
"source_location": "L6",
|
||||
"weight": 1.0,
|
||||
"_src": "cluster",
|
||||
"_tgt": "cluster_build_graph",
|
||||
"source": "cluster",
|
||||
"target": "cluster_build_graph"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/cluster.py",
|
||||
"source_location": "L27",
|
||||
"weight": 1.0,
|
||||
"_src": "cluster",
|
||||
"_tgt": "cluster_cluster",
|
||||
"source": "cluster",
|
||||
"target": "cluster_cluster"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/cluster.py",
|
||||
"source_location": "L72",
|
||||
"weight": 1.0,
|
||||
"_src": "cluster",
|
||||
"_tgt": "cluster_split_community",
|
||||
"source": "cluster",
|
||||
"target": "cluster_split_community"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/cluster.py",
|
||||
"source_location": "L92",
|
||||
"weight": 1.0,
|
||||
"_src": "cluster",
|
||||
"_tgt": "cluster_cohesion_score",
|
||||
"source": "cluster",
|
||||
"target": "cluster_cohesion_score"
|
||||
},
|
||||
{
|
||||
"relation": "contains",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": "worked/mixed-corpus/raw/cluster.py",
|
||||
"source_location": "L103",
|
||||
"weight": 1.0,
|
||||
"_src": "cluster",
|
||||
"_tgt": "cluster_score_all",
|
||||
"source": "cluster",
|
||||
"target": "cluster_score_all"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/cluster.py",
|
||||
"source_location": "L63",
|
||||
"weight": 0.8,
|
||||
"_src": "cluster_cluster",
|
||||
"_tgt": "cluster_split_community",
|
||||
"source": "cluster_cluster",
|
||||
"target": "cluster_split_community"
|
||||
},
|
||||
{
|
||||
"relation": "calls",
|
||||
"confidence": "INFERRED",
|
||||
"source_file": "worked/mixed-corpus/raw/cluster.py",
|
||||
"source_location": "L104",
|
||||
"weight": 0.8,
|
||||
"_src": "cluster_score_all",
|
||||
"_tgt": "cluster_cohesion_score",
|
||||
"source": "cluster_cohesion_score",
|
||||
"target": "cluster_score_all"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,517 @@
|
||||
"""Graph analysis: god nodes (most connected), surprising connections (cross-community), suggested questions."""
|
||||
from __future__ import annotations
|
||||
import networkx as nx
|
||||
|
||||
|
||||
def _node_community_map(communities: dict[int, list[str]]) -> dict[str, int]:
|
||||
"""Invert communities dict: node_id -> community_id."""
|
||||
return {n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
|
||||
|
||||
def _is_file_node(G: nx.Graph, node_id: str) -> bool:
|
||||
"""
|
||||
Return True if this node is a file-level hub node (e.g. 'client', 'models')
|
||||
or an AST method stub (e.g. '.auth_flow()', '.__init__()').
|
||||
|
||||
These are synthetic nodes created by the AST extractor and should be excluded
|
||||
from god nodes, surprising connections, and knowledge gap reporting.
|
||||
"""
|
||||
label = G.nodes[node_id].get("label", "")
|
||||
if not label:
|
||||
return False
|
||||
# File-level hub: label is a filename with a code extension
|
||||
if label.split(".")[-1] in ("py", "ts", "js", "go", "rs", "java", "rb", "cpp", "c", "h"):
|
||||
return True
|
||||
# Method stub: AST extractor labels methods as '.method_name()'
|
||||
if label.startswith(".") and label.endswith("()"):
|
||||
return True
|
||||
# Module-level function stub: labeled 'function_name()' - only has a contains edge
|
||||
# These are real functions but structurally isolated by definition; not a gap worth flagging
|
||||
if label.endswith("()") and G.degree(node_id) <= 1:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def god_nodes(G: nx.Graph, top_n: int = 10) -> list[dict]:
|
||||
"""Return the top_n most-connected real entities - the core abstractions.
|
||||
|
||||
File-level hub nodes are excluded: they accumulate import/contains edges
|
||||
mechanically and don't represent meaningful architectural abstractions.
|
||||
"""
|
||||
degree = dict(G.degree())
|
||||
sorted_nodes = sorted(degree.items(), key=lambda x: x[1], reverse=True)
|
||||
result = []
|
||||
for node_id, deg in sorted_nodes:
|
||||
if _is_file_node(G, node_id) or _is_concept_node(G, node_id):
|
||||
continue
|
||||
result.append({
|
||||
"id": node_id,
|
||||
"label": G.nodes[node_id].get("label", node_id),
|
||||
"edges": deg,
|
||||
})
|
||||
if len(result) >= top_n:
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def surprising_connections(
|
||||
G: nx.Graph,
|
||||
communities: dict[int, list[str]] | None = None,
|
||||
top_n: int = 5,
|
||||
) -> list[dict]:
|
||||
"""
|
||||
Find connections that are genuinely surprising - not obvious from file structure.
|
||||
|
||||
Strategy:
|
||||
- Multi-file corpora: cross-file edges between real entities (not concept nodes).
|
||||
Sorted AMBIGUOUS → INFERRED → EXTRACTED.
|
||||
- Single-file / single-source corpora: cross-community edges that bridge
|
||||
distant parts of the graph (betweenness centrality on edges).
|
||||
These reveal non-obvious structural couplings.
|
||||
|
||||
Concept nodes (empty source_file, or injected semantic annotations) are excluded
|
||||
from surprising connections because they are intentional, not discovered.
|
||||
"""
|
||||
# Identify unique source files (ignore empty/null source_file)
|
||||
source_files = {
|
||||
data.get("source_file", "")
|
||||
for _, data in G.nodes(data=True)
|
||||
if data.get("source_file", "")
|
||||
}
|
||||
is_multi_source = len(source_files) > 1
|
||||
|
||||
if is_multi_source:
|
||||
return _cross_file_surprises(G, communities or {}, top_n)
|
||||
else:
|
||||
return _cross_community_surprises(G, communities or {}, top_n)
|
||||
|
||||
|
||||
def _is_concept_node(G: nx.Graph, node_id: str) -> bool:
|
||||
"""
|
||||
Return True if this node is a manually-injected semantic concept node
|
||||
rather than a real entity found in source code.
|
||||
|
||||
Signals:
|
||||
- Empty source_file
|
||||
- source_file doesn't look like a real file path (no extension)
|
||||
"""
|
||||
data = G.nodes[node_id]
|
||||
source = data.get("source_file", "")
|
||||
if not source:
|
||||
return True
|
||||
# Has no file extension → probably a concept label, not a real file
|
||||
if "." not in source.split("/")[-1]:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
_CODE_EXTENSIONS = {"py", "ts", "tsx", "js", "go", "rs", "java", "rb", "cpp", "c", "h", "cs", "kt", "scala", "php"}
|
||||
_DOC_EXTENSIONS = {"md", "txt", "rst"}
|
||||
_PAPER_EXTENSIONS = {"pdf"}
|
||||
_IMAGE_EXTENSIONS = {"png", "jpg", "jpeg", "webp", "gif", "svg"}
|
||||
|
||||
|
||||
def _file_category(path: str) -> str:
|
||||
ext = path.rsplit(".", 1)[-1].lower() if "." in path else ""
|
||||
if ext in _CODE_EXTENSIONS:
|
||||
return "code"
|
||||
if ext in _PAPER_EXTENSIONS:
|
||||
return "paper"
|
||||
if ext in _IMAGE_EXTENSIONS:
|
||||
return "image"
|
||||
return "doc"
|
||||
|
||||
|
||||
def _top_level_dir(path: str) -> str:
|
||||
"""Return the first path component - used to detect cross-repo edges."""
|
||||
return path.split("/")[0] if "/" in path else path
|
||||
|
||||
|
||||
def _surprise_score(
|
||||
G: nx.Graph,
|
||||
u: str,
|
||||
v: str,
|
||||
data: dict,
|
||||
node_community: dict[str, int],
|
||||
u_source: str,
|
||||
v_source: str,
|
||||
) -> tuple[int, list[str]]:
|
||||
"""Score how surprising a cross-file edge is. Returns (score, reasons)."""
|
||||
score = 0
|
||||
reasons: list[str] = []
|
||||
|
||||
# 1. Confidence weight - uncertain connections are more noteworthy
|
||||
conf = data.get("confidence", "EXTRACTED")
|
||||
conf_bonus = {"AMBIGUOUS": 3, "INFERRED": 2, "EXTRACTED": 1}.get(conf, 1)
|
||||
score += conf_bonus
|
||||
if conf in ("AMBIGUOUS", "INFERRED"):
|
||||
reasons.append(f"{conf.lower()} connection - not explicitly stated in source")
|
||||
|
||||
# 2. Cross file-type bonus - code↔paper or code↔image is non-obvious
|
||||
cat_u = _file_category(u_source)
|
||||
cat_v = _file_category(v_source)
|
||||
if cat_u != cat_v:
|
||||
score += 2
|
||||
reasons.append(f"crosses file types ({cat_u} ↔ {cat_v})")
|
||||
|
||||
# 3. Cross-repo bonus - different top-level directory
|
||||
if _top_level_dir(u_source) != _top_level_dir(v_source):
|
||||
score += 2
|
||||
reasons.append("connects across different repos/directories")
|
||||
|
||||
# 4. Cross-community bonus - Leiden says these are structurally distant
|
||||
cid_u = node_community.get(u)
|
||||
cid_v = node_community.get(v)
|
||||
if cid_u is not None and cid_v is not None and cid_u != cid_v:
|
||||
score += 1
|
||||
reasons.append("bridges separate communities")
|
||||
|
||||
# 5. Peripheral→hub: a low-degree node connecting to a high-degree one
|
||||
deg_u = G.degree(u)
|
||||
deg_v = G.degree(v)
|
||||
if min(deg_u, deg_v) <= 2 and max(deg_u, deg_v) >= 5:
|
||||
score += 1
|
||||
peripheral = G.nodes[u].get("label", u) if deg_u <= 2 else G.nodes[v].get("label", v)
|
||||
hub = G.nodes[v].get("label", v) if deg_u <= 2 else G.nodes[u].get("label", u)
|
||||
reasons.append(f"peripheral node `{peripheral}` unexpectedly reaches hub `{hub}`")
|
||||
|
||||
return score, reasons
|
||||
|
||||
|
||||
def _cross_file_surprises(G: nx.Graph, communities: dict[int, list[str]], top_n: int) -> list[dict]:
|
||||
"""
|
||||
Cross-file edges between real code/doc entities, ranked by a composite
|
||||
surprise score rather than confidence alone.
|
||||
|
||||
Surprise score accounts for:
|
||||
- Confidence (AMBIGUOUS > INFERRED > EXTRACTED)
|
||||
- Cross file-type (code↔paper is more surprising than code↔code)
|
||||
- Cross-repo (different top-level directory)
|
||||
- Cross-community (Leiden says structurally distant)
|
||||
- Peripheral→hub (low-degree node reaching a god node)
|
||||
|
||||
Each result includes a 'why' field explaining what makes it non-obvious.
|
||||
"""
|
||||
node_community = _node_community_map(communities)
|
||||
candidates = []
|
||||
|
||||
for u, v, data in G.edges(data=True):
|
||||
relation = data.get("relation", "")
|
||||
if relation in ("imports", "imports_from", "contains", "method"):
|
||||
continue
|
||||
if _is_concept_node(G, u) or _is_concept_node(G, v):
|
||||
continue
|
||||
if _is_file_node(G, u) or _is_file_node(G, v):
|
||||
continue
|
||||
|
||||
u_source = G.nodes[u].get("source_file", "")
|
||||
v_source = G.nodes[v].get("source_file", "")
|
||||
|
||||
if not u_source or not v_source or u_source == v_source:
|
||||
continue
|
||||
|
||||
score, reasons = _surprise_score(G, u, v, data, node_community, u_source, v_source)
|
||||
src_id = data.get("_src", u)
|
||||
tgt_id = data.get("_tgt", v)
|
||||
candidates.append({
|
||||
"_score": score,
|
||||
"source": G.nodes[src_id].get("label", src_id),
|
||||
"target": G.nodes[tgt_id].get("label", tgt_id),
|
||||
"source_files": [
|
||||
G.nodes[src_id].get("source_file", ""),
|
||||
G.nodes[tgt_id].get("source_file", ""),
|
||||
],
|
||||
"confidence": data.get("confidence", "EXTRACTED"),
|
||||
"relation": relation,
|
||||
"why": "; ".join(reasons) if reasons else "cross-file semantic connection",
|
||||
})
|
||||
|
||||
candidates.sort(key=lambda x: x["_score"], reverse=True)
|
||||
for c in candidates:
|
||||
c.pop("_score")
|
||||
|
||||
if candidates:
|
||||
return candidates[:top_n]
|
||||
|
||||
return _cross_community_surprises(G, communities, top_n)
|
||||
|
||||
|
||||
def _cross_community_surprises(
|
||||
G: nx.Graph,
|
||||
communities: dict[int, list[str]],
|
||||
top_n: int,
|
||||
) -> list[dict]:
|
||||
"""
|
||||
For single-source corpora: find edges that bridge different communities.
|
||||
These are surprising because Leiden grouped everything else tightly -
|
||||
these edges cut across the natural structure.
|
||||
|
||||
Falls back to high-betweenness edges if no community info is provided.
|
||||
"""
|
||||
if not communities:
|
||||
# No community info - use edge betweenness centrality
|
||||
if G.number_of_edges() == 0:
|
||||
return []
|
||||
betweenness = nx.edge_betweenness_centrality(G)
|
||||
top_edges = sorted(betweenness.items(), key=lambda x: x[1], reverse=True)[:top_n]
|
||||
result = []
|
||||
for (u, v), score in top_edges:
|
||||
data = G.edges[u, v]
|
||||
result.append({
|
||||
"source": G.nodes[u].get("label", u),
|
||||
"target": G.nodes[v].get("label", v),
|
||||
"source_files": [
|
||||
G.nodes[u].get("source_file", ""),
|
||||
G.nodes[v].get("source_file", ""),
|
||||
],
|
||||
"confidence": data.get("confidence", "EXTRACTED"),
|
||||
"relation": data.get("relation", ""),
|
||||
"note": f"Bridges graph structure (betweenness={score:.3f})",
|
||||
})
|
||||
return result
|
||||
|
||||
# Build node → community map
|
||||
node_community = _node_community_map(communities)
|
||||
|
||||
surprises = []
|
||||
for u, v, data in G.edges(data=True):
|
||||
cid_u = node_community.get(u)
|
||||
cid_v = node_community.get(v)
|
||||
if cid_u is None or cid_v is None or cid_u == cid_v:
|
||||
continue
|
||||
# Skip file hub nodes and plain structural edges
|
||||
if _is_file_node(G, u) or _is_file_node(G, v):
|
||||
continue
|
||||
relation = data.get("relation", "")
|
||||
if relation in ("imports", "imports_from", "contains", "method"):
|
||||
continue
|
||||
# This edge crosses community boundaries - interesting
|
||||
confidence = data.get("confidence", "EXTRACTED")
|
||||
src_id = data.get("_src", u)
|
||||
tgt_id = data.get("_tgt", v)
|
||||
surprises.append({
|
||||
"source": G.nodes[src_id].get("label", src_id),
|
||||
"target": G.nodes[tgt_id].get("label", tgt_id),
|
||||
"source_files": [
|
||||
G.nodes[src_id].get("source_file", ""),
|
||||
G.nodes[tgt_id].get("source_file", ""),
|
||||
],
|
||||
"confidence": confidence,
|
||||
"relation": relation,
|
||||
"note": f"Bridges community {cid_u} → community {cid_v}",
|
||||
"_pair": tuple(sorted([cid_u, cid_v])),
|
||||
})
|
||||
|
||||
# Sort: AMBIGUOUS first, then INFERRED, then EXTRACTED
|
||||
order = {"AMBIGUOUS": 0, "INFERRED": 1, "EXTRACTED": 2}
|
||||
surprises.sort(key=lambda x: order.get(x["confidence"], 3))
|
||||
|
||||
# Deduplicate by community pair - one representative edge per (A→B) boundary.
|
||||
# Without this, a single high-betweenness god node dominates all results.
|
||||
seen_pairs: set[tuple] = set()
|
||||
deduped = []
|
||||
for s in surprises:
|
||||
pair = s.pop("_pair")
|
||||
if pair not in seen_pairs:
|
||||
seen_pairs.add(pair)
|
||||
deduped.append(s)
|
||||
return deduped[:top_n]
|
||||
|
||||
|
||||
def suggest_questions(
|
||||
G: nx.Graph,
|
||||
communities: dict[int, list[str]],
|
||||
community_labels: dict[int, str],
|
||||
top_n: int = 7,
|
||||
) -> list[dict]:
|
||||
"""
|
||||
Generate questions the graph is uniquely positioned to answer.
|
||||
Based on: AMBIGUOUS edges, bridge nodes, underexplored god nodes, isolated nodes.
|
||||
Each question has a 'type', 'question', and 'why' field.
|
||||
"""
|
||||
questions = []
|
||||
node_community = _node_community_map(communities)
|
||||
|
||||
# 1. AMBIGUOUS edges → unresolved relationship questions
|
||||
for u, v, data in G.edges(data=True):
|
||||
if data.get("confidence") == "AMBIGUOUS":
|
||||
ul = G.nodes[u].get("label", u)
|
||||
vl = G.nodes[v].get("label", v)
|
||||
relation = data.get("relation", "related to")
|
||||
questions.append({
|
||||
"type": "ambiguous_edge",
|
||||
"question": f"What is the exact relationship between `{ul}` and `{vl}`?",
|
||||
"why": f"Edge tagged AMBIGUOUS (relation: {relation}) - confidence is low.",
|
||||
})
|
||||
|
||||
# 2. Bridge nodes (high betweenness) → cross-cutting concern questions
|
||||
if G.number_of_edges() > 0:
|
||||
betweenness = nx.betweenness_centrality(G)
|
||||
# Top bridge nodes that are NOT file-level hubs
|
||||
bridges = sorted(
|
||||
[(n, s) for n, s in betweenness.items()
|
||||
if not _is_file_node(G, n) and not _is_concept_node(G, n) and s > 0],
|
||||
key=lambda x: x[1],
|
||||
reverse=True,
|
||||
)[:3]
|
||||
for node_id, score in bridges:
|
||||
label = G.nodes[node_id].get("label", node_id)
|
||||
cid = node_community.get(node_id)
|
||||
comm_label = community_labels.get(cid, f"Community {cid}") if cid is not None else "unknown"
|
||||
neighbors = list(G.neighbors(node_id))
|
||||
neighbor_comms = {node_community.get(n) for n in neighbors if node_community.get(n) != cid}
|
||||
if neighbor_comms:
|
||||
other_labels = [community_labels.get(c, f"Community {c}") for c in neighbor_comms]
|
||||
questions.append({
|
||||
"type": "bridge_node",
|
||||
"question": f"Why does `{label}` connect `{comm_label}` to {', '.join(f'`{l}`' for l in other_labels)}?",
|
||||
"why": f"High betweenness centrality ({score:.3f}) - this node is a cross-community bridge.",
|
||||
})
|
||||
|
||||
# 3. God nodes with many INFERRED edges → verification questions
|
||||
degree = dict(G.degree())
|
||||
top_nodes = sorted(
|
||||
[(n, d) for n, d in degree.items() if not _is_file_node(G, n)],
|
||||
key=lambda x: x[1],
|
||||
reverse=True,
|
||||
)[:5]
|
||||
for node_id, _ in top_nodes:
|
||||
inferred = [
|
||||
(u, v, d) for u, v, d in G.edges(node_id, data=True)
|
||||
if d.get("confidence") == "INFERRED"
|
||||
]
|
||||
if len(inferred) >= 2:
|
||||
label = G.nodes[node_id].get("label", node_id)
|
||||
# Use _src/_tgt to get the correct direction; fall back to v (the other node)
|
||||
others = []
|
||||
for u, v, d in inferred[:2]:
|
||||
src_id = d.get("_src", u)
|
||||
tgt_id = d.get("_tgt", v)
|
||||
other_id = tgt_id if src_id == node_id else src_id
|
||||
others.append(G.nodes[other_id].get("label", other_id))
|
||||
questions.append({
|
||||
"type": "verify_inferred",
|
||||
"question": f"Are the {len(inferred)} inferred relationships involving `{label}` (e.g. with `{others[0]}` and `{others[1]}`) actually correct?",
|
||||
"why": f"`{label}` has {len(inferred)} INFERRED edges - model-reasoned connections that need verification.",
|
||||
})
|
||||
|
||||
# 4. Isolated or weakly-connected nodes → exploration questions
|
||||
isolated = [
|
||||
n for n in G.nodes()
|
||||
if G.degree(n) <= 1 and not _is_file_node(G, n) and not _is_concept_node(G, n)
|
||||
]
|
||||
if isolated:
|
||||
labels = [G.nodes[n].get("label", n) for n in isolated[:3]]
|
||||
questions.append({
|
||||
"type": "isolated_nodes",
|
||||
"question": f"What connects {', '.join(f'`{l}`' for l in labels)} to the rest of the system?",
|
||||
"why": f"{len(isolated)} weakly-connected nodes found - possible documentation gaps or missing edges.",
|
||||
})
|
||||
|
||||
# 5. Low-cohesion communities → structural questions
|
||||
from .cluster import cohesion_score
|
||||
for cid, nodes in communities.items():
|
||||
score = cohesion_score(G, nodes)
|
||||
if score < 0.15 and len(nodes) >= 5:
|
||||
label = community_labels.get(cid, f"Community {cid}")
|
||||
questions.append({
|
||||
"type": "low_cohesion",
|
||||
"question": f"Should `{label}` be split into smaller, more focused modules?",
|
||||
"why": f"Cohesion score {score} - nodes in this community are weakly interconnected.",
|
||||
})
|
||||
|
||||
if not questions:
|
||||
return [{
|
||||
"type": "no_signal",
|
||||
"question": None,
|
||||
"why": (
|
||||
"Not enough signal to generate questions. "
|
||||
"This usually means the corpus has no AMBIGUOUS edges, no bridge nodes, "
|
||||
"no INFERRED relationships, and all communities are tightly cohesive. "
|
||||
"Add more files or run with --mode deep to extract richer edges."
|
||||
),
|
||||
}]
|
||||
|
||||
return questions[:top_n]
|
||||
|
||||
|
||||
def graph_diff(G_old: nx.Graph, G_new: nx.Graph) -> dict:
|
||||
"""Compare two graph snapshots and return what changed.
|
||||
|
||||
Returns:
|
||||
{
|
||||
"new_nodes": [{"id": ..., "label": ...}],
|
||||
"removed_nodes": [{"id": ..., "label": ...}],
|
||||
"new_edges": [{"source": ..., "target": ..., "relation": ..., "confidence": ...}],
|
||||
"removed_edges": [...],
|
||||
"summary": "3 new nodes, 5 new edges, 1 node removed"
|
||||
}
|
||||
"""
|
||||
old_nodes = set(G_old.nodes())
|
||||
new_nodes = set(G_new.nodes())
|
||||
|
||||
added_node_ids = new_nodes - old_nodes
|
||||
removed_node_ids = old_nodes - new_nodes
|
||||
|
||||
new_nodes_list = [
|
||||
{"id": n, "label": G_new.nodes[n].get("label", n)}
|
||||
for n in added_node_ids
|
||||
]
|
||||
removed_nodes_list = [
|
||||
{"id": n, "label": G_old.nodes[n].get("label", n)}
|
||||
for n in removed_node_ids
|
||||
]
|
||||
|
||||
def edge_key(G: nx.Graph, u: str, v: str, data: dict) -> tuple:
|
||||
return (u, v, data.get("relation", ""))
|
||||
|
||||
old_edge_keys = {
|
||||
edge_key(G_old, u, v, d)
|
||||
for u, v, d in G_old.edges(data=True)
|
||||
}
|
||||
new_edge_keys = {
|
||||
edge_key(G_new, u, v, d)
|
||||
for u, v, d in G_new.edges(data=True)
|
||||
}
|
||||
|
||||
added_edge_keys = new_edge_keys - old_edge_keys
|
||||
removed_edge_keys = old_edge_keys - new_edge_keys
|
||||
|
||||
new_edges_list = []
|
||||
for u, v, d in G_new.edges(data=True):
|
||||
if edge_key(G_new, u, v, d) in added_edge_keys:
|
||||
new_edges_list.append({
|
||||
"source": u,
|
||||
"target": v,
|
||||
"relation": d.get("relation", ""),
|
||||
"confidence": d.get("confidence", ""),
|
||||
})
|
||||
|
||||
removed_edges_list = []
|
||||
for u, v, d in G_old.edges(data=True):
|
||||
if edge_key(G_old, u, v, d) in removed_edge_keys:
|
||||
removed_edges_list.append({
|
||||
"source": u,
|
||||
"target": v,
|
||||
"relation": d.get("relation", ""),
|
||||
"confidence": d.get("confidence", ""),
|
||||
})
|
||||
|
||||
parts = []
|
||||
if new_nodes_list:
|
||||
parts.append(f"{len(new_nodes_list)} new node{'s' if len(new_nodes_list) != 1 else ''}")
|
||||
if new_edges_list:
|
||||
parts.append(f"{len(new_edges_list)} new edge{'s' if len(new_edges_list) != 1 else ''}")
|
||||
if removed_nodes_list:
|
||||
parts.append(f"{len(removed_nodes_list)} node{'s' if len(removed_nodes_list) != 1 else ''} removed")
|
||||
if removed_edges_list:
|
||||
parts.append(f"{len(removed_edges_list)} edge{'s' if len(removed_edges_list) != 1 else ''} removed")
|
||||
summary = ", ".join(parts) if parts else "no changes"
|
||||
|
||||
return {
|
||||
"new_nodes": new_nodes_list,
|
||||
"removed_nodes": removed_nodes_list,
|
||||
"new_edges": new_edges_list,
|
||||
"removed_edges": removed_edges_list,
|
||||
"summary": summary,
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
# Attention Mechanism Notes
|
||||
|
||||
Notes on the Transformer architecture from Vaswani et al., 2017.
|
||||
arXiv: 1706.03762
|
||||
|
||||
## Abstract
|
||||
|
||||
The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism. The Transformer is a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output.
|
||||
|
||||
## Multi-Head Attention
|
||||
|
||||
The model uses h=8 parallel attention heads. For each head, d_k = d_v = d_model/h = 64.
|
||||
|
||||
Scaled dot-product attention:
|
||||
|
||||
Attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) V
|
||||
|
||||
Multi-head attention runs h attention functions in parallel, then concatenates and projects:
|
||||
|
||||
MultiHead(Q, K, V) = Concat(head_1, ..., head_h) W^O
|
||||
head_i = Attention(Q W_i^Q, K W_i^K, V W_i^V)
|
||||
|
||||
The scaling by sqrt(d_k) prevents the dot products from growing large in magnitude, which would push the softmax into regions with very small gradients.
|
||||
|
||||
## Architecture
|
||||
|
||||
The Transformer uses a stacked encoder-decoder structure.
|
||||
|
||||
Encoder: 6 identical layers, each with two sublayers:
|
||||
1. Multi-head self-attention
|
||||
2. Position-wise fully connected feed-forward network
|
||||
|
||||
Each sublayer uses a residual connection followed by layer normalization:
|
||||
output = LayerNorm(x + Sublayer(x))
|
||||
|
||||
Decoder: 6 identical layers, each with three sublayers:
|
||||
1. Masked multi-head self-attention (prevents positions from attending to subsequent positions)
|
||||
2. Multi-head attention over encoder output
|
||||
3. Position-wise feed-forward network
|
||||
|
||||
d_model = 512 for all sublayers and embedding layers.
|
||||
Feed-forward inner dimension = 2048.
|
||||
|
||||
## Positional Encoding
|
||||
|
||||
Since the model contains no recurrence and no convolution, positional encodings are added to the input embeddings to give the model information about the relative position of tokens:
|
||||
|
||||
PE(pos, 2i) = sin(pos / 10000^(2i/d_model))
|
||||
PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))
|
||||
|
||||
This allows the model to easily learn to attend by relative positions.
|
||||
|
||||
## Why attention over recurrence
|
||||
|
||||
Three main advantages:
|
||||
1. Total computational complexity per layer is lower for self-attention when sequence length is smaller than representation dimensionality
|
||||
2. Computations that can be parallelized — recurrent layers require O(n) sequential operations
|
||||
3. Path length between long-range dependencies is O(1) for self-attention vs O(n) for recurrence
|
||||
|
||||
## Results
|
||||
|
||||
WMT 2014 English-to-German: 28.4 BLEU, outperforming all previously published results by over 2 BLEU.
|
||||
WMT 2014 English-to-French: 41.0 BLEU, new state of the art.
|
||||
Training cost: 3.5 days on 8 P100 GPUs.
|
||||
|
||||
## Open questions
|
||||
|
||||
[1] Does the choice of h=8 heads generalize, or is it architecture-specific?
|
||||
[2] The scaling factor sqrt(d_k) is justified empirically — is there a theoretical justification?
|
||||
[3] How does learned positional encoding compare to sinusoidal at longer sequence lengths?
|
||||
|
||||
## References
|
||||
|
||||
[1] Vaswani, A., Shazeer, N., Parmar, N., et al. (2017). Attention Is All You Need. arXiv:1706.03762
|
||||
[2] Ba, J., Kiros, J., Hinton, G. (2016). Layer Normalization. arXiv:1607.06450
|
||||
[3] He, K., et al. (2016). Deep Residual Learning for Image Recognition. CVPR 2016.
|
||||
@@ -0,0 +1,39 @@
|
||||
# assemble node+edge dicts into a NetworkX graph, preserving edge direction
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
import networkx as nx
|
||||
from .validate import validate_extraction
|
||||
|
||||
|
||||
def build_from_json(extraction: dict) -> nx.Graph:
|
||||
errors = validate_extraction(extraction)
|
||||
# Dangling edges (stdlib/external imports) are expected - only warn about real schema errors.
|
||||
real_errors = [e for e in errors if "does not match any node id" not in e]
|
||||
if real_errors:
|
||||
print(f"[graphify] Extraction warning ({len(real_errors)} issues): {real_errors[0]}", file=sys.stderr)
|
||||
G = nx.Graph()
|
||||
for node in extraction.get("nodes", []):
|
||||
G.add_node(node["id"], **{k: v for k, v in node.items() if k != "id"})
|
||||
node_set = set(G.nodes())
|
||||
for edge in extraction.get("edges", []):
|
||||
src, tgt = edge["source"], edge["target"]
|
||||
if src not in node_set or tgt not in node_set:
|
||||
continue # skip edges to external/stdlib nodes - expected, not an error
|
||||
attrs = {k: v for k, v in edge.items() if k not in ("source", "target")}
|
||||
# Preserve original edge direction - undirected graphs lose it otherwise,
|
||||
# causing display functions to show edges backwards.
|
||||
attrs["_src"] = src
|
||||
attrs["_tgt"] = tgt
|
||||
G.add_edge(src, tgt, **attrs)
|
||||
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}
|
||||
for ext in extractions:
|
||||
combined["nodes"].extend(ext.get("nodes", []))
|
||||
combined["edges"].extend(ext.get("edges", []))
|
||||
combined["input_tokens"] += ext.get("input_tokens", 0)
|
||||
combined["output_tokens"] += ext.get("output_tokens", 0)
|
||||
return build_from_json(combined)
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Leiden community detection on NetworkX graphs. Splits oversized communities. Returns cohesion scores."""
|
||||
from __future__ import annotations
|
||||
import networkx as nx
|
||||
|
||||
|
||||
def build_graph(nodes: list[dict], edges: list[dict]) -> nx.Graph:
|
||||
"""Build a NetworkX graph from graphify node/edge dicts.
|
||||
|
||||
Preserves original edge direction as _src/_tgt attributes so that
|
||||
display functions can show relationships in the correct direction,
|
||||
even though the graph is undirected for structural analysis.
|
||||
"""
|
||||
G = nx.Graph()
|
||||
for n in nodes:
|
||||
G.add_node(n["id"], **{k: v for k, v in n.items() if k != "id"})
|
||||
for e in edges:
|
||||
attrs = {k: v for k, v in e.items() if k not in ("source", "target")}
|
||||
attrs["_src"] = e["source"]
|
||||
attrs["_tgt"] = e["target"]
|
||||
G.add_edge(e["source"], e["target"], **attrs)
|
||||
return G
|
||||
|
||||
_MAX_COMMUNITY_FRACTION = 0.25 # communities larger than 25% of graph get split
|
||||
_MIN_SPLIT_SIZE = 10 # only split if community has at least this many nodes
|
||||
|
||||
|
||||
def cluster(G: nx.Graph) -> dict[int, list[str]]:
|
||||
"""Run Leiden community detection. Returns {community_id: [node_ids]}.
|
||||
|
||||
Community IDs are stable across runs: 0 = largest community after splitting.
|
||||
Oversized communities (> 25% of graph nodes, min 10) are split by running
|
||||
a second Leiden pass on the subgraph.
|
||||
"""
|
||||
if G.number_of_nodes() == 0:
|
||||
return {}
|
||||
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]
|
||||
connected = G.subgraph(connected_nodes)
|
||||
|
||||
raw: dict[int, list[str]] = {}
|
||||
if connected.number_of_nodes() > 0:
|
||||
partition: dict[str, int] = leiden(connected)
|
||||
for node, cid in partition.items():
|
||||
raw.setdefault(cid, []).append(node)
|
||||
|
||||
# Each isolate becomes its own single-node community
|
||||
next_cid = max(raw.keys(), default=-1) + 1
|
||||
for node in isolates:
|
||||
raw[next_cid] = [node]
|
||||
next_cid += 1
|
||||
|
||||
# Split oversized communities
|
||||
max_size = max(_MIN_SPLIT_SIZE, int(G.number_of_nodes() * _MAX_COMMUNITY_FRACTION))
|
||||
final_communities: list[list[str]] = []
|
||||
for nodes in raw.values():
|
||||
if len(nodes) > max_size:
|
||||
final_communities.extend(_split_community(G, nodes))
|
||||
else:
|
||||
final_communities.append(nodes)
|
||||
|
||||
# Re-index by size descending for deterministic ordering
|
||||
final_communities.sort(key=len, reverse=True)
|
||||
return {i: sorted(nodes) for i, nodes in enumerate(final_communities)}
|
||||
|
||||
|
||||
def _split_community(G: nx.Graph, nodes: list[str]) -> list[list[str]]:
|
||||
"""Run a second Leiden pass on a community subgraph to split it further."""
|
||||
subgraph = G.subgraph(nodes)
|
||||
if subgraph.number_of_edges() == 0:
|
||||
# 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_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:
|
||||
return [sorted(nodes)]
|
||||
|
||||
|
||||
def cohesion_score(G: nx.Graph, community_nodes: list[str]) -> float:
|
||||
"""Ratio of actual intra-community edges to maximum possible."""
|
||||
n = len(community_nodes)
|
||||
if n <= 1:
|
||||
return 1.0
|
||||
subgraph = G.subgraph(community_nodes)
|
||||
actual = subgraph.number_of_edges()
|
||||
possible = n * (n - 1) / 2
|
||||
return round(actual / possible, 2) if possible > 0 else 0.0
|
||||
|
||||
|
||||
def score_all(G: nx.Graph, communities: dict[int, list[str]]) -> dict[int, float]:
|
||||
return {cid: cohesion_score(G, nodes) for cid, nodes in communities.items()}
|
||||
@@ -1,4 +1,4 @@
|
||||
# Graphify Evaluation — Mixed Corpus (2026-04-04)
|
||||
# Graphify Evaluation - Mixed Corpus (2026-04-04)
|
||||
|
||||
**Evaluator:** Claude Sonnet 4.6 (live execution)
|
||||
**Corpus:** 3 Python files + 1 markdown paper + 1 Arabic PNG image
|
||||
@@ -13,7 +13,7 @@ code: [analyze.py, build.py, cluster.py] 3 files
|
||||
paper: [attention_notes.md] 1 file (arxiv signals detected)
|
||||
image: [attention_arabic.png] 1 file
|
||||
total: 5 files · ~4,020 words
|
||||
warning: fits in a single context window (correct — corpus is small)
|
||||
warning: fits in a single context window (correct - corpus is small)
|
||||
```
|
||||
|
||||
**Finding:** `attention_notes.md` correctly classified as `paper` (not document) because it
|
||||
@@ -42,12 +42,12 @@ Total: 18 nodes, 19 edges → graph: 20 nodes, 19 edges (2 external deps
|
||||
| 1 | Clustering & Scoring | 0.29 | cluster.py, `cluster()`, `score_all()`, `cohesion_score()`, `build_graph()`, `_split_community()`, graspologic |
|
||||
| 2 | Graph Building | 0.50 | build.py, `build()`, `build_from_json()`, networkx |
|
||||
|
||||
**Finding:** Communities are semantically correct — the three graphify modules map cleanly
|
||||
**Finding:** Communities are semantically correct - the three graphify modules map cleanly
|
||||
to their functional roles. `build.py` has the highest cohesion (0.50) because it's a tight,
|
||||
self-contained module. `analyze.py` is lowest (0.22) because its functions don't call each
|
||||
other — each is a standalone analysis pass, making the subgraph sparse.
|
||||
other - each is a standalone analysis pass, making the subgraph sparse.
|
||||
|
||||
**Finding:** Zero surprising connections — the three modules are structurally independent
|
||||
**Finding:** Zero surprising connections - the three modules are structurally independent
|
||||
(no cross-file imports between them). Expected for a cleanly layered codebase.
|
||||
|
||||
---
|
||||
@@ -55,10 +55,10 @@ other — each is a standalone analysis pass, making the subgraph sparse.
|
||||
## 4. Query Tests (live BFS traversal)
|
||||
|
||||
All three queries ran against the real graph.json, returned relevant subgraphs, and were
|
||||
saved to `.graphify/memory/`.
|
||||
saved to `graphify-out/memory/`.
|
||||
|
||||
### Q1: "what does cluster do and how does it connect to build?"
|
||||
- BFS from `cluster()` reached 20 nodes (full graph — small corpus)
|
||||
- BFS from `cluster()` reached 20 nodes (full graph - small corpus)
|
||||
- `cluster.py` and `build.py` are linked via the `graspologic_partition` external dep node
|
||||
- Saved: `query_..._what_does_cluster_do_and_how_does_it_connect_to_bu.md`
|
||||
|
||||
@@ -83,19 +83,19 @@ Memory files created: 3
|
||||
query_..._how_does_score_all...md 1,763 bytes
|
||||
query_..._what_does_cluster...md 1,838 bytes
|
||||
|
||||
detect() on eval root with .graphify/memory/ present:
|
||||
detect() on eval root with graphify-out/memory/ present:
|
||||
Memory files found by next scan: 3 / 3 ✓
|
||||
```
|
||||
|
||||
**Result: PASS.** All 3 query results appear in the next `detect()` scan. On the next
|
||||
`--update`, these files will be extracted as nodes in the graph — closing the feedback loop.
|
||||
`--update`, these files will be extracted as nodes in the graph - closing the feedback loop.
|
||||
The graph grows from what you ask, not just what you add.
|
||||
|
||||
---
|
||||
|
||||
## 6. Arabic Image OCR (via Claude vision)
|
||||
|
||||
**Image:** `attention_arabic.png` — Arabic notes on the Transformer paper
|
||||
**Image:** `attention_arabic.png` - Arabic notes on the Transformer paper
|
||||
|
||||
**What graphify extracts (Claude vision reads directly, no reshaper/bidi needed):**
|
||||
|
||||
@@ -108,17 +108,17 @@ The graph grows from what you ask, not just what you add.
|
||||
| المحول: مكدس من 6 طبقات ترميز و6 طبقات فك ترميز | Transformer: 6 encoder + 6 decoder layers |
|
||||
| الترميز الموضعي | Positional encoding |
|
||||
| التطبيع الطبقي | Layer normalization |
|
||||
| المصدر: Vaswani et al., 2017 — arXiv: 1706.03762 | Source citation |
|
||||
| المصدر: Vaswani et al., 2017 - arXiv: 1706.03762 | Source citation |
|
||||
|
||||
**Nodes graphify would extract:**
|
||||
- `MultiHeadAttention` (آلية الانتباه) — hyperparameters: h=8, d_model=512, d_k=64
|
||||
- `PositionalEncoding` (الترميز الموضعي) — feeds into transformer input
|
||||
- `LayerNorm` (التطبيع الطبقي) — applied per sublayer
|
||||
- `Transformer` — 6 encoder + 6 decoder stack
|
||||
- `MultiHeadAttention` (آلية الانتباه) - hyperparameters: h=8, d_model=512, d_k=64
|
||||
- `PositionalEncoding` (الترميز الموضعي) - feeds into transformer input
|
||||
- `LayerNorm` (التطبيع الطبقي) - applied per sublayer
|
||||
- `Transformer` - 6 encoder + 6 decoder stack
|
||||
|
||||
**Key finding:** Arabic text OCR works natively via Claude vision. No preprocessing, no
|
||||
reshaper libraries, no bidi algorithms. The model reads Arabic, Persian, Hebrew, Chinese etc.
|
||||
identically to English. The image node in graphify is just a path — the vision subagent does
|
||||
identically to English. The image node in graphify is just a path - the vision subagent does
|
||||
the rest.
|
||||
|
||||
---
|
||||
@@ -129,7 +129,7 @@ the rest.
|
||||
`suggest_questions()` requires a `community_labels` dict. When called with auto-generated
|
||||
labels on a small corpus with no AMBIGUOUS edges and no isolated nodes, it returns an empty
|
||||
list. The function requires more signal (AMBIGUOUS edges, bridge nodes, underexplored god nodes)
|
||||
to generate questions — correct behavior, but the skill should handle the empty case gracefully.
|
||||
to generate questions - correct behavior, but the skill should handle the empty case gracefully.
|
||||
|
||||
### Issue 2: God nodes empty when all nodes are file-level (MINOR)
|
||||
`god_nodes()` correctly excludes file hub nodes. But on a 3-file corpus where the only
|
||||
@@ -138,7 +138,7 @@ degree-ranked nodes manually. Fix: emit a notice ("corpus too small for meaningf
|
||||
rather than silent empty list.
|
||||
|
||||
### Issue 3: 0 surprising connections on cleanly-layered code (NOT a bug)
|
||||
The three modules don't import from each other — they're connected only through external deps
|
||||
The three modules don't import from each other - they're connected only through external deps
|
||||
(networkx, graspologic). No cross-community edges means no surprises to surface. This is
|
||||
correct. Surprising connections require a less-cleanly-separated codebase.
|
||||
|
||||
@@ -155,7 +155,7 @@ correct. Surprising connections require a less-cleanly-separated codebase.
|
||||
| Feedback loop | 10/10 | query results appear in next detect() scan, 3/3 |
|
||||
| Arabic OCR | 10/10 | Claude vision reads RTL Arabic natively, no libraries needed |
|
||||
|
||||
**Overall: 9.0/10** — strong pass on all dimensions with a small corpus.
|
||||
**Overall: 9.0/10** - strong pass on all dimensions with a small corpus.
|
||||
Primary gaps are edge-level semantics (no INFERRED edges from AST-only) and god_nodes/
|
||||
suggest_questions behavior on tiny corpora.
|
||||
|
||||
@@ -169,8 +169,8 @@ The core pipeline is solid. The three most important findings:
|
||||
the next `detect()` scan and will be extracted into the graph on `--update`.
|
||||
|
||||
2. **Arabic OCR requires zero special handling.** PIL creates the image, Claude reads it.
|
||||
The same applies to any language — no language-specific preprocessing needed.
|
||||
The same applies to any language - no language-specific preprocessing needed.
|
||||
|
||||
3. **The corpus-size warning is working correctly.** At 4,020 words the warning fires:
|
||||
"fits in a single context window — you may not need a graph." This is honest.
|
||||
"fits in a single context window - you may not need a graph." This is honest.
|
||||
The graph adds value at scale, not on 5-file repos.
|
||||
Reference in new issue
Block a user