Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
762b85d7ca | ||
|
|
267c392a96 | ||
|
|
832dc537b3 | ||
|
|
6c82f81d13 | ||
|
|
6c9b5ef63c | ||
|
|
3145ca2e52 | ||
|
|
fd0ebb5957 | ||
|
|
b9871d7019 | ||
|
|
ac72cd3aaa | ||
|
|
48c9f024fb | ||
|
|
e1636a0e88 | ||
|
|
8b41440ad1 | ||
|
|
e1947826fc | ||
|
|
441e3b6574 | ||
|
|
0999822364 | ||
|
|
47a994ad5b | ||
|
|
5aaa268650 | ||
|
|
18d697aac9 | ||
|
|
e97379e551 | ||
|
|
3755fdc885 | ||
|
|
4e871ad36c | ||
|
|
97099edc38 | ||
|
|
7683df1cd5 | ||
|
|
ffc5427351 | ||
|
|
4360f9644b | ||
|
|
f755aca58f | ||
|
|
28b17d37f1 | ||
|
|
326c03e132 | ||
|
|
44fc32e3e2 | ||
|
|
744827166e | ||
|
|
c750582db4 | ||
|
|
71d1b394e9 | ||
|
|
a4ad901284 | ||
|
|
f9c344b546 | ||
|
|
59cbad3937 | ||
|
|
5904081d7a | ||
|
|
5f4f557034 | ||
|
|
eceaaad61e | ||
|
|
dd86271312 | ||
|
|
7359cdace9 | ||
|
|
ee1df22b25 | ||
|
|
a566bfb566 | ||
|
|
4563b043f2 | ||
|
|
6175e0a8ea | ||
|
|
770d7f54c4 | ||
|
|
8bed332ff4 | ||
|
|
df9b7ec54f | ||
|
|
2faeed99a2 | ||
|
|
2c49da24f0 |
No files matched your search
@@ -2,16 +2,25 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["v1", "v2", "v3", "v4", "main"]
|
||||
branches: ["v1", "v2", "v3", "v4", "v5", "main"]
|
||||
pull_request:
|
||||
branches: ["v1", "v2", "v3", "v4", "main"]
|
||||
branches: ["v1", "v2", "v3", "v4", "v5", "main"]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: ["3.10", "3.12"]
|
||||
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -20,11 +29,12 @@ jobs:
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache: 'pip'
|
||||
cache-dependency-path: 'pyproject.toml'
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pip install -e ".[mcp,pdf,watch]"
|
||||
pip install pytest
|
||||
pip install -e ".[all,test]"
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
|
||||
@@ -2,6 +2,57 @@
|
||||
|
||||
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
|
||||
|
||||
## 0.5.7 (2026-04-30)
|
||||
|
||||
- Feat: YAML/YML files now indexed for semantic extraction — Kubernetes, Kustomize, Helm, and any YAML corpus now picked up automatically (#633)
|
||||
|
||||
## 0.5.6 (2026-04-30)
|
||||
|
||||
- Fix: `NameError: name '_os' is not defined` crash after `graphify update` — this was fixed in v5 branch but not released to PyPI (#618, #612)
|
||||
|
||||
## 0.5.5 (2026-04-29)
|
||||
|
||||
- Feat: Kimi K2.6 backend — `pip install 'graphifyy[kimi]'` + `MOONSHOT_API_KEY` routes semantic extraction through Kimi K2.6. 3-6x richer relation extraction at ~3x lower cost. Claude remains default; Kimi is opt-in.
|
||||
- Fix: phantom god nodes (#598) — member-call callees (`this.logger.log()` → `log`) no longer cross-file resolved. Go package-qualified calls (`pkg.Func()`) correctly preserved. Affects JS/TS, Go, Rust, Swift, Kotlin, Scala, PHP, C++, C#, Zig, Elixir.
|
||||
- Fix: `concept` file_type no longer triggers validation warnings (#601)
|
||||
- Fix: `graphify update` remembers scan root via `graphify-out/.graphify_root` — no path argument needed on subsequent runs
|
||||
- Fix: Kimi K2.6 temperature 400 error — temperature param is now skipped for Kimi backends (model enforces its own fixed value) (#610)
|
||||
- Fix: community labels deleted in Step 9 cleanup — `.graphify_labels.json` is now preserved so wiki/obsidian/HTML retain human-readable names after re-cluster (#608)
|
||||
- Fix: `NameError: name '_os' is not defined` in `graphify update` Kimi tip (#612)
|
||||
- Fix: `SyntaxWarning` in `__main__.py` for shell glob pattern with backslash escapes
|
||||
- Fix: Python upper bound removed — `requires-python = ">=3.10"` now supports Python 3.14+ (#607)
|
||||
|
||||
## 0.5.4 (2026-04-28)
|
||||
|
||||
- Fix: SSRF DNS rebinding — `safe_fetch` now patches `socket.getaddrinfo` for the full request duration (#591)
|
||||
- Fix: yt-dlp SSRF bypass — `download_audio` now calls `validate_url` before handing URL to yt-dlp (#592)
|
||||
|
||||
## 0.5.3 (2026-04-27)
|
||||
|
||||
- Fix: cache namespace — AST and semantic entries now live in `cache/ast/` and `cache/semantic/` subdirectories; flat entries read as migration fallback
|
||||
|
||||
## 0.5.2 (2026-04-26)
|
||||
|
||||
- Fix: PreToolUse hook now matches on `Bash` instead of `Glob|Grep` for Claude Code v2.1.117+
|
||||
|
||||
## 0.5.1 (2026-04-25)
|
||||
|
||||
- Fix: node ID collision for same-named files in different directories
|
||||
- Fix: `source_file` paths relativized before return so `graph.json` is portable
|
||||
- Fix: desync guard — `to_json()` returns bool; report only written on successful JSON write
|
||||
- Feat: TypeScript `@/` path aliases resolved via `tsconfig.json`
|
||||
- Feat: Show All / Hide All buttons in HTML community panel
|
||||
|
||||
## 0.5.0 (2026-04-24)
|
||||
|
||||
- Feat: `graphify clone <github-url>` — clone and graph any public repo
|
||||
- Feat: `graphify merge-graphs` — combine multiple `graph.json` outputs into one cross-repo graph
|
||||
- Feat: `CLAUDE_CONFIG_DIR` support in `graphify install`
|
||||
- Feat: shrink guard — `to_json()` refuses to overwrite with a smaller graph
|
||||
- Feat: `build_merge()` for safe incremental updates
|
||||
- Feat: duplicate node deduplication via `deduplicate_by_label()`
|
||||
- Fix: `graphify-out/` excluded from source scanning
|
||||
|
||||
## 0.4.23 (2026-04-18)
|
||||
|
||||
- Fix: stale skill version warning persists after running `graphify install` when multiple platforms were previously installed — `graphify install` now refreshes `.graphify_version` in all other known skill directories so the warning clears across the board (#178)
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://safishamsi.gumroad.com/l/qetvlo"><img src="https://img.shields.io/badge/Book-The%20Memory%20Layer-2ea44f?style=flat&logo=gitbook&logoColor=white" alt="The Memory Layer"/></a>
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
@@ -22,7 +23,7 @@
|
||||
|
||||
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, or Google Antigravity - it reads your files, builds a knowledge graph, and gives you back structure you didn't know was there. Understand a codebase faster. Find the "why" behind architectural decisions.
|
||||
|
||||
Fully multimodal. Drop in code, PDFs, markdown, screenshots, diagrams, whiteboard photos, images in other languages, or video and audio files - graphify extracts concepts and relationships from all of it and connects them into one graph. Videos are transcribed with Whisper using a domain-aware prompt derived from your corpus. 25 languages supported via tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
|
||||
Fully multimodal. Drop in code, PDFs, markdown, screenshots, diagrams, whiteboard photos, images in other languages, or video and audio files - graphify extracts concepts and relationships from all of it and connects them into one graph. Videos are transcribed with Whisper using a domain-aware prompt derived from your corpus. YAML/YML files (Kubernetes, Kustomize, Helm, config) are indexed for semantic extraction. 25 languages supported via tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
|
||||
|
||||
> 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.
|
||||
|
||||
@@ -96,7 +97,7 @@ pip install graphifyy && graphify install
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism. Codex supports PreToolUse hooks — `graphify codex install` installs one in `.codex/hooks.json` in addition to writing AGENTS.md.
|
||||
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism. Codex supports UserPromptSubmit hooks — `graphify codex install` installs one in `.codex/hooks.json` in addition to writing AGENTS.md.
|
||||
|
||||
Then open your AI coding assistant and type:
|
||||
|
||||
@@ -130,7 +131,7 @@ After building a graph, run this once in your project:
|
||||
|
||||
**Claude Code** does two things: writes a `CLAUDE.md` section telling Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs a **PreToolUse hook** (`settings.json`) that fires before every Glob and Grep call. If a knowledge graph exists, Claude sees: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ — so Claude navigates via the graph instead of grepping through every file.
|
||||
|
||||
**Codex** writes to `AGENTS.md` and also installs a **PreToolUse hook** in `.codex/hooks.json` that fires before every Bash tool call — same always-on mechanism as Claude Code.
|
||||
**Codex** writes to `AGENTS.md` and also installs a **UserPromptSubmit hook** in `.codex/hooks.json` that fires when the user submits a prompt. This reminds Codex about `GRAPH_REPORT.md` before it decides whether to search files.
|
||||
|
||||
**OpenCode** writes to `AGENTS.md` and also installs a **`tool.execute.before` plugin** (`.opencode/plugins/graphify.js` + `opencode.json` registration) that fires before bash tool calls and injects the graph reminder into tool output when the graph exists.
|
||||
|
||||
@@ -165,9 +166,15 @@ Think of it this way: the always-on hook gives your assistant a map. The `/graph
|
||||
**Recommended `.gitignore` additions:**
|
||||
```
|
||||
# keep graph outputs, skip heavy/local-only files
|
||||
graphify-out/cache/ # optional: commit for shared extraction speed, skip to keep repo small
|
||||
graphify-out/manifest.json # mtime-based, invalid after git clone — always gitignore this
|
||||
graphify-out/cost.json # local token tracking, not useful to share
|
||||
|
||||
# optional: commit for shared extraction speed, skip to keep repo small
|
||||
graphify-out/cache/
|
||||
|
||||
# mtime-based, invalid after git clone - always gitignore this
|
||||
graphify-out/manifest.json
|
||||
|
||||
# local token tracking, not useful to share
|
||||
graphify-out/cost.json
|
||||
```
|
||||
|
||||
**Shared setup:**
|
||||
@@ -292,7 +299,7 @@ graphify hook status
|
||||
# always-on assistant instructions - platform-specific
|
||||
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
|
||||
graphify claude uninstall
|
||||
graphify codex install # AGENTS.md + PreToolUse hook in .codex/hooks.json (Codex)
|
||||
graphify codex install # AGENTS.md + UserPromptSubmit hook in .codex/hooks.json (Codex)
|
||||
graphify opencode install # AGENTS.md + tool.execute.before plugin (OpenCode)
|
||||
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
|
||||
graphify cursor uninstall
|
||||
@@ -327,6 +334,14 @@ graphify explain "SwinTransformer" # plain-language explanation of a n
|
||||
graphify add https://arxiv.org/abs/1706.03762 # fetch paper, save to ./raw, update graph
|
||||
graphify add https://... --author "Name" --contributor "Name"
|
||||
|
||||
# clone any GitHub repo and run the full pipeline on it
|
||||
graphify clone https://github.com/karpathy/nanoGPT # clones to ~/.graphify/repos/karpathy/nanoGPT
|
||||
graphify clone https://github.com/org/repo --branch dev --out ./my-clone
|
||||
|
||||
# cross-repo graphs — merge two or more graph.json outputs into one
|
||||
graphify merge-graphs repo1/graphify-out/graph.json repo2/graphify-out/graph.json
|
||||
graphify merge-graphs g1.json g2.json g3.json --out cross-repo.json
|
||||
|
||||
# incremental update and maintenance
|
||||
graphify watch ./src # auto-rebuild on code changes
|
||||
graphify check-update ./src # check if semantic re-extraction is pending (cron-safe)
|
||||
@@ -339,7 +354,7 @@ Works with any mix of file types:
|
||||
| Type | Extensions | Extraction |
|
||||
|------|-----------|------------|
|
||||
| Code | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl .vue .svelte` | AST via tree-sitter + call-graph (cross-file for all languages) + Java extends/implements + docstring/comment rationale |
|
||||
| Docs | `.md .mdx .html .txt .rst` | Concepts + relationships + design rationale via Claude |
|
||||
| Docs | `.md .mdx .html .txt .rst .yaml .yml` | Concepts + relationships + design rationale via Claude |
|
||||
| Office | `.docx .xlsx` | Converted to markdown then extracted via Claude (requires `pip install graphifyy[office]`) |
|
||||
| Papers | `.pdf` | Citation mining + concept extraction |
|
||||
| Images | `.png .jpg .webp .gif` | Claude vision - screenshots, diagrams, any language |
|
||||
@@ -371,6 +386,8 @@ For better accuracy on technical content, use a larger model:
|
||||
|
||||
Audio never leaves your machine. All transcription runs locally.
|
||||
|
||||
> **Legal notice:** Only use `/graphify add <url>` to download content you have the rights to. graphify uses yt-dlp for audio extraction — the same terms of service and copyright rules apply.
|
||||
|
||||
## What you get
|
||||
|
||||
**God nodes** - highest-degree concepts (what everything connects through)
|
||||
@@ -409,6 +426,14 @@ Token reduction scales with corpus size. 6 files fits in a context window anyway
|
||||
|
||||
graphify sends file contents to your AI coding assistant's underlying model API for semantic extraction of docs, papers, and images — Anthropic (Claude Code), OpenAI (Codex), or whichever provider your platform uses. Code files are processed locally via tree-sitter AST — no file contents leave your machine for code. Video and audio files are transcribed locally with faster-whisper — audio never leaves your machine. No telemetry, usage tracking, or analytics of any kind. The only network calls are to your platform's model API during extraction, using your own API key.
|
||||
|
||||
## Optional integrations
|
||||
|
||||
Runbooks for setting up extra tooling alongside graphify. None of these are required.
|
||||
|
||||
| Integration | Doc |
|
||||
|---|---|
|
||||
| LocalColabFold (ColabFold + AlphaFold2) on macOS Apple Silicon | [`docs/colabfold-macos-install.md`](docs/colabfold-macos-install.md) |
|
||||
|
||||
## Tech stack
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantic extraction via Claude (Claude Code), GPT-4 (Codex), or whichever model your platform runs. Video transcription via faster-whisper + yt-dlp (optional, `pip install graphifyy[video]`). No Neo4j required, no server, runs entirely locally.
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
# Installing LocalColabFold on macOS Apple Silicon
|
||||
A reproducible runbook for installing
|
||||
[LocalColabFold](https://github.com/YoshitakaMo/localcolabfold)
|
||||
(ColabFold + AlphaFold2 weights) on Apple Silicon (arm64) Macs, so you can
|
||||
predict protein structures locally and feed the resulting PDBs / confidence
|
||||
scores into a graphify corpus.
|
||||
|
||||
This document is **optional** and unrelated to graphify's pipeline. It is
|
||||
included as a known-good recipe for users who want a CPU-capable local
|
||||
ColabFold install alongside graphify on the same machine.
|
||||
|
||||
## Why a separate runbook
|
||||
LocalColabFold's current top-level installer (`install_colabbatch_linux.sh`)
|
||||
hardcodes `Miniforge3-Linux-x86_64.sh` and later runs
|
||||
`pip install jax[cuda12]==0.5.3`. Both fail on Apple Silicon: there are no
|
||||
macOS CUDA wheels, and Apple GPUs are unreachable from JAX's CUDA backend.
|
||||
Upstream stopped shipping a current macOS installer after v1.5.5. The
|
||||
**v1.5.5 M1 installer** (bundled in the LocalColabFold repo at
|
||||
`v1.5.5_old_installers/install_colabbatch_M1mac.sh`) is the working Apple
|
||||
Silicon path — ColabFold 1.6.1, JAX 0.4.23 CPU build.
|
||||
|
||||
## Verified configuration
|
||||
- Hardware: Apple Silicon (arm64)
|
||||
- OS: macOS (Darwin)
|
||||
- ColabFold installed: 1.6.1 (commit `de5ab5f`)
|
||||
- JAX: 0.4.23 (CPU build)
|
||||
- 62-residue smoke test (1 model, 1 recycle, single-sequence MSA): ~60 s wall
|
||||
|
||||
## Prerequisites (Homebrew)
|
||||
The M1 installer fail-fasts on these. Install once before running:
|
||||
|
||||
```bash
|
||||
brew tap brewsci/bio # custom tap for hh-suite
|
||||
brew install brewsci/bio/hh-suite \
|
||||
kalign \
|
||||
mmseqs2
|
||||
|
||||
# verify
|
||||
for c in wget hhsearch kalign mmseqs; do
|
||||
printf "%-10s " "$c" && command -v "$c" || echo MISSING
|
||||
done
|
||||
```
|
||||
|
||||
Roughly ~600 MB of brew downloads (gcc, open-mpi, hh-suite are the heavy
|
||||
items); 5–10 minutes on a modern internet link.
|
||||
|
||||
## Install
|
||||
Clone LocalColabFold (or use an existing clone), then from the repo root:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/YoshitakaMo/localcolabfold.git
|
||||
cd localcolabfold
|
||||
bash v1.5.5_old_installers/install_colabbatch_M1mac.sh
|
||||
```
|
||||
|
||||
What the installer does, in order:
|
||||
1. Downloads `Miniforge3-MacOSX-arm64.sh` and installs into
|
||||
`localcolabfold/conda/`
|
||||
2. `conda update -n base conda -y`
|
||||
3. Creates env at `localcolabfold/colabfold-conda` with
|
||||
`python=3.10 openmm==8.0.0 pdbfixer==1.9` from conda-forge
|
||||
4. `pip install "colabfold[alphafold] @ git+https://github.com/sokrypton/ColabFold"`
|
||||
5. `pip install jax==0.4.23 jaxlib==0.4.23` (CPU build)
|
||||
6. `pip install silence_tensorflow`
|
||||
7. Downloads `update_M1mac.sh`
|
||||
8. `python -m colabfold.download` — pulls AlphaFold2 weights into
|
||||
`~/Library/Caches/colabfold` (~5.3 GB total: 3.82 GB multimer_v3 +
|
||||
3.47 GB AlphaFold2-ptm)
|
||||
|
||||
Total install time: ~10–30 min depending on network and AlphaFold weight
|
||||
download speed.
|
||||
|
||||
## Add to PATH
|
||||
The installer's last step prints the line for your shell. Adapt the prefix
|
||||
to wherever you cloned LocalColabFold:
|
||||
|
||||
```bash
|
||||
export PATH="$(pwd)/localcolabfold/colabfold-conda/bin:$PATH"
|
||||
```
|
||||
|
||||
Add the line to `~/.zshrc` to persist across shell sessions.
|
||||
|
||||
## Smoke test
|
||||
A minimal CPU-only inference exercising the JAX path (no MMseqs2 server,
|
||||
no templates, single model, single recycle). Use any short FASTA — the
|
||||
LocalColabFold repo ships `1BJP_1.fasta` (62 residues).
|
||||
|
||||
```bash
|
||||
colabfold_batch \
|
||||
--num-models 1 --num-recycle 1 \
|
||||
--msa-mode single_sequence \
|
||||
--random-seed 0 \
|
||||
1BJP_1.fasta out_smoketest/
|
||||
```
|
||||
|
||||
Expected output in `out_smoketest/`:
|
||||
- `*.pdb` — predicted structure
|
||||
- `*_scores_*.json` — per-residue confidence
|
||||
- `*_pae.png`, `*_plddt.png`, `*_coverage.png` — diagnostic plots
|
||||
- `1BJP_1.done.txt` — sentinel marker
|
||||
|
||||
Sample log lines on success:
|
||||
```
|
||||
Running colabfold 1.6.1 (de5ab5f795ed95c70a7a9b6a9dc6bb5625016142)
|
||||
WARNING: no GPU detected, will be using CPU
|
||||
Query 1/1: 1BJP_1 (length 62)
|
||||
alphafold2_ptm_model_1_seed_000 recycle=0 pLDDT=56.7 pTM=0.363
|
||||
alphafold2_ptm_model_1_seed_000 took 18.1s (1 recycles)
|
||||
```
|
||||
|
||||
The low pLDDT (~57) is **expected** — single-sequence MSA, 1 model, and
|
||||
1 recycle is the cheapest config that still exercises the JAX inference
|
||||
path. It is **not** representative of structure quality. Use the
|
||||
production config below for real predictions.
|
||||
|
||||
## Production run (CPU-friendly defaults)
|
||||
LocalColabFold's bundled `run_colabfoldbatch_sample.sh` uses
|
||||
`--use-gpu-relax`, `--templates`, and `--amber` — all of which require
|
||||
either GPU or extra setup that doesn't apply on macOS. Use this
|
||||
CPU-friendly variant instead:
|
||||
|
||||
```bash
|
||||
colabfold_batch \
|
||||
--num-recycle 3 \
|
||||
--num-models 5 \
|
||||
--model-order 1,2,3,4,5 \
|
||||
--random-seed 0 \
|
||||
YOUR_INPUT.fasta out_dir/
|
||||
# Dropped from the sample script:
|
||||
# --use-gpu-relax (no GPU)
|
||||
# --amber (slow on CPU; pdbfixer-only is fine for many use cases)
|
||||
# --templates (requires hhsearch + a PDB templates DB)
|
||||
```
|
||||
|
||||
MSA defaults to MMseqs2 server-side queries — needs network, ~30–90 s
|
||||
roundtrip per sequence.
|
||||
|
||||
Expect 5–15 min per ~100-residue monomer on this hardware. Multimers and
|
||||
longer chains scale much worse on CPU.
|
||||
|
||||
## Honest caveats
|
||||
- **CPU-only.** No CUDA wheels for macOS exist; JAX has experimental
|
||||
Metal support but LocalColabFold's pinned `jax==0.4.23` is the CPU
|
||||
build. Inference can be 30–100× slower than a recent NVIDIA GPU.
|
||||
- **ColabFold version is 1.6.1**, pinned by the v1.5.5 installer track.
|
||||
Newer features in ColabFold `main` aren't available here. For latest
|
||||
features either use Google Colab or a Linux + NVIDIA box.
|
||||
- **Weights cache is ~5.3 GB** at `~/Library/Caches/colabfold`. Move with
|
||||
`XDG_CACHE_HOME` if disk is tight.
|
||||
- **Apple Silicon Metal** is not used by this JAX. There's no
|
||||
straightforward way to enable it without changing the pinned versions
|
||||
in the installer script.
|
||||
|
||||
## Update
|
||||
```bash
|
||||
bash localcolabfold/update_M1mac.sh
|
||||
```
|
||||
|
||||
## Uninstall / reset
|
||||
```bash
|
||||
# Remove the conda env + Miniforge (keeps weights cache)
|
||||
rm -rf localcolabfold/
|
||||
|
||||
# Optionally drop weights cache
|
||||
rm -rf ~/Library/Caches/colabfold
|
||||
|
||||
# Optionally remove brew prereqs
|
||||
brew uninstall brewsci/bio/hh-suite kalign mmseqs2
|
||||
brew untap brewsci/bio
|
||||
```
|
||||
+252
-29
@@ -1,6 +1,7 @@
|
||||
"""graphify CLI - `graphify install` sets up the Claude Code skill."""
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
@@ -37,14 +38,22 @@ def _refresh_all_version_stamps() -> None:
|
||||
vf.write_text(__version__, encoding="utf-8")
|
||||
|
||||
_SETTINGS_HOOK = {
|
||||
"matcher": "Glob|Grep",
|
||||
# Claude Code v2.1.117+ removed dedicated Grep/Glob tools; searches now go through Bash.
|
||||
# We match on Bash and inspect the command string to avoid firing on every shell call.
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": (
|
||||
"[ -f graphify-out/graph.json ] && "
|
||||
r"""echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}}' """
|
||||
"|| true"
|
||||
"CMD=$(python3 -c \""
|
||||
"import json,sys; d=json.load(sys.stdin); "
|
||||
"print(d.get('tool_input',d).get('command',''))\" 2>/dev/null || true); "
|
||||
"case \"$CMD\" in "
|
||||
r"*grep*|*rg\ *|*ripgrep*|*find\ *|*fd\ *|*ack\ *|*ag\ *) "
|
||||
" [ -f graphify-out/graph.json ] && "
|
||||
r""" echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}}' """
|
||||
" || true ;; "
|
||||
"esac"
|
||||
),
|
||||
}
|
||||
],
|
||||
@@ -148,7 +157,12 @@ def install(platform: str = "claude") -> None:
|
||||
print(f"error: {cfg['skill_file']} not found in package - reinstall graphify", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
skill_dst = Path.home() / cfg["skill_dst"]
|
||||
import os as _os
|
||||
if platform in ("claude", "windows") and _os.environ.get("CLAUDE_CONFIG_DIR"):
|
||||
_claude_base = Path(_os.environ["CLAUDE_CONFIG_DIR"])
|
||||
skill_dst = _claude_base / "skills" / "graphify" / "SKILL.md"
|
||||
else:
|
||||
skill_dst = Path.home() / cfg["skill_dst"]
|
||||
skill_dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy(skill_src, skill_dst)
|
||||
(skill_dst.parent / ".graphify_version").write_text(__version__, encoding="utf-8")
|
||||
@@ -698,15 +712,14 @@ def _uninstall_opencode_plugin(project_dir: Path) -> None:
|
||||
|
||||
_CODEX_HOOK = {
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
"UserPromptSubmit": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": (
|
||||
"[ -f graphify-out/graph.json ] && "
|
||||
r"""echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}}' """
|
||||
r"""echo '{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}}' """
|
||||
"|| true"
|
||||
),
|
||||
}
|
||||
@@ -717,40 +730,103 @@ _CODEX_HOOK = {
|
||||
}
|
||||
|
||||
|
||||
_LEGACY_CODEX_PRE_TOOL_HOOK = {
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": (
|
||||
"[ -f graphify-out/graph.json ] && "
|
||||
r"""echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}}' """
|
||||
"|| true"
|
||||
),
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _is_graphify_codex_hook(hook: object) -> bool:
|
||||
"""Return True for Codex hooks generated by graphify."""
|
||||
return hook in (
|
||||
_CODEX_HOOK["hooks"]["UserPromptSubmit"][0],
|
||||
_LEGACY_CODEX_PRE_TOOL_HOOK,
|
||||
)
|
||||
|
||||
|
||||
def _remove_graphify_codex_hooks(existing: dict) -> None:
|
||||
"""Remove graphify Codex hooks while preserving unrelated hooks."""
|
||||
hooks = existing.get("hooks")
|
||||
if not isinstance(hooks, dict):
|
||||
return
|
||||
|
||||
for event in ("UserPromptSubmit", "PreToolUse"):
|
||||
event_hooks = hooks.get(event)
|
||||
if not isinstance(event_hooks, list):
|
||||
continue
|
||||
filtered = [h for h in event_hooks if not _is_graphify_codex_hook(h)]
|
||||
if filtered:
|
||||
hooks[event] = filtered
|
||||
else:
|
||||
hooks.pop(event, None)
|
||||
|
||||
if not hooks:
|
||||
existing.pop("hooks", None)
|
||||
|
||||
|
||||
def _install_codex_hook(project_dir: Path) -> None:
|
||||
"""Add graphify PreToolUse hook to .codex/hooks.json."""
|
||||
"""Add graphify UserPromptSubmit hook to .codex/hooks.json."""
|
||||
hooks_path = project_dir / ".codex" / "hooks.json"
|
||||
hooks_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if hooks_path.exists():
|
||||
try:
|
||||
existing = json.loads(hooks_path.read_text(encoding="utf-8"))
|
||||
loaded = json.loads(hooks_path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
existing = {}
|
||||
print(" .codex/hooks.json -> invalid JSON; left unchanged")
|
||||
return
|
||||
if not isinstance(loaded, dict):
|
||||
print(" .codex/hooks.json -> top-level value is not an object; left unchanged")
|
||||
return
|
||||
existing = loaded
|
||||
else:
|
||||
existing = {}
|
||||
|
||||
pre_tool = existing.setdefault("hooks", {}).setdefault("PreToolUse", [])
|
||||
existing["hooks"]["PreToolUse"] = [h for h in pre_tool if "graphify" not in str(h)]
|
||||
existing["hooks"]["PreToolUse"].extend(_CODEX_HOOK["hooks"]["PreToolUse"])
|
||||
_remove_graphify_codex_hooks(existing)
|
||||
hooks = existing.get("hooks")
|
||||
if hooks is None:
|
||||
hooks = existing["hooks"] = {}
|
||||
elif not isinstance(hooks, dict):
|
||||
print(" .codex/hooks.json -> existing hooks value is not an object; left unchanged")
|
||||
return
|
||||
|
||||
user_prompt = hooks.get("UserPromptSubmit")
|
||||
if user_prompt is None:
|
||||
user_prompt = hooks["UserPromptSubmit"] = []
|
||||
elif not isinstance(user_prompt, list):
|
||||
print(" .codex/hooks.json -> UserPromptSubmit hooks are not a list; left unchanged")
|
||||
return
|
||||
|
||||
user_prompt.extend(_CODEX_HOOK["hooks"]["UserPromptSubmit"])
|
||||
hooks_path.write_text(json.dumps(existing, indent=2), encoding="utf-8")
|
||||
print(f" .codex/hooks.json -> PreToolUse hook registered")
|
||||
print(f" .codex/hooks.json -> UserPromptSubmit hook registered")
|
||||
|
||||
|
||||
def _uninstall_codex_hook(project_dir: Path) -> None:
|
||||
"""Remove graphify PreToolUse hook from .codex/hooks.json."""
|
||||
"""Remove graphify Codex hooks from .codex/hooks.json."""
|
||||
hooks_path = project_dir / ".codex" / "hooks.json"
|
||||
if not hooks_path.exists():
|
||||
return
|
||||
try:
|
||||
existing = json.loads(hooks_path.read_text(encoding="utf-8"))
|
||||
loaded = json.loads(hooks_path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
pre_tool = existing.get("hooks", {}).get("PreToolUse", [])
|
||||
filtered = [h for h in pre_tool if "graphify" not in str(h)]
|
||||
existing["hooks"]["PreToolUse"] = filtered
|
||||
hooks_path.write_text(json.dumps(existing, indent=2), encoding="utf-8")
|
||||
print(f" .codex/hooks.json -> PreToolUse hook removed")
|
||||
if not isinstance(loaded, dict):
|
||||
return
|
||||
before = json.dumps(loaded, sort_keys=True)
|
||||
_remove_graphify_codex_hooks(loaded)
|
||||
if json.dumps(loaded, sort_keys=True) != before:
|
||||
hooks_path.write_text(json.dumps(loaded, indent=2), encoding="utf-8")
|
||||
print(f" .codex/hooks.json -> graphify hooks removed")
|
||||
|
||||
|
||||
def _agents_install(project_dir: Path, platform: str) -> None:
|
||||
@@ -852,7 +928,7 @@ def _install_claude_hook(project_dir: Path) -> None:
|
||||
hooks = settings.setdefault("hooks", {})
|
||||
pre_tool = hooks.setdefault("PreToolUse", [])
|
||||
|
||||
hooks["PreToolUse"] = [h for h in pre_tool if not (h.get("matcher") == "Glob|Grep" and "graphify" in str(h))]
|
||||
hooks["PreToolUse"] = [h for h in pre_tool if not (h.get("matcher") in ("Glob|Grep", "Bash") and "graphify" in str(h))]
|
||||
hooks["PreToolUse"].append(_SETTINGS_HOOK)
|
||||
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
|
||||
print(f" .claude/settings.json -> PreToolUse hook registered")
|
||||
@@ -868,7 +944,7 @@ def _uninstall_claude_hook(project_dir: Path) -> None:
|
||||
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))]
|
||||
filtered = [h for h in pre_tool if not (h.get("matcher") in ("Glob|Grep", "Bash") and "graphify" in str(h))]
|
||||
if len(filtered) == len(pre_tool):
|
||||
return
|
||||
settings["hooks"]["PreToolUse"] = filtered
|
||||
@@ -906,6 +982,59 @@ def claude_uninstall(project_dir: Path | None = None) -> None:
|
||||
_uninstall_claude_hook(project_dir or Path("."))
|
||||
|
||||
|
||||
def _clone_repo(url: str, branch: str | None = None, out_dir: Path | None = None) -> Path:
|
||||
"""Clone a GitHub repo to a local cache dir and return the path.
|
||||
|
||||
Clones into ~/.graphify/repos/<owner>/<repo> by default so repeated
|
||||
runs on the same URL reuse the existing clone (git pull instead of clone).
|
||||
"""
|
||||
import subprocess as _sp
|
||||
import re as _re
|
||||
|
||||
# Normalise URL — strip trailing .git if present
|
||||
url = url.rstrip("/")
|
||||
if not url.endswith(".git"):
|
||||
git_url = url + ".git"
|
||||
else:
|
||||
git_url = url
|
||||
url = url[:-4]
|
||||
|
||||
# Extract owner/repo from URL
|
||||
m = _re.search(r"github\.com[:/]([^/]+)/([^/]+?)(?:\.git)?$", url)
|
||||
if not m:
|
||||
print(f"error: not a recognised GitHub URL: {url}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
owner, repo = m.group(1), m.group(2)
|
||||
|
||||
if out_dir:
|
||||
dest = out_dir
|
||||
else:
|
||||
dest = Path.home() / ".graphify" / "repos" / owner / repo
|
||||
|
||||
if dest.exists():
|
||||
print(f"Repo already cloned at {dest} — pulling latest...", flush=True)
|
||||
cmd = ["git", "-C", str(dest), "pull"]
|
||||
if branch:
|
||||
cmd += ["origin", branch]
|
||||
result = _sp.run(cmd, capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
print(f"warning: git pull failed:\n{result.stderr}", file=sys.stderr)
|
||||
else:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
print(f"Cloning {url} → {dest} ...", flush=True)
|
||||
cmd = ["git", "clone", "--depth", "1"]
|
||||
if branch:
|
||||
cmd += ["--branch", branch]
|
||||
cmd += [git_url, str(dest)]
|
||||
result = _sp.run(cmd, capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
print(f"error: git clone failed:\n{result.stderr}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Ready at: {dest}", flush=True)
|
||||
return dest
|
||||
|
||||
|
||||
def main() -> None:
|
||||
# Check all known skill install locations for a stale version stamp.
|
||||
# Skip during install/uninstall (hook writes trigger a fresh check anyway).
|
||||
@@ -923,6 +1052,11 @@ def main() -> None:
|
||||
print(" --graph <path> path to graph.json (default graphify-out/graph.json)")
|
||||
print(" explain \"X\" plain-language explanation of a node and its neighbors")
|
||||
print(" --graph <path> path to graph.json (default graphify-out/graph.json)")
|
||||
print(" clone <github-url> clone a GitHub repo locally and print its path for /graphify")
|
||||
print(" merge-graphs <g1> <g2> merge two or more graph.json files into one cross-repo graph")
|
||||
print(" --out <path> output path (default: graphify-out/merged-graph.json)")
|
||||
print(" --branch <branch> checkout a specific branch (default: repo default)")
|
||||
print(" --out <dir> clone to a custom directory (default: ~/.graphify/repos/<owner>/<repo>)")
|
||||
print(" add <url> fetch a URL and save it to ./raw, then update the graph")
|
||||
print(" --author \"Name\" tag the author of the content")
|
||||
print(" --contributor \"Name\" tag who added it to the corpus")
|
||||
@@ -930,6 +1064,7 @@ def main() -> None:
|
||||
print(" watch <path> watch a folder and rebuild the graph on code changes")
|
||||
print(" update <path> re-extract code files and update the graph (no LLM needed)")
|
||||
print(" cluster-only <path> rerun clustering on an existing graph.json and regenerate report")
|
||||
print(" --no-viz skip graph.html generation (useful for >5000 node graphs / CI)")
|
||||
print(" query \"<question>\" BFS traversal of graph.json for a question")
|
||||
print(" --dfs use depth-first instead of breadth-first")
|
||||
print(" --budget N cap output at N tokens (default 2000)")
|
||||
@@ -951,8 +1086,8 @@ def main() -> None:
|
||||
print(" cursor uninstall remove .cursor/rules/graphify.mdc")
|
||||
print(" claude install write graphify section to CLAUDE.md + PreToolUse hook (Claude Code)")
|
||||
print(" claude uninstall remove graphify section from CLAUDE.md + PreToolUse hook")
|
||||
print(" codex install write graphify section to AGENTS.md (Codex)")
|
||||
print(" codex uninstall remove graphify section from AGENTS.md")
|
||||
print(" codex install write AGENTS.md section + UserPromptSubmit hook (Codex)")
|
||||
print(" codex uninstall remove AGENTS.md section + graphify Codex hook")
|
||||
print(" opencode install write graphify section to AGENTS.md + tool.execute.before plugin (OpenCode)")
|
||||
print(" opencode uninstall remove graphify section from AGENTS.md + plugin")
|
||||
print(" aider install write graphify section to AGENTS.md (Aider)")
|
||||
@@ -1307,6 +1442,7 @@ def main() -> None:
|
||||
|
||||
elif cmd == "cluster-only":
|
||||
watch_path = Path(sys.argv[2]) if len(sys.argv) > 2 else Path(".")
|
||||
no_viz = "--no-viz" in sys.argv
|
||||
graph_json = watch_path / "graphify-out" / "graph.json"
|
||||
if not graph_json.exists():
|
||||
print(f"error: no graph found at {graph_json} — run /graphify first", file=sys.stderr)
|
||||
@@ -1335,11 +1471,36 @@ def main() -> None:
|
||||
out = watch_path / "graphify-out"
|
||||
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
|
||||
to_json(G, communities, str(out / "graph.json"))
|
||||
to_html(G, communities, str(out / "graph.html"), community_labels=labels or None)
|
||||
print(f"Done — {len(communities)} communities. GRAPH_REPORT.md, graph.json and graph.html updated.")
|
||||
|
||||
# Mirror watch.py pattern: gate to_html so core outputs (graph.json +
|
||||
# GRAPH_REPORT.md) always land. Honor --no-viz explicitly; otherwise
|
||||
# fall back to ValueError handling so an oversized graph doesn't crash
|
||||
# the CLI mid-write and leave a stale graph.html on disk.
|
||||
html_target = out / "graph.html"
|
||||
if no_viz:
|
||||
if html_target.exists():
|
||||
html_target.unlink()
|
||||
print(f"Done — {len(communities)} communities. GRAPH_REPORT.md and graph.json updated (--no-viz; graph.html removed).")
|
||||
else:
|
||||
try:
|
||||
to_html(G, communities, str(html_target), community_labels=labels or None)
|
||||
print(f"Done — {len(communities)} communities. GRAPH_REPORT.md, graph.json and graph.html updated.")
|
||||
except ValueError as viz_err:
|
||||
if html_target.exists():
|
||||
html_target.unlink()
|
||||
print(f"Skipped graph.html: {viz_err}")
|
||||
print(f"Done — {len(communities)} communities. GRAPH_REPORT.md and graph.json updated.")
|
||||
|
||||
elif cmd == "update":
|
||||
watch_path = Path(sys.argv[2]) if len(sys.argv) > 2 else Path(".")
|
||||
if len(sys.argv) > 2:
|
||||
watch_path = Path(sys.argv[2])
|
||||
else:
|
||||
# Try to recover the scan root saved by the last full build
|
||||
saved = Path("graphify-out/.graphify_root")
|
||||
if saved.exists():
|
||||
watch_path = Path(saved.read_text(encoding="utf-8").strip())
|
||||
else:
|
||||
watch_path = Path(".")
|
||||
if not watch_path.exists():
|
||||
print(f"error: path not found: {watch_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -1348,6 +1509,8 @@ def main() -> None:
|
||||
ok = _rebuild_code(watch_path)
|
||||
if ok:
|
||||
print("Code graph updated. For doc/paper/image changes run /graphify --update in your AI assistant.")
|
||||
if not os.environ.get("MOONSHOT_API_KEY") and not os.environ.get("GRAPHIFY_NO_TIPS"):
|
||||
print("Tip: set MOONSHOT_API_KEY to use Kimi K2.6 for semantic extraction — 3x cheaper, richer graphs. pip install 'graphifyy[kimi]'")
|
||||
else:
|
||||
print("Nothing to update or rebuild failed — check output above.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -1359,6 +1522,66 @@ def main() -> None:
|
||||
from graphify.watch import check_update
|
||||
check_update(Path(sys.argv[2]).resolve())
|
||||
sys.exit(0)
|
||||
elif cmd == "merge-graphs":
|
||||
# graphify merge-graphs graph1.json graph2.json ... --out merged.json
|
||||
args = sys.argv[2:]
|
||||
graph_paths: list[Path] = []
|
||||
out_path = Path("graphify-out/merged-graph.json")
|
||||
i = 0
|
||||
while i < len(args):
|
||||
if args[i] == "--out" and i + 1 < len(args):
|
||||
out_path = Path(args[i + 1]); i += 2
|
||||
else:
|
||||
graph_paths.append(Path(args[i])); i += 1
|
||||
if len(graph_paths) < 2:
|
||||
print("Usage: graphify merge-graphs <graph1.json> <graph2.json> [...] [--out merged.json]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
import networkx as _nx
|
||||
from networkx.readwrite import json_graph as _jg
|
||||
graphs = []
|
||||
for gp in graph_paths:
|
||||
if not gp.exists():
|
||||
print(f"error: not found: {gp}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
data = json.loads(gp.read_text(encoding="utf-8"))
|
||||
try:
|
||||
G = _jg.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
G = _jg.node_link_graph(data)
|
||||
# Tag every node with which repo it came from
|
||||
repo_tag = gp.parent.parent.name # graphify-out/../ → repo dir name
|
||||
for node in G.nodes:
|
||||
G.nodes[node].setdefault("repo", repo_tag)
|
||||
graphs.append(G)
|
||||
merged = _nx.compose_all(graphs)
|
||||
try:
|
||||
out_data = _jg.node_link_data(merged, edges="links")
|
||||
except TypeError:
|
||||
out_data = _jg.node_link_data(merged)
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_text(json.dumps(out_data, indent=2), encoding="utf-8")
|
||||
print(f"Merged {len(graphs)} graphs → {merged.number_of_nodes()} nodes, {merged.number_of_edges()} edges")
|
||||
print(f"Written to: {out_path}")
|
||||
|
||||
elif cmd == "clone":
|
||||
if len(sys.argv) < 3:
|
||||
print("Usage: graphify clone <github-url> [--branch <branch>] [--out <dir>]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
url = sys.argv[2]
|
||||
branch: str | None = None
|
||||
out_dir: Path | None = None
|
||||
args = sys.argv[3:]
|
||||
i = 0
|
||||
while i < len(args):
|
||||
if args[i] == "--branch" and i + 1 < len(args):
|
||||
branch = args[i + 1]; i += 2
|
||||
elif args[i] == "--out" and i + 1 < len(args):
|
||||
out_dir = Path(args[i + 1]); i += 2
|
||||
else:
|
||||
i += 1
|
||||
local_path = _clone_repo(url, branch=branch, out_dir=out_dir)
|
||||
print(local_path)
|
||||
|
||||
elif cmd == "benchmark":
|
||||
from graphify.benchmark import run_benchmark, print_benchmark
|
||||
graph_path = sys.argv[2] if len(sys.argv) > 2 else "graphify-out/graph.json"
|
||||
|
||||
@@ -21,8 +21,10 @@
|
||||
# before any graph construction happens.
|
||||
#
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
from .validate import validate_extraction
|
||||
|
||||
@@ -50,6 +52,18 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
|
||||
# Canonicalize legacy node/edge schema before validation.
|
||||
for node in extraction.get("nodes", []):
|
||||
if isinstance(node, dict) and "source" in node and "source_file" not in node:
|
||||
# Count edges that reference this node so the warning is actionable (#479)
|
||||
node_id = node.get("id", "?")
|
||||
affected_edges = sum(
|
||||
1 for e in extraction.get("edges", [])
|
||||
if e.get("source") == node_id or e.get("target") == node_id
|
||||
)
|
||||
print(
|
||||
f"[graphify] WARNING: node '{node_id}' uses field 'source' instead of "
|
||||
f"'source_file' — {affected_edges} edge(s) may be misrouted. "
|
||||
f"Rename the field to 'source_file' to silence this warning.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
node["source_file"] = node.pop("source")
|
||||
|
||||
errors = validate_extraction(extraction)
|
||||
@@ -111,3 +125,110 @@ def build(extractions: list[dict], *, directed: bool = False) -> nx.Graph:
|
||||
combined["input_tokens"] += ext.get("input_tokens", 0)
|
||||
combined["output_tokens"] += ext.get("output_tokens", 0)
|
||||
return build_from_json(combined, directed=directed)
|
||||
|
||||
|
||||
def _norm_label(label: str) -> str:
|
||||
"""Canonical dedup key — lowercase, alphanumeric only."""
|
||||
return re.sub(r"[^a-z0-9 ]", "", label.lower()).strip()
|
||||
|
||||
|
||||
def deduplicate_by_label(nodes: list[dict], edges: list[dict]) -> tuple[list[dict], list[dict]]:
|
||||
"""Merge nodes that share a normalised label, rewriting edge references.
|
||||
|
||||
Prefers IDs without chunk suffixes (_c\\d+) and shorter IDs when tied.
|
||||
Drops self-loops created by the merge. Called in build() automatically.
|
||||
"""
|
||||
_CHUNK_SUFFIX = re.compile(r"_c\d+$")
|
||||
canonical: dict[str, dict] = {} # norm_label -> surviving node
|
||||
remap: dict[str, str] = {} # old_id -> surviving_id
|
||||
|
||||
for node in nodes:
|
||||
key = _norm_label(node.get("label", node.get("id", "")))
|
||||
if not key:
|
||||
continue
|
||||
existing = canonical.get(key)
|
||||
if existing is None:
|
||||
canonical[key] = node
|
||||
else:
|
||||
has_suffix = bool(_CHUNK_SUFFIX.search(node["id"]))
|
||||
existing_has_suffix = bool(_CHUNK_SUFFIX.search(existing["id"]))
|
||||
if has_suffix and not existing_has_suffix:
|
||||
remap[node["id"]] = existing["id"]
|
||||
elif existing_has_suffix and not has_suffix:
|
||||
remap[existing["id"]] = node["id"]
|
||||
canonical[key] = node
|
||||
elif len(node["id"]) < len(existing["id"]):
|
||||
remap[existing["id"]] = node["id"]
|
||||
canonical[key] = node
|
||||
else:
|
||||
remap[node["id"]] = existing["id"]
|
||||
|
||||
if not remap:
|
||||
return nodes, edges
|
||||
|
||||
print(f"[graphify] Deduplicated {len(remap)} duplicate node(s) by label.", file=sys.stderr)
|
||||
deduped_nodes = list(canonical.values())
|
||||
deduped_edges = []
|
||||
for edge in edges:
|
||||
e = dict(edge)
|
||||
e["source"] = remap.get(e["source"], e["source"])
|
||||
e["target"] = remap.get(e["target"], e["target"])
|
||||
if e["source"] != e["target"]:
|
||||
deduped_edges.append(e)
|
||||
return deduped_nodes, deduped_edges
|
||||
|
||||
|
||||
def build_merge(
|
||||
new_chunks: list[dict],
|
||||
graph_path: str | Path = "graphify-out/graph.json",
|
||||
prune_sources: list[str] | None = None,
|
||||
*,
|
||||
directed: bool = False,
|
||||
) -> nx.Graph:
|
||||
"""Load existing graph.json, merge new chunks into it, and save back.
|
||||
|
||||
Never replaces — only grows (or prunes deleted-file nodes via prune_sources).
|
||||
Safe to call repeatedly: existing nodes and edges are preserved.
|
||||
"""
|
||||
from networkx.readwrite import json_graph as _jg
|
||||
|
||||
graph_path = Path(graph_path)
|
||||
if graph_path.exists():
|
||||
data = json.loads(graph_path.read_text(encoding="utf-8"))
|
||||
try:
|
||||
existing_G = _jg.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
existing_G = _jg.node_link_graph(data)
|
||||
# Reconstruct as a plain extraction dict so build() can merge it
|
||||
existing_nodes = [{"id": n, **existing_G.nodes[n]} for n in existing_G.nodes]
|
||||
existing_edges = [
|
||||
{"source": u, "target": v, **d} for u, v, d in existing_G.edges(data=True)
|
||||
]
|
||||
base = [{"nodes": existing_nodes, "edges": existing_edges}]
|
||||
else:
|
||||
base = []
|
||||
|
||||
all_chunks = base + list(new_chunks)
|
||||
G = build(all_chunks, directed=directed)
|
||||
|
||||
# Prune nodes from deleted source files
|
||||
if prune_sources:
|
||||
to_remove = [
|
||||
n for n, d in G.nodes(data=True)
|
||||
if d.get("source_file") in prune_sources
|
||||
]
|
||||
G.remove_nodes_from(to_remove)
|
||||
if to_remove:
|
||||
print(f"[graphify] Pruned {len(to_remove)} node(s) from deleted sources.", file=sys.stderr)
|
||||
|
||||
# Safety check: refuse to shrink the graph silently (#479)
|
||||
if graph_path.exists():
|
||||
existing_n = len(existing_nodes)
|
||||
new_n = G.number_of_nodes()
|
||||
if new_n < existing_n:
|
||||
raise ValueError(
|
||||
f"graphify: build_merge would shrink graph from {existing_n} → {new_n} nodes. "
|
||||
f"Pass prune_sources explicitly if you intend to remove nodes."
|
||||
)
|
||||
|
||||
return G
|
||||
+59
-25
@@ -43,37 +43,52 @@ def file_hash(path: Path, root: Path = Path(".")) -> str:
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def cache_dir(root: Path = Path(".")) -> Path:
|
||||
"""Returns graphify-out/cache/ - creates it if needed."""
|
||||
d = Path(root).resolve() / "graphify-out" / "cache"
|
||||
def cache_dir(root: Path = Path("."), kind: str = "ast") -> Path:
|
||||
"""Returns graphify-out/cache/{kind}/ - creates it if needed.
|
||||
|
||||
kind is "ast" or "semantic". Separate subdirectories prevent semantic cache
|
||||
entries from overwriting AST cache entries for the same source_file (#582).
|
||||
"""
|
||||
d = Path(root).resolve() / "graphify-out" / "cache" / kind
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def load_cached(path: Path, root: Path = Path(".")) -> dict | None:
|
||||
def load_cached(path: Path, root: Path = Path("."), kind: str = "ast") -> dict | None:
|
||||
"""Return cached extraction for this file if hash matches, else None.
|
||||
|
||||
Cache key: SHA256 of file contents.
|
||||
Cache value: stored as graphify-out/cache/{hash}.json
|
||||
Cache value: stored as graphify-out/cache/{kind}/{hash}.json
|
||||
|
||||
For kind="ast", also checks the legacy flat cache/ directory so users
|
||||
upgrading from pre-0.5.3 don't lose their existing AST cache entries.
|
||||
Returns None if no cache entry or file has changed.
|
||||
"""
|
||||
try:
|
||||
h = file_hash(path, root)
|
||||
except OSError:
|
||||
return None
|
||||
entry = cache_dir(root) / f"{h}.json"
|
||||
if not entry.exists():
|
||||
return None
|
||||
try:
|
||||
return json.loads(entry.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
entry = cache_dir(root, kind) / f"{h}.json"
|
||||
if entry.exists():
|
||||
try:
|
||||
return json.loads(entry.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
# Migration fallback: check legacy flat cache/ dir for AST entries
|
||||
if kind == "ast":
|
||||
legacy = Path(root).resolve() / "graphify-out" / "cache" / f"{h}.json"
|
||||
if legacy.exists():
|
||||
try:
|
||||
return json.loads(legacy.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
|
||||
def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "ast") -> None:
|
||||
"""Save extraction result for this file.
|
||||
|
||||
Stores as graphify-out/cache/{hash}.json where hash = SHA256 of current file contents.
|
||||
Stores as graphify-out/cache/{kind}/{hash}.json where hash = SHA256 of current file contents.
|
||||
result should be a dict with 'nodes' and 'edges' lists.
|
||||
|
||||
No-ops if `path` is not a regular file. Subagent-produced semantic fragments
|
||||
@@ -84,7 +99,7 @@ def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
|
||||
if not p.is_file():
|
||||
return
|
||||
h = file_hash(p, root)
|
||||
entry = cache_dir(root) / f"{h}.json"
|
||||
entry = cache_dir(root, kind) / f"{h}.json"
|
||||
tmp = entry.with_suffix(".tmp")
|
||||
try:
|
||||
tmp.write_text(json.dumps(result), encoding="utf-8")
|
||||
@@ -102,16 +117,33 @@ def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
|
||||
|
||||
|
||||
def cached_files(root: Path = Path(".")) -> set[str]:
|
||||
"""Return set of file paths that have a valid cache entry (hash still matches)."""
|
||||
d = cache_dir(root)
|
||||
return {p.stem for p in d.glob("*.json")}
|
||||
"""Return set of file hashes that have a valid cache entry (any kind)."""
|
||||
base = Path(root).resolve() / "graphify-out" / "cache"
|
||||
hashes: set[str] = set()
|
||||
# Legacy flat entries
|
||||
if base.is_dir():
|
||||
hashes.update(p.stem for p in base.glob("*.json"))
|
||||
# Namespaced entries
|
||||
for kind in ("ast", "semantic"):
|
||||
d = base / kind
|
||||
if d.is_dir():
|
||||
hashes.update(p.stem for p in d.glob("*.json"))
|
||||
return hashes
|
||||
|
||||
|
||||
def clear_cache(root: Path = Path(".")) -> None:
|
||||
"""Delete all graphify-out/cache/*.json files."""
|
||||
d = cache_dir(root)
|
||||
for f in d.glob("*.json"):
|
||||
f.unlink()
|
||||
"""Delete all cache entries (ast/, semantic/, and legacy flat entries)."""
|
||||
base = Path(root).resolve() / "graphify-out" / "cache"
|
||||
# Legacy flat entries
|
||||
if base.is_dir():
|
||||
for f in base.glob("*.json"):
|
||||
f.unlink()
|
||||
# Namespaced entries
|
||||
for kind in ("ast", "semantic"):
|
||||
d = base / kind
|
||||
if d.is_dir():
|
||||
for f in d.glob("*.json"):
|
||||
f.unlink()
|
||||
|
||||
|
||||
def check_semantic_cache(
|
||||
@@ -129,7 +161,7 @@ def check_semantic_cache(
|
||||
uncached: list[str] = []
|
||||
|
||||
for fpath in files:
|
||||
result = load_cached(Path(fpath), root)
|
||||
result = load_cached(Path(fpath), root, kind="semantic")
|
||||
if result is not None:
|
||||
cached_nodes.extend(result.get("nodes", []))
|
||||
cached_edges.extend(result.get("edges", []))
|
||||
@@ -148,7 +180,9 @@ def save_semantic_cache(
|
||||
) -> int:
|
||||
"""Save semantic extraction results to cache, keyed by source_file.
|
||||
|
||||
Groups nodes and edges by source_file, then saves one cache entry per file.
|
||||
Groups nodes and edges by source_file, then saves one cache entry per file
|
||||
under cache/semantic/ (separate from AST entries in cache/ast/) to prevent
|
||||
hash-key collisions (#582).
|
||||
Returns the number of files cached.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
@@ -173,6 +207,6 @@ def save_semantic_cache(
|
||||
if not p.is_absolute():
|
||||
p = Path(root) / p
|
||||
if p.is_file():
|
||||
save_cached(p, result, root)
|
||||
save_cached(p, result, root, kind="semantic")
|
||||
saved += 1
|
||||
return saved
|
||||
+96
-24
@@ -19,7 +19,7 @@ class FileType(str, Enum):
|
||||
_MANIFEST_PATH = "graphify-out/manifest.json"
|
||||
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.ejs', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.dart', '.v', '.sv'}
|
||||
DOC_EXTENSIONS = {'.md', '.mdx', '.txt', '.rst', '.html'}
|
||||
DOC_EXTENSIONS = {'.md', '.mdx', '.txt', '.rst', '.html', '.yaml', '.yml'}
|
||||
PAPER_EXTENSIONS = {'.pdf'}
|
||||
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
|
||||
OFFICE_EXTENSIONS = {'.docx', '.xlsx'}
|
||||
@@ -241,6 +241,7 @@ _SKIP_DIRS = {
|
||||
"site-packages", "lib64",
|
||||
".pytest_cache", ".mypy_cache", ".ruff_cache",
|
||||
".tox", ".eggs", "*.egg-info",
|
||||
"graphify-out", # never treat own output as source input (#524)
|
||||
}
|
||||
|
||||
# Large generated files that are never useful to extract
|
||||
@@ -262,13 +263,13 @@ def _is_noise_dir(part: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
"""Read .graphifyignore from root **and ancestor directories**.
|
||||
def _load_pattern_file(root: Path, filename: str) -> list[tuple[Path, str]]:
|
||||
"""Read a Graphify pattern file from root **and ancestor directories**.
|
||||
|
||||
Returns a list of (anchor_dir, pattern) pairs. Each pattern is matched
|
||||
against paths relative to both the scan root and the anchor_dir where
|
||||
the .graphifyignore file was found — so patterns written relative to a
|
||||
parent directory still work when graphify is run on a subfolder.
|
||||
the pattern file was found — so patterns written relative to a parent
|
||||
directory still work when graphify is run on a subfolder.
|
||||
|
||||
Walks upward from *root* towards the filesystem root, stopping at a
|
||||
``.git`` boundary. Lines starting with # are comments; blank lines ignored.
|
||||
@@ -276,9 +277,9 @@ def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
patterns: list[tuple[Path, str]] = []
|
||||
current = root.resolve()
|
||||
while True:
|
||||
ignore_file = current / ".graphifyignore"
|
||||
if ignore_file.exists():
|
||||
for line in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||
pattern_file = current / filename
|
||||
if pattern_file.exists():
|
||||
for line in pattern_file.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#"):
|
||||
patterns.append((current, line))
|
||||
@@ -292,13 +293,29 @@ def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
return patterns
|
||||
|
||||
|
||||
def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if path matches any .graphifyignore pattern."""
|
||||
if not patterns:
|
||||
return False
|
||||
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
"""Read .graphifyignore patterns from root and ancestor directories."""
|
||||
return _load_pattern_file(root, ".graphifyignore")
|
||||
|
||||
def _matches(rel: str, p: str) -> bool:
|
||||
parts = rel.split("/")
|
||||
|
||||
def _load_graphifyinclude(root: Path) -> list[tuple[Path, str]]:
|
||||
"""Read .graphifyinclude allowlist patterns from root and ancestors.
|
||||
|
||||
Include patterns are intentionally narrow: they only opt matching files and
|
||||
the directories needed to reach them into hidden-path traversal. Sensitive
|
||||
files and hard-skipped noise directories are still excluded later.
|
||||
"""
|
||||
return _load_pattern_file(root, ".graphifyinclude")
|
||||
|
||||
|
||||
def _pattern_matches(path: Path, rel: str, pattern: str) -> bool:
|
||||
"""Return True if *rel* or path.name matches a Graphify glob pattern."""
|
||||
parts = rel.split("/")
|
||||
candidates = [pattern]
|
||||
if "/**/" in pattern:
|
||||
# Treat foo/**/*.md as matching both foo/bar.md and foo/a/bar.md.
|
||||
candidates.append(pattern.replace("/**/", "/"))
|
||||
for p in candidates:
|
||||
if fnmatch.fnmatch(rel, p):
|
||||
return True
|
||||
if fnmatch.fnmatch(path.name, p):
|
||||
@@ -308,6 +325,12 @@ def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> boo
|
||||
return True
|
||||
if fnmatch.fnmatch("/".join(parts[:i + 1]), p):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _matches_patterns(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if path matches any pattern loaded for root/ancestors."""
|
||||
if not patterns:
|
||||
return False
|
||||
|
||||
for anchor, pattern in patterns:
|
||||
@@ -317,22 +340,64 @@ def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> boo
|
||||
# Try path relative to the scan root
|
||||
try:
|
||||
rel = str(path.relative_to(root)).replace(os.sep, "/")
|
||||
if _matches(rel, p):
|
||||
if _pattern_matches(path, rel, p):
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
# Also try relative to the anchor dir (the .graphifyignore's location),
|
||||
# so patterns written at a parent level still fire when running on a subfolder
|
||||
# Also try relative to the anchor dir (the pattern file's location),
|
||||
# so parent-level patterns still fire when running on a subfolder.
|
||||
if anchor != root:
|
||||
try:
|
||||
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
|
||||
if _matches(rel_anchor, p):
|
||||
if _pattern_matches(path, rel_anchor, p):
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if path matches any .graphifyignore pattern."""
|
||||
return _matches_patterns(path, root, patterns)
|
||||
|
||||
|
||||
def _is_included(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if path matches any .graphifyinclude allowlist pattern."""
|
||||
return _matches_patterns(path, root, patterns)
|
||||
|
||||
|
||||
def _could_contain_included_path(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if a directory may contain files matched by .graphifyinclude."""
|
||||
if not patterns:
|
||||
return False
|
||||
|
||||
rels: list[str] = []
|
||||
try:
|
||||
rels.append(str(path.relative_to(root)).replace(os.sep, "/"))
|
||||
except ValueError:
|
||||
pass
|
||||
for anchor, _ in patterns:
|
||||
if anchor != root:
|
||||
try:
|
||||
rels.append(str(path.relative_to(anchor)).replace(os.sep, "/"))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
for rel in rels:
|
||||
rel = rel.strip("/")
|
||||
if not rel:
|
||||
return True
|
||||
for _, pattern in patterns:
|
||||
p = pattern.strip("/")
|
||||
if not p:
|
||||
continue
|
||||
if p == rel or p.startswith(rel + "/"):
|
||||
return True
|
||||
if _pattern_matches(path, rel, p):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
root = root.resolve()
|
||||
files: dict[FileType, list[str]] = {
|
||||
@@ -346,6 +411,7 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
|
||||
skipped_sensitive: list[str] = []
|
||||
ignore_patterns = _load_graphifyignore(root)
|
||||
include_patterns = _load_graphifyinclude(root)
|
||||
|
||||
# Always include graphify-out/memory/ - query results filed back into the graph
|
||||
memory_dir = root / "graphify-out" / "memory"
|
||||
@@ -367,11 +433,13 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
dirnames.clear()
|
||||
continue
|
||||
if not in_memory_tree:
|
||||
# Prune noise dirs in-place so os.walk never descends into them
|
||||
# Prune noise dirs in-place so os.walk never descends into them.
|
||||
# Hidden dirs remain skipped by default, but .graphifyinclude can
|
||||
# opt in the exact hidden subtrees needed to reach allowlisted files.
|
||||
dirnames[:] = [
|
||||
d for d in dirnames
|
||||
if not d.startswith(".")
|
||||
and not _is_noise_dir(d)
|
||||
if not _is_noise_dir(d)
|
||||
and (not d.startswith(".") or _could_contain_included_path(dp / d, root, include_patterns))
|
||||
and not _is_ignored(dp / d, root, ignore_patterns)
|
||||
]
|
||||
for fname in filenames:
|
||||
@@ -388,9 +456,12 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
# For memory dir files, skip hidden/noise filtering
|
||||
in_memory = memory_dir.exists() and str(p).startswith(str(memory_dir))
|
||||
if not in_memory:
|
||||
# Hidden files are already excluded via dir pruning above,
|
||||
# but catch hidden files at the root level
|
||||
if p.name.startswith("."):
|
||||
try:
|
||||
rel_parts = p.relative_to(root).parts
|
||||
except ValueError:
|
||||
rel_parts = p.parts
|
||||
# Hidden files/directories are excluded unless this exact file is allowlisted.
|
||||
if any(part.startswith(".") for part in rel_parts) and not _is_included(p, root, include_patterns):
|
||||
continue
|
||||
# Skip files inside our own converted/ dir (avoid re-processing sidecars)
|
||||
if str(p).startswith(str(converted_dir)):
|
||||
@@ -441,6 +512,7 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
"warning": warning,
|
||||
"skipped_sensitive": skipped_sensitive,
|
||||
"graphifyignore_patterns": len(ignore_patterns),
|
||||
"graphifyinclude_patterns": len(include_patterns),
|
||||
}
|
||||
|
||||
|
||||
|
||||
+88
-15
@@ -25,6 +25,22 @@ COMMUNITY_COLORS = [
|
||||
MAX_NODES_FOR_VIZ = 5_000
|
||||
|
||||
|
||||
def _viz_node_limit() -> int:
|
||||
"""Return the effective viz node limit, honoring GRAPHIFY_VIZ_NODE_LIMIT env var.
|
||||
|
||||
Falls back to MAX_NODES_FOR_VIZ when the env var is unset, empty, or non-integer.
|
||||
Set to 0 to disable HTML viz unconditionally (useful for CI runners).
|
||||
"""
|
||||
import os
|
||||
raw = os.environ.get("GRAPHIFY_VIZ_NODE_LIMIT")
|
||||
if raw is None or not raw.strip():
|
||||
return MAX_NODES_FOR_VIZ
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError:
|
||||
return MAX_NODES_FOR_VIZ
|
||||
|
||||
|
||||
def _html_styles() -> str:
|
||||
return """<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
@@ -55,6 +71,9 @@ def _html_styles() -> str:
|
||||
.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; }
|
||||
#legend-controls { display: flex; gap: 6px; margin-bottom: 8px; }
|
||||
#legend-controls button { flex: 1; background: #0f0f1a; border: 1px solid #3a3a5e; color: #aaa; padding: 4px 0; border-radius: 4px; font-size: 11px; cursor: pointer; }
|
||||
#legend-controls button:hover { border-color: #4E79A7; color: #e0e0e0; }
|
||||
</style>"""
|
||||
|
||||
|
||||
@@ -240,6 +259,18 @@ document.addEventListener('click', e => {{
|
||||
}});
|
||||
|
||||
const hiddenCommunities = new Set();
|
||||
|
||||
function toggleAllCommunities(hide) {{
|
||||
document.querySelectorAll('.legend-item').forEach(item => {{
|
||||
hide ? item.classList.add('dimmed') : item.classList.remove('dimmed');
|
||||
}});
|
||||
LEGEND.forEach(c => {{
|
||||
if (hide) hiddenCommunities.add(c.cid); else hiddenCommunities.delete(c.cid);
|
||||
}});
|
||||
const updates = RAW_NODES.map(n => ({{ id: n.id, hidden: hide }}));
|
||||
nodesDS.update(updates);
|
||||
}}
|
||||
|
||||
const legendEl = document.getElementById('legend');
|
||||
LEGEND.forEach(c => {{
|
||||
const item = document.createElement('div');
|
||||
@@ -279,7 +310,27 @@ def attach_hyperedges(G: nx.Graph, hyperedges: list) -> None:
|
||||
G.graph["hyperedges"] = existing
|
||||
|
||||
|
||||
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) -> None:
|
||||
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *, force: bool = False) -> bool:
|
||||
# Safety check: refuse to silently shrink an existing graph (#479)
|
||||
existing_path = Path(output_path)
|
||||
if not force and existing_path.exists():
|
||||
try:
|
||||
existing_data = json.loads(existing_path.read_text(encoding="utf-8"))
|
||||
existing_n = len(existing_data.get("nodes", []))
|
||||
new_n = G.number_of_nodes()
|
||||
if new_n < existing_n:
|
||||
import sys as _sys
|
||||
print(
|
||||
f"[graphify] WARNING: new graph has {new_n} nodes but existing "
|
||||
f"graph.json has {existing_n}. Refusing to overwrite — you may be "
|
||||
f"missing chunk files from a previous session. "
|
||||
f"Pass force=True to override.",
|
||||
file=_sys.stderr,
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
pass # unreadable existing file — proceed with write
|
||||
|
||||
node_community = _node_community_map(communities)
|
||||
try:
|
||||
data = json_graph.node_link_data(G, edges="links")
|
||||
@@ -292,9 +343,19 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) ->
|
||||
if "confidence_score" not in link:
|
||||
conf = link.get("confidence", "EXTRACTED")
|
||||
link["confidence_score"] = _CONFIDENCE_SCORE_DEFAULTS.get(conf, 1.0)
|
||||
# Restore original edge direction. Undirected NetworkX storage may
|
||||
# canonicalize endpoint order, flipping `calls` and other directional
|
||||
# edges in graph.json. The build path stashes the true endpoints in
|
||||
# _src/_tgt for exactly this purpose (#563).
|
||||
true_src = link.pop("_src", None)
|
||||
true_tgt = link.pop("_tgt", None)
|
||||
if true_src is not None and true_tgt is not None:
|
||||
link["source"] = true_src
|
||||
link["target"] = true_tgt
|
||||
data["hyperedges"] = getattr(G, "graph", {}).get("hyperedges", [])
|
||||
with open(output_path, "w", encoding="utf-8") as f:
|
||||
with open(output_path, "w", encoding="utf-8") as f: # nosec
|
||||
json.dump(data, f, indent=2)
|
||||
return True
|
||||
|
||||
|
||||
def prune_dangling_edges(graph_data: dict) -> tuple[dict, int]:
|
||||
@@ -335,7 +396,7 @@ def to_cypher(G: nx.Graph, output_path: str) -> None:
|
||||
f"MATCH (a {{id: '{u_esc}'}}), (b {{id: '{v_esc}'}}) "
|
||||
f"MERGE (a)-[:{rel} {{confidence: '{conf}'}}]->(b);"
|
||||
)
|
||||
with open(output_path, "w", encoding="utf-8") as f:
|
||||
with open(output_path, "w", encoding="utf-8") as f: # nosec
|
||||
f.write("\n".join(lines))
|
||||
|
||||
|
||||
@@ -350,15 +411,18 @@ def to_html(
|
||||
|
||||
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.
|
||||
Raises ValueError if graph exceeds the effective viz node limit
|
||||
(MAX_NODES_FOR_VIZ by default; overridable via GRAPHIFY_VIZ_NODE_LIMIT env var).
|
||||
|
||||
If member_counts is provided (aggregated community view), node sizes are
|
||||
based on community member counts rather than graph degree.
|
||||
"""
|
||||
if G.number_of_nodes() > MAX_NODES_FOR_VIZ:
|
||||
limit = _viz_node_limit()
|
||||
if G.number_of_nodes() > limit:
|
||||
raise ValueError(
|
||||
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz. "
|
||||
f"Use --no-viz or reduce input size."
|
||||
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz "
|
||||
f"(limit: {limit}). Use --no-viz, raise GRAPHIFY_VIZ_NODE_LIMIT, "
|
||||
f"or reduce input size."
|
||||
)
|
||||
|
||||
node_community = _node_community_map(communities)
|
||||
@@ -395,14 +459,19 @@ def to_html(
|
||||
"degree": deg,
|
||||
})
|
||||
|
||||
# Build edges list
|
||||
# Build edges list. Restore original edge direction from _src/_tgt
|
||||
# (stashed by build.py for exactly this reason): undirected NetworkX
|
||||
# canonicalizes endpoint order, which would otherwise flip the arrow
|
||||
# for `calls` and `rationale_for` in the rendered graph (#563).
|
||||
vis_edges = []
|
||||
for u, v, data in G.edges(data=True):
|
||||
confidence = data.get("confidence", "EXTRACTED")
|
||||
relation = data.get("relation", "")
|
||||
true_src = data.get("_src", u)
|
||||
true_tgt = data.get("_tgt", v)
|
||||
vis_edges.append({
|
||||
"from": u,
|
||||
"to": v,
|
||||
"from": true_src,
|
||||
"to": true_tgt,
|
||||
"label": relation,
|
||||
"title": _html.escape(f"{relation} [{confidence}]"),
|
||||
"dashes": confidence != "EXTRACTED",
|
||||
@@ -451,6 +520,10 @@ def to_html(
|
||||
</div>
|
||||
<div id="legend-wrap">
|
||||
<h3>Communities</h3>
|
||||
<div id="legend-controls">
|
||||
<button onclick="toggleAllCommunities(false)">Show All</button>
|
||||
<button onclick="toggleAllCommunities(true)">Hide All</button>
|
||||
</div>
|
||||
<div id="legend"></div>
|
||||
</div>
|
||||
<div id="stats">{stats}</div>
|
||||
@@ -460,7 +533,7 @@ def to_html(
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
Path(output_path).write_text(html, encoding="utf-8")
|
||||
Path(output_path).write_text(html, encoding="utf-8") # nosec
|
||||
|
||||
|
||||
# Keep backward-compatible alias - skill.md calls generate_html
|
||||
@@ -575,7 +648,7 @@ def to_obsidian(
|
||||
lines.append(inline_tags)
|
||||
|
||||
fname = node_filename[node_id] + ".md"
|
||||
(out / fname).write_text("\n".join(lines), encoding="utf-8")
|
||||
(out / fname).write_text("\n".join(lines), encoding="utf-8") # nosec
|
||||
|
||||
# Write one _COMMUNITY_name.md overview note per community
|
||||
# Build inter-community edge counts for "Connections to other communities"
|
||||
@@ -692,7 +765,7 @@ def to_obsidian(
|
||||
|
||||
community_safe = safe_name(community_name)
|
||||
fname = f"_COMMUNITY_{community_safe}.md"
|
||||
(out / fname).write_text("\n".join(lines), encoding="utf-8")
|
||||
(out / fname).write_text("\n".join(lines), encoding="utf-8") # nosec
|
||||
community_notes_written += 1
|
||||
|
||||
# Improvement 4: write .obsidian/graph.json to color nodes by community in graph view
|
||||
@@ -707,7 +780,7 @@ def to_obsidian(
|
||||
for cid, label in sorted((community_labels or {}).items())
|
||||
]
|
||||
}
|
||||
(obsidian_dir / "graph.json").write_text(json.dumps(graph_config, indent=2), encoding="utf-8")
|
||||
(obsidian_dir / "graph.json").write_text(json.dumps(graph_config, indent=2), encoding="utf-8") # nosec
|
||||
|
||||
return G.number_of_nodes() + community_notes_written
|
||||
|
||||
@@ -868,7 +941,7 @@ def to_canvas(
|
||||
})
|
||||
|
||||
canvas_data = {"nodes": canvas_nodes, "edges": canvas_edges}
|
||||
Path(output_path).write_text(json.dumps(canvas_data, indent=2), encoding="utf-8")
|
||||
Path(output_path).write_text(json.dumps(canvas_data, indent=2), encoding="utf-8") # nosec
|
||||
|
||||
|
||||
def push_to_neo4j(
|
||||
|
||||
+193
-22
@@ -11,6 +11,29 @@ from typing import Callable, Any
|
||||
from .cache import load_cached, save_cached
|
||||
|
||||
|
||||
# AST node types that represent a member-expression callee
|
||||
# (`x.foo()`, `obj.bar()`, `Pkg::baz()`). Cross-file name-only resolution of
|
||||
# these is unsafe — without receiver type info we routinely link them to the
|
||||
# wrong target, producing phantom god nodes (e.g. every `Logger.log(...)` call
|
||||
# in a NestJS codebase collapsing onto a one-off `function log(...)` defined
|
||||
# in a smoke-test script). The cross-file resolver in `extract()` skips
|
||||
# entries whose `callee_node_type` falls in this set.
|
||||
_MEMBER_CALL_NODE_TYPES = frozenset({
|
||||
"member_expression", # JS / TS / Python attribute calls
|
||||
"selector_expression", # Go
|
||||
"field_expression", # Rust, C++, Scala
|
||||
"navigation_expression", # Swift, Kotlin
|
||||
"qualified_identifier", # C++ (Foo::bar())
|
||||
"scoped_identifier", # Rust (foo::bar())
|
||||
"scoped_call_expression", # PHP (Foo::bar())
|
||||
"member_call_expression", # PHP ($obj->method())
|
||||
"field_access", # Java
|
||||
"method_invocation", # Java (when receiver-qualified)
|
||||
"dot", # Elixir
|
||||
"_zig_dotted_callee", # synthetic marker for Zig (callee text contains ".")
|
||||
})
|
||||
|
||||
|
||||
def _make_id(*parts: str) -> str:
|
||||
"""Build a stable node ID from one or more name parts."""
|
||||
combined = "_".join(p.strip("_.") for p in parts if p)
|
||||
@@ -18,6 +41,48 @@ def _make_id(*parts: str) -> str:
|
||||
return cleaned.strip("_").lower()
|
||||
|
||||
|
||||
def _file_stem(path: Path) -> str:
|
||||
"""Return a stem qualified with the parent directory name to avoid ID collisions
|
||||
when multiple files share the same filename in different directories (#550)."""
|
||||
parent = path.parent.name
|
||||
if parent and parent not in (".", ""):
|
||||
return f"{parent}.{path.stem}"
|
||||
return path.stem
|
||||
|
||||
|
||||
_TSCONFIG_ALIAS_CACHE: dict[str, dict[str, str]] = {}
|
||||
|
||||
|
||||
def _load_tsconfig_aliases(start_dir: Path) -> dict[str, str]:
|
||||
"""Walk up from start_dir to find tsconfig.json and return compilerOptions.paths aliases.
|
||||
|
||||
Returns a dict mapping alias prefix (e.g. "@/") to resolved base dir (e.g. "src/").
|
||||
Result is cached by tsconfig path string.
|
||||
"""
|
||||
current = start_dir.resolve()
|
||||
for candidate in [current, *current.parents]:
|
||||
tsconfig = candidate / "tsconfig.json"
|
||||
if tsconfig.exists():
|
||||
key = str(tsconfig)
|
||||
if key not in _TSCONFIG_ALIAS_CACHE:
|
||||
try:
|
||||
data = json.loads(tsconfig.read_text(encoding="utf-8"))
|
||||
paths = data.get("compilerOptions", {}).get("paths", {})
|
||||
aliases: dict[str, str] = {}
|
||||
for alias, targets in paths.items():
|
||||
if not targets:
|
||||
continue
|
||||
# Strip trailing /* from alias and target
|
||||
alias_prefix = alias.rstrip("/*")
|
||||
target_base = targets[0].rstrip("/*")
|
||||
aliases[alias_prefix] = str(candidate / target_base)
|
||||
_TSCONFIG_ALIAS_CACHE[key] = aliases
|
||||
except Exception:
|
||||
_TSCONFIG_ALIAS_CACHE[key] = {}
|
||||
return _TSCONFIG_ALIAS_CACHE[key]
|
||||
return {}
|
||||
|
||||
|
||||
# ── LanguageConfig dataclass ─────────────────────────────────────────────────
|
||||
|
||||
@dataclass
|
||||
@@ -156,11 +221,22 @@ def _import_js(node, source: bytes, file_nid: str, stem: str, edges: list, str_p
|
||||
resolved = resolved.with_suffix(".tsx")
|
||||
tgt_nid = _make_id(str(resolved))
|
||||
else:
|
||||
# Bare/scoped import (node_modules) - use last segment; dropped as external
|
||||
module_name = raw.split("/")[-1]
|
||||
if not module_name:
|
||||
break
|
||||
tgt_nid = _make_id(module_name)
|
||||
# Check tsconfig.json path aliases (e.g. "@/" → "src/") before treating as external (#575)
|
||||
aliases = _load_tsconfig_aliases(Path(str_path).parent)
|
||||
resolved_alias = None
|
||||
for alias_prefix, alias_base in aliases.items():
|
||||
if raw == alias_prefix or raw.startswith(alias_prefix + "/"):
|
||||
rest = raw[len(alias_prefix):].lstrip("/")
|
||||
resolved_alias = Path(os.path.normpath(Path(alias_base) / rest))
|
||||
break
|
||||
if resolved_alias is not None:
|
||||
tgt_nid = _make_id(str(resolved_alias))
|
||||
else:
|
||||
# Bare/scoped import (node_modules) - use last segment; dropped as external
|
||||
module_name = raw.split("/")[-1]
|
||||
if not module_name:
|
||||
break
|
||||
tgt_nid = _make_id(module_name)
|
||||
edges.append({
|
||||
"source": file_nid,
|
||||
"target": tgt_nid,
|
||||
@@ -676,7 +752,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -999,6 +1075,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
|
||||
if node.type in config.call_types:
|
||||
callee_name: str | None = None
|
||||
is_member_call: bool = False
|
||||
|
||||
# Special handling per language
|
||||
if config.ts_module == "tree_sitter_swift":
|
||||
@@ -1008,6 +1085,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
if first.type == "simple_identifier":
|
||||
callee_name = _read_text(first, source)
|
||||
elif first.type == "navigation_expression":
|
||||
is_member_call = True
|
||||
for child in first.children:
|
||||
if child.type == "navigation_suffix":
|
||||
for sc in child.children:
|
||||
@@ -1020,6 +1098,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
if first.type == "simple_identifier":
|
||||
callee_name = _read_text(first, source)
|
||||
elif first.type == "navigation_expression":
|
||||
is_member_call = True
|
||||
for child in reversed(first.children):
|
||||
if child.type == "simple_identifier":
|
||||
callee_name = _read_text(child, source)
|
||||
@@ -1031,6 +1110,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
if first.type == "identifier":
|
||||
callee_name = _read_text(first, source)
|
||||
elif first.type == "field_expression":
|
||||
is_member_call = True
|
||||
field = first.child_by_field_name("field")
|
||||
if field:
|
||||
callee_name = _read_text(field, source)
|
||||
@@ -1050,6 +1130,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
raw = _read_text(child, source)
|
||||
if "." in raw:
|
||||
callee_name = raw.split(".")[-1]
|
||||
is_member_call = True
|
||||
else:
|
||||
callee_name = raw
|
||||
break
|
||||
@@ -1065,6 +1146,8 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
if scope_node:
|
||||
callee_name = _read_text(scope_node, source)
|
||||
else:
|
||||
# member_call_expression: $obj->method()
|
||||
is_member_call = True
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node:
|
||||
callee_name = _read_text(name_node, source)
|
||||
@@ -1075,6 +1158,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
if func_node.type == "identifier":
|
||||
callee_name = _read_text(func_node, source)
|
||||
elif func_node.type in ("field_expression", "qualified_identifier"):
|
||||
is_member_call = True
|
||||
name = func_node.child_by_field_name("field") or func_node.child_by_field_name("name")
|
||||
if name:
|
||||
callee_name = _read_text(name, source)
|
||||
@@ -1085,6 +1169,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
if func_node.type == "identifier":
|
||||
callee_name = _read_text(func_node, source)
|
||||
elif func_node.type in config.call_accessor_node_types:
|
||||
is_member_call = True
|
||||
if config.call_accessor_field:
|
||||
attr = func_node.child_by_field_name(config.call_accessor_field)
|
||||
if attr:
|
||||
@@ -1110,12 +1195,16 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
"weight": 1.0,
|
||||
})
|
||||
elif callee_name and not tgt_nid:
|
||||
# Callee not in this file — save for cross-file resolution in extract()
|
||||
# Callee not in this file — save for cross-file resolution in extract().
|
||||
# Track the AST node type so the cross-file resolver can refuse to
|
||||
# name-match member-expression callees (`x.foo()`).
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee_name,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
"callee_node_type": func_node.type if func_node is not None else None,
|
||||
})
|
||||
|
||||
# Helper function calls: config('foo.bar') → uses_config edge to "foo"
|
||||
@@ -1301,7 +1390,7 @@ def _extract_python_rationale(path: Path, result: dict) -> None:
|
||||
except Exception:
|
||||
return
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes = result["nodes"]
|
||||
edges = result["edges"]
|
||||
@@ -1560,7 +1649,7 @@ def extract_verilog(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -1676,7 +1765,7 @@ def extract_julia(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -1888,7 +1977,7 @@ def extract_go(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
# Use directory name as package scope so methods on the same type across
|
||||
# multiple files in a package share one canonical type node.
|
||||
pkg_scope = path.parent.name or stem
|
||||
@@ -1897,6 +1986,7 @@ def extract_go(path: Path) -> dict:
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
function_bodies: list[tuple[str, object]] = []
|
||||
go_imported_pkgs: set[str] = set() # local names of imported packages
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
@@ -1994,12 +2084,21 @@ def extract_go(path: Path) -> dict:
|
||||
# don't collide with local files of the same basename.
|
||||
tgt_nid = _make_id("go", "pkg", raw)
|
||||
add_edge(file_nid, tgt_nid, "imports_from", spec.start_point[0] + 1)
|
||||
# Track local name (alias or last path segment)
|
||||
alias = spec.child_by_field_name("name")
|
||||
local_name = _read_text(alias, source) if alias else raw.split("/")[-1]
|
||||
if local_name and local_name != "_" and local_name != ".":
|
||||
go_imported_pkgs.add(local_name)
|
||||
elif child.type == "import_spec":
|
||||
path_node = child.child_by_field_name("path")
|
||||
if path_node:
|
||||
raw = _read_text(path_node, source).strip('"')
|
||||
tgt_nid = _make_id("go", "pkg", raw)
|
||||
add_edge(file_nid, tgt_nid, "imports_from", child.start_point[0] + 1)
|
||||
alias = child.child_by_field_name("name")
|
||||
local_name = _read_text(alias, source) if alias else raw.split("/")[-1]
|
||||
if local_name and local_name != "_" and local_name != ".":
|
||||
go_imported_pkgs.add(local_name)
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
@@ -2022,11 +2121,17 @@ def extract_go(path: Path) -> dict:
|
||||
if node.type == "call_expression":
|
||||
func_node = node.child_by_field_name("function")
|
||||
callee_name: str | None = None
|
||||
is_member_call: bool = False
|
||||
if func_node:
|
||||
if func_node.type == "identifier":
|
||||
callee_name = _read_text(func_node, source)
|
||||
elif func_node.type == "selector_expression":
|
||||
field = func_node.child_by_field_name("field")
|
||||
operand = func_node.child_by_field_name("operand")
|
||||
receiver_name = _read_text(operand, source) if operand else ""
|
||||
# Package-qualified call (e.g. fmt.Println) → allow cross-file resolution.
|
||||
# Receiver method call (e.g. s.logger.Log) → skip, no import evidence.
|
||||
is_member_call = receiver_name not in go_imported_pkgs
|
||||
if field:
|
||||
callee_name = _read_text(field, source)
|
||||
if callee_name:
|
||||
@@ -2049,8 +2154,10 @@ def extract_go(path: Path) -> dict:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee_name,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
"callee_node_type": func_node.type if func_node is not None else None,
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
@@ -2087,7 +2194,7 @@ def extract_rust(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -2195,10 +2302,12 @@ def extract_rust(path: Path) -> dict:
|
||||
if node.type == "call_expression":
|
||||
func_node = node.child_by_field_name("function")
|
||||
callee_name: str | None = None
|
||||
is_member_call: bool = False
|
||||
if func_node:
|
||||
if func_node.type == "identifier":
|
||||
callee_name = _read_text(func_node, source)
|
||||
elif func_node.type == "field_expression":
|
||||
is_member_call = True
|
||||
field = func_node.child_by_field_name("field")
|
||||
if field:
|
||||
callee_name = _read_text(field, source)
|
||||
@@ -2226,8 +2335,10 @@ def extract_rust(path: Path) -> dict:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee_name,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
"callee_node_type": func_node.type if func_node is not None else None,
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
@@ -2264,7 +2375,7 @@ def extract_zig(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -2380,7 +2491,9 @@ def extract_zig(path: Path) -> dict:
|
||||
if node.type == "call_expression":
|
||||
fn = node.child_by_field_name("function")
|
||||
if fn:
|
||||
callee = _read_text(fn, source).split(".")[-1]
|
||||
fn_text = _read_text(fn, source)
|
||||
callee = fn_text.split(".")[-1]
|
||||
is_member_call = "." in fn_text
|
||||
tgt_nid = next((n["id"] for n in nodes if n["label"] in
|
||||
(f"{callee}()", f".{callee}()")), None)
|
||||
if tgt_nid and tgt_nid != caller_nid:
|
||||
@@ -2394,8 +2507,16 @@ def extract_zig(path: Path) -> dict:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
# Zig: callee is `_read_text(fn, source).split(".")[-1]`,
|
||||
# so a "." in the original text means it was a member call.
|
||||
"callee_node_type": (
|
||||
"_zig_dotted_callee"
|
||||
if "." in _read_text(fn, source)
|
||||
else fn.type
|
||||
),
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
@@ -2427,7 +2548,7 @@ def extract_powershell(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -2558,8 +2679,10 @@ def extract_powershell(path: Path) -> dict:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": cmd_text,
|
||||
"is_member_call": False,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
"callee_node_type": "command_name",
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
@@ -2612,8 +2735,17 @@ def _resolve_cross_file_imports(
|
||||
stem = Path(src).stem
|
||||
label = node.get("label", "")
|
||||
nid = node.get("id", "")
|
||||
# Only index real classes/functions (not file nodes, not method stubs)
|
||||
if label and not label.endswith((")", ".py")) and "_" not in label[:1]:
|
||||
# Index class-level entities only. Function/method labels end in "()"
|
||||
# so are excluded by the `endswith(")")` filter; file nodes end in ".py";
|
||||
# private/internal labels start with "_"; rationale nodes carry
|
||||
# file_type=="rationale" and must never participate in cross-file
|
||||
# import resolution (#563).
|
||||
if (
|
||||
label
|
||||
and not label.endswith((")", ".py"))
|
||||
and "_" not in label[:1]
|
||||
and node.get("file_type") != "rationale"
|
||||
):
|
||||
stem_to_entities.setdefault(stem, {})[label] = nid
|
||||
|
||||
# Pass 2: for each file, find `from .X import A, B, C` and resolve
|
||||
@@ -2621,15 +2753,18 @@ def _resolve_cross_file_imports(
|
||||
stem_to_path: dict[str, Path] = {p.stem: p for p in paths}
|
||||
|
||||
for file_result, path in zip(per_file, paths):
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
|
||||
# Find all classes defined in this file (the importers)
|
||||
# Find all classes defined in this file (the importers).
|
||||
# Excludes rationale nodes whose labels happen not to end in ")" or ".py"
|
||||
# but which must never be treated as importing entities (#563).
|
||||
local_classes = [
|
||||
n["id"] for n in file_result.get("nodes", [])
|
||||
if n.get("source_file") == str_path
|
||||
and not n["label"].endswith((")", ".py"))
|
||||
and n["id"] != _make_id(stem) # exclude file-level node
|
||||
and n.get("file_type") != "rationale"
|
||||
]
|
||||
if not local_classes:
|
||||
continue
|
||||
@@ -2745,7 +2880,7 @@ def _resolve_cross_file_java_imports(
|
||||
new_edges: list[dict] = []
|
||||
seen_pairs: set[tuple[str, str]] = set()
|
||||
for path in paths:
|
||||
file_nid = _make_id(path.stem)
|
||||
file_nid = _make_id(str(path))
|
||||
try:
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
@@ -2809,7 +2944,7 @@ def extract_objc(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -3007,7 +3142,7 @@ def extract_elixir(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -3139,8 +3274,10 @@ def extract_elixir(path: Path) -> dict:
|
||||
return
|
||||
break
|
||||
callee_name: str | None = None
|
||||
is_member_call: bool = False
|
||||
for child in node.children:
|
||||
if child.type == "dot":
|
||||
is_member_call = True
|
||||
dot_text = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
|
||||
parts = dot_text.rstrip(".").split(".")
|
||||
if parts:
|
||||
@@ -3161,8 +3298,12 @@ def extract_elixir(path: Path) -> dict:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee_name,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
# Elixir: `child` is the node we just inspected — `dot` for
|
||||
# `Mod.fn(...)`, `identifier` for a bare local call.
|
||||
"callee_node_type": child.type,
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
@@ -3345,8 +3486,13 @@ def extract(paths: list[Path], cache_root: Path | None = None) -> dict:
|
||||
# Cross-file call resolution for all languages
|
||||
# Each extractor saved unresolved calls in raw_calls. Now that we have all
|
||||
# nodes from all files, resolve any callee that exists in another file.
|
||||
# Build label -> node_id index for cross-file call resolution.
|
||||
# Skip rationale nodes (their labels are docstring text, not callable
|
||||
# identifiers, and they were polluting matches for short names — #563).
|
||||
global_label_to_nid: dict[str, str] = {}
|
||||
for n in all_nodes:
|
||||
if n.get("file_type") == "rationale":
|
||||
continue
|
||||
raw = n.get("label", "")
|
||||
normalised = raw.strip("()").lstrip(".")
|
||||
if normalised:
|
||||
@@ -3355,9 +3501,21 @@ def extract(paths: list[Path], cache_root: Path | None = None) -> dict:
|
||||
existing_pairs = {(e["source"], e["target"]) for e in all_edges}
|
||||
for result in per_file:
|
||||
for rc in result.get("raw_calls", []):
|
||||
# Member-expression callees (`x.foo()`, `obj.bar()`, `Pkg::baz()`)
|
||||
# cannot be safely resolved by bare property name across files —
|
||||
# without receiver-type analysis we routinely link them to the
|
||||
# wrong target, producing phantom god nodes (e.g. every
|
||||
# `Logger.log(...)` call collapsing onto a one-off
|
||||
# `function log(...)` defined in a smoke-test script).
|
||||
if rc.get("callee_node_type") in _MEMBER_CALL_NODE_TYPES:
|
||||
continue
|
||||
callee = rc.get("callee", "")
|
||||
if not callee:
|
||||
continue
|
||||
# Skip member-call callees: obj.log() → "log" has no import evidence
|
||||
# and collides with any top-level function named "log" in the corpus.
|
||||
if rc.get("is_member_call"):
|
||||
continue
|
||||
tgt = global_label_to_nid.get(callee.lower())
|
||||
caller = rc["caller_nid"]
|
||||
if tgt and tgt != caller and (caller, tgt) not in existing_pairs:
|
||||
@@ -3373,6 +3531,19 @@ def extract(paths: list[Path], cache_root: Path | None = None) -> dict:
|
||||
"weight": 1.0,
|
||||
})
|
||||
|
||||
# Relativize source_file fields so paths are portable across machines (#555)
|
||||
for item in all_nodes + all_edges:
|
||||
sf = item.get("source_file")
|
||||
if not sf:
|
||||
continue
|
||||
sf_path = Path(sf)
|
||||
if not sf_path.is_absolute():
|
||||
continue
|
||||
try:
|
||||
item["source_file"] = str(sf_path.relative_to(root))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return {
|
||||
"nodes": all_nodes,
|
||||
"edges": all_edges,
|
||||
|
||||
+1
-1
@@ -145,7 +145,7 @@ def _hooks_dir(root: Path) -> Path:
|
||||
if result.returncode == 0:
|
||||
custom = result.stdout.strip()
|
||||
if custom:
|
||||
p = Path(custom)
|
||||
p = Path(custom).expanduser()
|
||||
if not p.is_absolute():
|
||||
p = root / p
|
||||
p.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
# Direct LLM backend for semantic extraction — supports Claude and Kimi K2.6.
|
||||
# Used by `graphify . --backend kimi` and the benchmark scripts.
|
||||
# The default graphify pipeline uses Claude Code subagents via skill.md;
|
||||
# this module provides a direct API path for non-Claude-Code environments.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
BACKENDS: dict[str, dict] = {
|
||||
"claude": {
|
||||
"base_url": "https://api.anthropic.com",
|
||||
"default_model": "claude-sonnet-4-6",
|
||||
"env_key": "ANTHROPIC_API_KEY",
|
||||
"pricing": {"input": 3.0, "output": 15.0}, # USD per 1M tokens
|
||||
"temperature": 0,
|
||||
},
|
||||
"kimi": {
|
||||
"base_url": "https://api.moonshot.ai/v1",
|
||||
"default_model": "kimi-k2.6",
|
||||
"env_key": "MOONSHOT_API_KEY",
|
||||
"pricing": {"input": 0.74, "output": 4.66}, # USD per 1M tokens
|
||||
"temperature": None, # kimi-k2.6 enforces its own fixed temperature; sending any value raises 400
|
||||
},
|
||||
}
|
||||
|
||||
_EXTRACTION_SYSTEM = """\
|
||||
You are a graphify semantic extraction agent. Extract a knowledge graph fragment from the files provided.
|
||||
Output ONLY valid JSON — no explanation, no markdown fences, no preamble.
|
||||
|
||||
Rules:
|
||||
- EXTRACTED: relationship explicit in source (import, call, citation, reference)
|
||||
- INFERRED: reasonable inference (shared data structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain — flag for review, do not omit
|
||||
|
||||
Node ID format: lowercase, only [a-z0-9_], no dots or slashes.
|
||||
Format: {stem}_{entity} where stem = filename without extension, entity = symbol name (both normalised).
|
||||
|
||||
Output exactly this schema:
|
||||
{"nodes":[{"id":"stem_entity","label":"Human Readable Name","file_type":"code|document|paper|image|concept","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":[],"input_tokens":0,"output_tokens":0}
|
||||
"""
|
||||
|
||||
|
||||
def _read_files(paths: list[Path], root: Path) -> str:
|
||||
"""Return file contents formatted for the extraction prompt."""
|
||||
parts: list[str] = []
|
||||
for p in paths:
|
||||
try:
|
||||
rel = p.relative_to(root)
|
||||
except ValueError:
|
||||
rel = p
|
||||
try:
|
||||
content = p.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
continue
|
||||
parts.append(f"=== {rel} ===\n{content[:20000]}")
|
||||
return "\n\n".join(parts)
|
||||
|
||||
|
||||
def _parse_llm_json(raw: str) -> dict:
|
||||
"""Strip optional markdown fences and parse JSON. Returns empty fragment on failure."""
|
||||
if raw.startswith("```"):
|
||||
raw = raw.split("```", 2)[1]
|
||||
if raw.startswith("json"):
|
||||
raw = raw[4:]
|
||||
raw = raw.rsplit("```", 1)[0]
|
||||
try:
|
||||
return json.loads(raw.strip())
|
||||
except json.JSONDecodeError as exc:
|
||||
print(f"[graphify] LLM returned invalid JSON, skipping chunk: {exc}", file=sys.stderr)
|
||||
return {"nodes": [], "edges": [], "hyperedges": []}
|
||||
|
||||
|
||||
def _call_openai_compat(
|
||||
base_url: str,
|
||||
api_key: str,
|
||||
model: str,
|
||||
user_message: str,
|
||||
temperature: float | None = 0,
|
||||
) -> dict:
|
||||
"""Call any OpenAI-compatible API (Kimi, OpenAI, etc.) and return parsed JSON."""
|
||||
try:
|
||||
from openai import OpenAI
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Kimi/OpenAI-compatible extraction requires the openai package. "
|
||||
"Run: pip install openai"
|
||||
) from exc
|
||||
|
||||
client = OpenAI(api_key=api_key, base_url=base_url)
|
||||
kwargs: dict = {
|
||||
"model": model,
|
||||
"messages": [
|
||||
{"role": "system", "content": _EXTRACTION_SYSTEM},
|
||||
{"role": "user", "content": user_message},
|
||||
],
|
||||
"max_completion_tokens": 8192,
|
||||
}
|
||||
if temperature is not None:
|
||||
kwargs["temperature"] = temperature
|
||||
resp = client.chat.completions.create(**kwargs)
|
||||
result = _parse_llm_json(resp.choices[0].message.content or "{}")
|
||||
result["input_tokens"] = resp.usage.prompt_tokens if resp.usage else 0
|
||||
result["output_tokens"] = resp.usage.completion_tokens if resp.usage else 0
|
||||
result["model"] = model
|
||||
return result
|
||||
|
||||
|
||||
def _call_claude(api_key: str, model: str, user_message: str) -> dict:
|
||||
"""Call Anthropic Claude directly (not via OpenAI compat layer)."""
|
||||
try:
|
||||
import anthropic
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Claude direct extraction requires the anthropic package. "
|
||||
"Run: pip install anthropic"
|
||||
) from exc
|
||||
|
||||
client = anthropic.Anthropic(api_key=api_key)
|
||||
resp = client.messages.create(
|
||||
model=model,
|
||||
max_tokens=8192,
|
||||
system=_EXTRACTION_SYSTEM,
|
||||
messages=[{"role": "user", "content": user_message}],
|
||||
)
|
||||
result = _parse_llm_json(resp.content[0].text if resp.content else "{}")
|
||||
result["input_tokens"] = resp.usage.input_tokens if resp.usage else 0
|
||||
result["output_tokens"] = resp.usage.output_tokens if resp.usage else 0
|
||||
result["model"] = model
|
||||
return result
|
||||
|
||||
|
||||
def extract_files_direct(
|
||||
files: list[Path],
|
||||
backend: str = "kimi",
|
||||
api_key: str | None = None,
|
||||
model: str | None = None,
|
||||
root: Path = Path("."),
|
||||
) -> dict:
|
||||
"""Extract semantic nodes/edges from a list of files using the given backend.
|
||||
|
||||
Returns dict with nodes, edges, hyperedges, input_tokens, output_tokens.
|
||||
Raises ValueError for unknown backends. Raises ImportError if SDK missing.
|
||||
"""
|
||||
if backend not in BACKENDS:
|
||||
raise ValueError(f"Unknown backend {backend!r}. Available: {sorted(BACKENDS)}")
|
||||
|
||||
cfg = BACKENDS[backend]
|
||||
key = api_key or os.environ.get(cfg["env_key"], "")
|
||||
if not key:
|
||||
raise ValueError(
|
||||
f"No API key for backend '{backend}'. "
|
||||
f"Set {cfg['env_key']} or pass api_key=."
|
||||
)
|
||||
mdl = model or cfg["default_model"]
|
||||
user_msg = _read_files(files, root)
|
||||
|
||||
if backend == "claude":
|
||||
return _call_claude(key, mdl, user_msg)
|
||||
else:
|
||||
return _call_openai_compat(cfg["base_url"], key, mdl, user_msg, temperature=cfg.get("temperature", 0))
|
||||
|
||||
|
||||
def extract_corpus_parallel(
|
||||
files: list[Path],
|
||||
backend: str = "kimi",
|
||||
api_key: str | None = None,
|
||||
model: str | None = None,
|
||||
root: Path = Path("."),
|
||||
chunk_size: int = 20,
|
||||
on_chunk_done: Callable | None = None,
|
||||
) -> dict:
|
||||
"""Extract a corpus in chunks, merging results.
|
||||
|
||||
on_chunk_done(idx, total, chunk_result) is called after each chunk if provided.
|
||||
Returns merged dict with nodes, edges, hyperedges, input_tokens, output_tokens.
|
||||
"""
|
||||
chunks = [files[i:i + chunk_size] for i in range(0, len(files), chunk_size)]
|
||||
merged: dict = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
|
||||
for idx, chunk in enumerate(chunks):
|
||||
t0 = time.time()
|
||||
result = extract_files_direct(chunk, backend=backend, api_key=api_key, model=model, root=root)
|
||||
result["elapsed_seconds"] = round(time.time() - t0, 2)
|
||||
merged["nodes"].extend(result.get("nodes", []))
|
||||
merged["edges"].extend(result.get("edges", []))
|
||||
merged["hyperedges"].extend(result.get("hyperedges", []))
|
||||
merged["input_tokens"] += result.get("input_tokens", 0)
|
||||
merged["output_tokens"] += result.get("output_tokens", 0)
|
||||
if callable(on_chunk_done):
|
||||
on_chunk_done(idx, len(chunks), result)
|
||||
|
||||
return merged
|
||||
|
||||
|
||||
def estimate_cost(backend: str, input_tokens: int, output_tokens: int) -> float:
|
||||
"""Estimate USD cost for a given token count using published pricing."""
|
||||
if backend not in BACKENDS:
|
||||
return 0.0
|
||||
p = BACKENDS[backend]["pricing"]
|
||||
return (input_tokens * p["input"] + output_tokens * p["output"]) / 1_000_000
|
||||
|
||||
|
||||
def detect_backend() -> str | None:
|
||||
"""Return the name of whichever backend has an API key set, or None.
|
||||
|
||||
Kimi is checked first (opt-in). Falls back to Claude if ANTHROPIC_API_KEY is set.
|
||||
Claude is the default for the skill.md subagent pipeline and is never forced here.
|
||||
"""
|
||||
if os.environ.get("MOONSHOT_API_KEY"):
|
||||
return "kimi"
|
||||
if os.environ.get("ANTHROPIC_API_KEY"):
|
||||
return "claude"
|
||||
return None
|
||||
+37
-3
@@ -1,6 +1,7 @@
|
||||
# Security helpers - URL validation, safe fetch, path guards, label sanitisation
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import html
|
||||
import re
|
||||
import urllib.error
|
||||
@@ -58,12 +59,45 @@ def validate_url(url: str) -> str:
|
||||
f"Blocked private/internal IP {addr} (resolved from '{hostname}'). "
|
||||
f"Got: {url!r}"
|
||||
)
|
||||
except socket.gaierror:
|
||||
pass # DNS failure will surface later during fetch
|
||||
except socket.gaierror as exc:
|
||||
raise ValueError(
|
||||
f"DNS resolution failed for '{hostname}': {exc}. Got: {url!r}"
|
||||
) from exc
|
||||
|
||||
return url
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _ssrf_guarded_socket():
|
||||
"""Patch socket.getaddrinfo for the duration of a fetch to catch DNS rebinding.
|
||||
|
||||
Validates every IP that urllib resolves so a DNS server cannot return a public IP
|
||||
for validate_url and swap to a private IP for the actual connection (TOCTOU fix).
|
||||
Not thread-safe, but graphify is a single-threaded CLI tool.
|
||||
"""
|
||||
original = socket.getaddrinfo
|
||||
|
||||
def _guarded(host, port, *args, **kwargs):
|
||||
results = original(host, port, *args, **kwargs)
|
||||
for info in results:
|
||||
addr = info[4][0]
|
||||
try:
|
||||
ip = ipaddress.ip_address(addr)
|
||||
except ValueError:
|
||||
continue
|
||||
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local:
|
||||
raise OSError(
|
||||
f"SSRF blocked: IP {addr} resolved from '{host}' is private/reserved"
|
||||
)
|
||||
return results
|
||||
|
||||
socket.getaddrinfo = _guarded
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
socket.getaddrinfo = original
|
||||
|
||||
|
||||
class _NoFileRedirectHandler(urllib.request.HTTPRedirectHandler):
|
||||
"""Redirect handler that re-validates every redirect target.
|
||||
|
||||
@@ -104,7 +138,7 @@ def safe_fetch(url: str, max_bytes: int = _MAX_FETCH_BYTES, timeout: int = 30) -
|
||||
opener = _build_opener()
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 graphify/1.0"})
|
||||
|
||||
with opener.open(req, timeout=timeout) as resp:
|
||||
with _ssrf_guarded_socket(), opener.open(req, timeout=timeout) as resp:
|
||||
# urllib raises HTTPError for non-2xx when using urlopen directly;
|
||||
# with a custom opener we check manually to be safe.
|
||||
status = getattr(resp, "status", None) or getattr(resp, "code", None)
|
||||
|
||||
@@ -235,12 +235,12 @@ Process each file one at a time. For each file:
|
||||
- INFERRED: reasonable inference (shared structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain — flag it, do not omit
|
||||
- Code files: semantic edges AST cannot find. Do not re-extract imports.
|
||||
- Doc/paper files: named concepts, entities, citations, and rationale nodes (WHY decisions were made → `rationale_for` edges)
|
||||
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. When adding `calls` edges: source is caller, target is callee.
|
||||
- Image files: use vision — understand what the image IS, not just OCR
|
||||
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
|
||||
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
|
||||
- Hyperedges: if 3+ nodes share a concept/flow not captured by pairwise edges, add a hyperedge. Max 3 per file.
|
||||
- confidence_score REQUIRED on every edge: EXTRACTED=1.0, INFERRED=0.6-0.9 (reason individually), AMBIGUOUS=0.1-0.3
|
||||
- confidence_score REQUIRED on every edge: EXTRACTED=1.0; INFERRED ∈ {0.55, 0.65, 0.75, 0.85, 0.95} forced-rank (NEVER 0.5 — pick the closest discrete value or mark AMBIGUOUS); AMBIGUOUS=0.1-0.3
|
||||
3. Accumulate results across all files
|
||||
|
||||
Schema for each file's output:
|
||||
|
||||
@@ -235,12 +235,12 @@ Process each file one at a time. For each file:
|
||||
- INFERRED: reasonable inference (shared structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain — flag it, do not omit
|
||||
- Code files: semantic edges AST cannot find. Do not re-extract imports.
|
||||
- Doc/paper files: named concepts, entities, citations, and rationale nodes (WHY decisions were made → `rationale_for` edges)
|
||||
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. When adding `calls` edges: source is caller, target is callee.
|
||||
- Image files: use vision — understand what the image IS, not just OCR
|
||||
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
|
||||
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
|
||||
- Hyperedges: if 3+ nodes share a concept/flow not captured by pairwise edges, add a hyperedge. Max 3 per file.
|
||||
- confidence_score REQUIRED on every edge: EXTRACTED=1.0, INFERRED=0.6-0.9 (reason individually), AMBIGUOUS=0.1-0.3
|
||||
- confidence_score REQUIRED on every edge: EXTRACTED=1.0; INFERRED ∈ {0.55, 0.65, 0.75, 0.85, 0.95} forced-rank (NEVER 0.5 — pick the closest discrete value or mark AMBIGUOUS); AMBIGUOUS=0.1-0.3
|
||||
3. Accumulate results across all files
|
||||
|
||||
Schema for each file's output:
|
||||
|
||||
+12
-5
@@ -263,7 +263,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
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.
|
||||
@@ -292,10 +293,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
|
||||
@@ -259,7 +259,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
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.
|
||||
@@ -288,10 +289,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
@@ -818,11 +825,22 @@ deleted = set(incremental.get('deleted_files', []))
|
||||
if deleted:
|
||||
to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted]
|
||||
G_existing.remove_nodes_from(to_remove)
|
||||
print(f'Pruned {len(to_remove)} ghost nodes from {len(deleted)} deleted file(s)')
|
||||
if to_remove:
|
||||
print(f'Pruned {len(to_remove)} ghost node(s) from {len(deleted)} deleted file(s) — drift detected and corrected.')
|
||||
else:
|
||||
print(f'{len(deleted)} file(s) deleted since last run, but no ghost nodes were present in the graph — no drift.')
|
||||
|
||||
# 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 with the CURRENT full file list so the next --update
|
||||
# diffs against today's filesystem state, not the prior --update's
|
||||
# baseline. Without this, deleted files get reported as ghosts again
|
||||
# on every subsequent --update until a full rebuild runs.
|
||||
from graphify.detect import save_manifest
|
||||
save_manifest(incremental['files'])
|
||||
print('[graphify update] Manifest saved.')
|
||||
"
|
||||
```
|
||||
|
||||
|
||||
+12
-5
@@ -260,7 +260,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
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.
|
||||
@@ -289,10 +290,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
|
||||
@@ -234,12 +234,12 @@ Process each file one at a time. For each file:
|
||||
- INFERRED: reasonable inference (shared structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain — flag it, do not omit
|
||||
- Code files: semantic edges AST cannot find. Do not re-extract imports.
|
||||
- Doc/paper files: named concepts, entities, citations, and rationale nodes (WHY decisions were made → `rationale_for` edges)
|
||||
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. When adding `calls` edges: source is caller, target is callee.
|
||||
- Image files: use vision — understand what the image IS, not just OCR
|
||||
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
|
||||
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
|
||||
- Hyperedges: if 3+ nodes share a concept/flow not captured by pairwise edges, add a hyperedge. Max 3 per file.
|
||||
- confidence_score REQUIRED on every edge: EXTRACTED=1.0, INFERRED=0.6-0.9 (reason individually), AMBIGUOUS=0.1-0.3
|
||||
- confidence_score REQUIRED on every edge: EXTRACTED=1.0; INFERRED ∈ {0.55, 0.65, 0.75, 0.85, 0.95} forced-rank (NEVER 0.5 — pick the closest discrete value or mark AMBIGUOUS); AMBIGUOUS=0.1-0.3
|
||||
3. Accumulate results across all files
|
||||
|
||||
Schema for each file's output:
|
||||
|
||||
@@ -261,7 +261,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
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.
|
||||
@@ -290,10 +291,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
|
||||
+12
-5
@@ -250,7 +250,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
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.
|
||||
@@ -279,10 +280,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
|
||||
@@ -249,7 +249,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
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.
|
||||
@@ -278,10 +279,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
|
||||
+62
-9
@@ -13,6 +13,9 @@ 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 https://github.com/<owner>/<repo> # clone repo then run full pipeline on it
|
||||
/graphify https://github.com/<owner>/<repo> --branch <branch> # clone a specific branch
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
@@ -57,8 +60,33 @@ Use it for:
|
||||
|
||||
If no path was given, use `.` (current directory). Do not ask the user for a path.
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL — run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
|
||||
### Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given)
|
||||
|
||||
**Single repo:**
|
||||
```bash
|
||||
LOCAL_PATH=$(graphify clone <github-url> [--branch <branch>])
|
||||
# Use LOCAL_PATH as the target for all subsequent steps
|
||||
```
|
||||
|
||||
**Multiple repos (cross-repo graph):**
|
||||
```bash
|
||||
# Clone each repo, run the full pipeline on each, then merge
|
||||
graphify clone <url1> # → ~/.graphify/repos/<owner1>/<repo1>
|
||||
graphify clone <url2> # → ~/.graphify/repos/<owner2>/<repo2>
|
||||
# Run /graphify on each local path to produce their graph.json files
|
||||
# Then merge:
|
||||
graphify merge-graphs \
|
||||
~/.graphify/repos/<owner1>/<repo1>/graphify-out/graph.json \
|
||||
~/.graphify/repos/<owner2>/<repo2>/graphify-out/graph.json \
|
||||
--out graphify-out/cross-repo-graph.json
|
||||
```
|
||||
|
||||
Graphify clones into `~/.graphify/repos/<owner>/<repo>` and reuses existing clones on repeat runs. Each node in the merged graph carries a `repo` attribute so you can filter by origin.
|
||||
|
||||
### Step 1 - Ensure graphify is installed
|
||||
|
||||
```bash
|
||||
@@ -84,6 +112,8 @@ if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
|
||||
# Write interpreter path for all subsequent steps (persists across invocations)
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
# Save scan root so `graphify update` (no args) knows where to look next time
|
||||
echo "$(cd INPUT_PATH && pwd)" > graphify-out/.graphify_root
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
@@ -170,7 +200,12 @@ After transcription:
|
||||
|
||||
**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) and **semantic extraction** (Claude, costs tokens).
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens).
|
||||
|
||||
**Before dispatching subagents:** check whether `MOONSHOT_API_KEY` is set. If it is NOT set, print this one-liner to the user:
|
||||
> Tip: set `MOONSHOT_API_KEY` to use Kimi K2.6 for semantic extraction — 3x cheaper, richer graphs (`pip install 'graphifyy[kimi]'`).
|
||||
|
||||
Print it once, then continue. If `MOONSHOT_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="kimi")` for semantic extraction instead of dispatching Claude subagents.
|
||||
|
||||
**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.**
|
||||
|
||||
@@ -272,7 +307,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
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.
|
||||
@@ -301,13 +337,19 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the filename without extension and entity is the symbol name, both normalized (lowercase, non-alphanumeric chars replaced with `_`). Example: `src/auth/session.py` + `ValidateToken` → `session_validatetoken`. This must match the ID the AST extractor generates so cross-references between code and semantic nodes connect correctly.
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the filename without extension and entity is the symbol name, both normalized (lowercase, non-alphanumeric chars replaced with `_`). Example: `src/auth/session.py` + `ValidateToken` → `session_validatetoken`. This must match the ID the AST extractor generates so cross-references between code and semantic nodes connect correctly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
@@ -768,7 +810,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
|
||||
"
|
||||
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_labels.json graphify-out/.graphify_chunk_*.json
|
||||
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -887,7 +929,10 @@ deleted = set(incremental.get('deleted_files', []))
|
||||
if deleted:
|
||||
to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted]
|
||||
G_existing.remove_nodes_from(to_remove)
|
||||
print(f'Pruned {len(to_remove)} ghost nodes from {len(deleted)} deleted file(s)')
|
||||
if to_remove:
|
||||
print(f'Pruned {len(to_remove)} ghost node(s) from {len(deleted)} deleted file(s) — drift detected and corrected.')
|
||||
else:
|
||||
print(f'{len(deleted)} file(s) deleted since last run, but no ghost nodes were present in the graph — no drift.')
|
||||
|
||||
# Merge: new nodes/edges into existing graph
|
||||
G_existing.update(G_new)
|
||||
@@ -903,6 +948,14 @@ merged_out = {
|
||||
}
|
||||
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out))
|
||||
print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)')
|
||||
|
||||
# Save manifest with the CURRENT full file list so the next --update
|
||||
# diffs against today's filesystem state, not the prior --update's
|
||||
# baseline. Without this, deleted files get reported as ghosts again
|
||||
# on every subsequent --update until a full rebuild runs.
|
||||
from graphify.detect import save_manifest
|
||||
save_manifest(incremental['files'])
|
||||
print('[graphify update] Manifest saved.')
|
||||
"
|
||||
```
|
||||
|
||||
|
||||
@@ -51,6 +51,8 @@ def download_audio(url: str, output_dir: Path) -> Path:
|
||||
Returns the path to the downloaded audio file (.m4a or .opus).
|
||||
Uses cached file if already downloaded.
|
||||
"""
|
||||
from graphify.security import validate_url
|
||||
validate_url(url) # blocks private IPs, bad schemes before yt-dlp runs
|
||||
yt_dlp = _get_yt_dlp()
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# validate extraction JSON against the graphify schema before graph assembly
|
||||
from __future__ import annotations
|
||||
|
||||
VALID_FILE_TYPES = {"code", "document", "paper", "image", "rationale"}
|
||||
VALID_FILE_TYPES = {"code", "document", "paper", "image", "rationale", "concept"}
|
||||
VALID_CONFIDENCES = {"EXTRACTED", "INFERRED", "AMBIGUOUS"}
|
||||
REQUIRED_NODE_FIELDS = {"id", "label", "file_type", "source_file"}
|
||||
REQUIRED_EDGE_FIELDS = {"source", "target", "relation", "confidence", "source_file"}
|
||||
|
||||
+5
-1
@@ -98,11 +98,15 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
out.mkdir(exist_ok=True)
|
||||
(out / ".graphify_root").write_text(str(watch_root), encoding="utf-8")
|
||||
|
||||
json_written = to_json(G, communities, str(out / "graph.json"))
|
||||
if not json_written:
|
||||
return False
|
||||
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection,
|
||||
{"input": 0, "output": 0}, report_root, suggested_questions=questions)
|
||||
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
|
||||
to_json(G, communities, str(out / "graph.json"))
|
||||
|
||||
# to_html raises ValueError for graphs > MAX_NODES_FOR_VIZ (5000).
|
||||
# Wrap so core outputs (graph.json + GRAPH_REPORT.md) always land.
|
||||
|
||||
+21
-1
@@ -7,7 +7,18 @@ import networkx as nx
|
||||
|
||||
|
||||
def _safe_filename(name: str) -> str:
|
||||
return name.replace("/", "-").replace(" ", "_").replace(":", "-")
|
||||
"""Make a label safe for use as a filename across platforms.
|
||||
|
||||
Substitutes characters that Windows reserves in filenames
|
||||
(< > : " / \\ | ? *) and strips trailing dots/spaces, also reserved.
|
||||
Falls back to 'unnamed' for empty results and caps length at 200
|
||||
chars to stay well under common filesystem limits.
|
||||
"""
|
||||
import re
|
||||
s = name.replace("/", "-").replace(" ", "_").replace(":", "-")
|
||||
s = re.sub(r'[<>:"/\\|?*]', '_', s)
|
||||
s = s.strip('. ')
|
||||
return s[:200] if s else 'unnamed'
|
||||
|
||||
|
||||
def _cross_community_links(G: nx.Graph, nodes: list[str], own_cid: int, labels: dict[int, str]) -> list[tuple[str, int]]:
|
||||
@@ -185,6 +196,15 @@ def to_wiki(
|
||||
out = Path(output_dir)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Clear stale .md files from previous runs to prevent orphan accumulation.
|
||||
# Community labels are LLM-generated (per skill.md Step 5) and non-deterministic
|
||||
# across runs — the same conceptual community may be named differently each time
|
||||
# (e.g. "AutoAgent Skills" → "AutoAgent Methodology"), leaving the previous file
|
||||
# as an orphan. Since to_wiki() owns wiki/ entirely (always writes the full set),
|
||||
# it can safely clear .md files at the start of each call.
|
||||
for old_article in out.glob("*.md"):
|
||||
old_article.unlink()
|
||||
|
||||
labels = community_labels or {cid: f"Community {cid}" for cid in communities}
|
||||
cohesion = cohesion or {}
|
||||
god_nodes_data = god_nodes_data or []
|
||||
|
||||
+5
-3
@@ -4,12 +4,12 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "graphifyy"
|
||||
version = "0.4.31"
|
||||
version = "0.5.7"
|
||||
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
|
||||
readme = "README.md"
|
||||
license = { file = "LICENSE" }
|
||||
keywords = ["claude", "claude-code", "codex", "opencode", "cursor", "gemini", "aider", "kiro", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
|
||||
requires-python = ">=3.10,<3.14"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"networkx",
|
||||
"tree-sitter>=0.23.0",
|
||||
@@ -50,7 +50,9 @@ svg = ["matplotlib"]
|
||||
leiden = ["graspologic; python_version < '3.13'"]
|
||||
office = ["python-docx", "openpyxl"]
|
||||
video = ["faster-whisper", "yt-dlp"]
|
||||
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper", "yt-dlp", "matplotlib"]
|
||||
kimi = ["openai"]
|
||||
test = ["pytest>=7", "pytest-cov"]
|
||||
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper", "yt-dlp", "matplotlib", "openai"]
|
||||
|
||||
[project.scripts]
|
||||
graphify = "graphify.__main__:main"
|
||||
|
||||
+5
-3
@@ -67,11 +67,13 @@ def test_cached_files(tmp_path, cache_root):
|
||||
|
||||
|
||||
def test_clear_cache(tmp_file, cache_root):
|
||||
"""clear_cache removes all .json files from graphify-out/cache/."""
|
||||
"""clear_cache removes all .json files from graphify-out/cache/ (all subdirs)."""
|
||||
save_cached(tmp_file, {"nodes": [], "edges": []}, root=cache_root)
|
||||
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) > 0
|
||||
# Since v0.5.3 entries go into cache/ast/, not the flat cache/ dir
|
||||
cache_base = cache_root / "graphify-out" / "cache"
|
||||
assert len(list(cache_base.rglob("*.json"))) > 0
|
||||
clear_cache(cache_root)
|
||||
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) == 0
|
||||
assert len(list(cache_base.rglob("*.json"))) == 0
|
||||
|
||||
|
||||
def test_md_frontmatter_only_change_same_hash(tmp_path):
|
||||
|
||||
@@ -109,7 +109,7 @@ def test_install_creates_settings_json(tmp_path):
|
||||
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)
|
||||
assert any(h.get("matcher") == "Bash" for h in hooks)
|
||||
|
||||
|
||||
def test_install_settings_json_idempotent(tmp_path):
|
||||
@@ -120,8 +120,8 @@ def test_install_settings_json_idempotent(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
|
||||
bash_hooks = [h for h in hooks if h.get("matcher") == "Bash" and "graphify" in str(h)]
|
||||
assert len(bash_hooks) == 1
|
||||
|
||||
|
||||
def test_uninstall_removes_settings_hook(tmp_path):
|
||||
@@ -133,4 +133,4 @@ def test_uninstall_removes_settings_hook(tmp_path):
|
||||
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)
|
||||
assert not any(h.get("matcher") == "Bash" and "graphify" in str(h) for h in hooks)
|
||||
@@ -104,6 +104,42 @@ def test_graphifyignore_missing_is_fine(tmp_path):
|
||||
assert result["graphifyignore_patterns"] == 0
|
||||
|
||||
|
||||
def test_graphifyinclude_allows_curated_files_inside_hidden_dirs(tmp_path):
|
||||
"""A .graphifyinclude allowlist can opt curated hidden markdown paths into detect()."""
|
||||
(tmp_path / ".graphifyinclude").write_text(".hermes/plans/**/*.md\n")
|
||||
plans = tmp_path / ".hermes" / "plans"
|
||||
plans.mkdir(parents=True)
|
||||
(plans / "knowledge-plan.md").write_text("# Knowledge Plan\nThis is the searchable plan.")
|
||||
context = tmp_path / ".hermes" / "context"
|
||||
context.mkdir(parents=True)
|
||||
(context / "scratch.md").write_text("# Scratch\nThis should stay out.")
|
||||
(tmp_path / "README.md").write_text("# Visible\nVisible docs still work.")
|
||||
|
||||
result = detect(tmp_path)
|
||||
docs = result["files"]["document"]
|
||||
|
||||
assert any(".hermes/plans/knowledge-plan.md" in f for f in docs)
|
||||
assert not any(".hermes/context/scratch.md" in f for f in docs)
|
||||
assert any("README.md" in f for f in docs)
|
||||
assert result["graphifyinclude_patterns"] == 1
|
||||
|
||||
|
||||
def test_graphifyinclude_does_not_override_sensitive_file_skips(tmp_path):
|
||||
"""Even allowlisted hidden paths must not index secret-looking files."""
|
||||
(tmp_path / ".graphifyinclude").write_text(".hermes/plans/**/*.md\n")
|
||||
plans = tmp_path / ".hermes" / "plans"
|
||||
plans.mkdir(parents=True)
|
||||
(plans / "api_token.md").write_text("token: should not be indexed")
|
||||
(plans / "public-plan.md").write_text("# Public Plan\nSafe searchable material.")
|
||||
|
||||
result = detect(tmp_path)
|
||||
docs = result["files"]["document"]
|
||||
|
||||
assert any(".hermes/plans/public-plan.md" in f for f in docs)
|
||||
assert not any("api_token.md" in f for f in docs)
|
||||
assert len(result["skipped_sensitive"]) == 1
|
||||
|
||||
|
||||
def test_graphifyignore_comments_ignored(tmp_path):
|
||||
"""Comment lines in .graphifyignore are not treated as patterns."""
|
||||
(tmp_path / ".graphifyignore").write_text("# this is a comment\n\nmain.py\n")
|
||||
|
||||
+67
-1
@@ -1,9 +1,19 @@
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import pytest
|
||||
from pathlib import Path
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster
|
||||
from graphify.export import to_json, to_cypher, to_graphml, to_html, to_canvas
|
||||
from graphify.export import (
|
||||
to_json,
|
||||
to_cypher,
|
||||
to_graphml,
|
||||
to_html,
|
||||
to_canvas,
|
||||
_viz_node_limit,
|
||||
MAX_NODES_FOR_VIZ,
|
||||
)
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
@@ -127,6 +137,62 @@ def test_to_html_contains_nodes_and_edges():
|
||||
assert "RAW_EDGES" in content
|
||||
|
||||
|
||||
# --- GRAPHIFY_VIZ_NODE_LIMIT env var --------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def restore_viz_env(monkeypatch):
|
||||
"""Ensure each test runs without GRAPHIFY_VIZ_NODE_LIMIT bleeding across cases."""
|
||||
monkeypatch.delenv("GRAPHIFY_VIZ_NODE_LIMIT", raising=False)
|
||||
yield
|
||||
|
||||
|
||||
def test_viz_node_limit_default(restore_viz_env):
|
||||
assert _viz_node_limit() == MAX_NODES_FOR_VIZ
|
||||
|
||||
|
||||
def test_viz_node_limit_env_override_higher(restore_viz_env, monkeypatch):
|
||||
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "20000")
|
||||
assert _viz_node_limit() == 20000
|
||||
|
||||
|
||||
def test_viz_node_limit_env_override_zero_disables(restore_viz_env, monkeypatch):
|
||||
"""Setting to 0 lets users disable HTML viz unconditionally (CI runners)."""
|
||||
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "0")
|
||||
assert _viz_node_limit() == 0
|
||||
|
||||
|
||||
def test_viz_node_limit_invalid_falls_back_to_default(restore_viz_env, monkeypatch):
|
||||
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "not-an-int")
|
||||
assert _viz_node_limit() == MAX_NODES_FOR_VIZ
|
||||
|
||||
|
||||
def test_viz_node_limit_empty_falls_back_to_default(restore_viz_env, monkeypatch):
|
||||
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", " ")
|
||||
assert _viz_node_limit() == MAX_NODES_FOR_VIZ
|
||||
|
||||
|
||||
def test_to_html_raises_with_lowered_limit(restore_viz_env, monkeypatch):
|
||||
"""Lowering the limit below the test graph's size triggers ValueError."""
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "1")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.html"
|
||||
with pytest.raises(ValueError, match="too large for HTML viz"):
|
||||
to_html(G, communities, str(out))
|
||||
|
||||
|
||||
def test_to_html_writes_with_raised_limit(restore_viz_env, monkeypatch):
|
||||
"""Raising the limit above the graph's size lets to_html proceed normally."""
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "100000")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.html"
|
||||
to_html(G, communities, str(out))
|
||||
assert out.exists()
|
||||
|
||||
|
||||
def test_to_html_member_counts_accepted():
|
||||
"""to_html accepts member_counts without raising."""
|
||||
G = make_graph()
|
||||
|
||||
@@ -123,3 +123,30 @@ def test_hook_skips_head_on_exe():
|
||||
"""Hook script must skip shebang extraction for .exe binaries (Windows)."""
|
||||
from graphify.hooks import _PYTHON_DETECT
|
||||
assert "*.exe) _SHEBANG=" in _PYTHON_DETECT or '*.exe)' in _PYTHON_DETECT
|
||||
|
||||
|
||||
def test_hooks_dir_expands_tilde(tmp_path, monkeypatch):
|
||||
"""_hooks_dir must call expanduser() so ~/... paths in core.hooksPath resolve correctly."""
|
||||
from graphify.hooks import _hooks_dir
|
||||
import types
|
||||
|
||||
repo = _make_git_repo(tmp_path)
|
||||
custom_hooks = tmp_path / "custom_hooks"
|
||||
custom_hooks.mkdir()
|
||||
|
||||
# expanduser() reads $HOME, so override it to make ~/custom_hooks predictable
|
||||
monkeypatch.setenv("HOME", str(tmp_path))
|
||||
|
||||
real_run = subprocess.run
|
||||
|
||||
def fake_run(cmd, **kwargs):
|
||||
if isinstance(cmd, list) and "config" in cmd and "core.hooksPath" in cmd:
|
||||
return types.SimpleNamespace(returncode=0, stdout="~/custom_hooks")
|
||||
return real_run(cmd, **kwargs)
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", fake_run)
|
||||
|
||||
resolved = _hooks_dir(repo)
|
||||
assert resolved == custom_hooks, (
|
||||
f"expected {custom_hooks}, got {resolved} — tilde was not expanded"
|
||||
)
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Tests for graphify install --platform routing."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
import pytest
|
||||
@@ -129,6 +130,69 @@ def test_codex_agents_install_writes_agents_md(tmp_path):
|
||||
assert "GRAPH_REPORT.md" in agents_md.read_text()
|
||||
|
||||
|
||||
def test_codex_agents_install_writes_user_prompt_submit_hook(tmp_path):
|
||||
_agents_install(tmp_path, "codex")
|
||||
|
||||
hooks_path = tmp_path / ".codex" / "hooks.json"
|
||||
hooks = json.loads(hooks_path.read_text())
|
||||
command = hooks["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"]
|
||||
|
||||
assert "UserPromptSubmit" in hooks["hooks"]
|
||||
assert "PreToolUse" not in hooks["hooks"]
|
||||
assert "UserPromptSubmit" in command
|
||||
assert "additionalContext" in command
|
||||
assert "graphify-out/GRAPH_REPORT.md" in command
|
||||
|
||||
|
||||
def test_codex_agents_install_removes_only_graphify_generated_hooks(tmp_path):
|
||||
from graphify.__main__ import _LEGACY_CODEX_PRE_TOOL_HOOK
|
||||
|
||||
unrelated_hook = {
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "echo graphify for my own plugin",
|
||||
}
|
||||
],
|
||||
}
|
||||
hooks_path = tmp_path / ".codex" / "hooks.json"
|
||||
hooks_path.parent.mkdir(parents=True)
|
||||
hooks_path.write_text(json.dumps({
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
_LEGACY_CODEX_PRE_TOOL_HOOK,
|
||||
unrelated_hook,
|
||||
]
|
||||
}
|
||||
}))
|
||||
|
||||
_agents_install(tmp_path, "codex")
|
||||
|
||||
hooks = json.loads(hooks_path.read_text())
|
||||
pre_tool = hooks["hooks"].get("PreToolUse", [])
|
||||
user_prompt = hooks["hooks"].get("UserPromptSubmit", [])
|
||||
|
||||
assert pre_tool == [unrelated_hook]
|
||||
assert len(user_prompt) == 1
|
||||
assert "graphify-out/GRAPH_REPORT.md" in user_prompt[0]["hooks"][0]["command"]
|
||||
|
||||
|
||||
def test_codex_agents_install_preserves_non_object_hooks_value(tmp_path):
|
||||
hooks_path = tmp_path / ".codex" / "hooks.json"
|
||||
hooks_path.parent.mkdir(parents=True)
|
||||
hooks_path.write_text(json.dumps({
|
||||
"hooks": ["recoverable user config"],
|
||||
"other": {"keep": True},
|
||||
}))
|
||||
|
||||
_agents_install(tmp_path, "codex")
|
||||
|
||||
hooks = json.loads(hooks_path.read_text())
|
||||
assert hooks["hooks"] == ["recoverable user config"]
|
||||
assert hooks["other"] == {"keep": True}
|
||||
|
||||
|
||||
def test_opencode_agents_install_writes_agents_md(tmp_path):
|
||||
_agents_install(tmp_path, "opencode")
|
||||
assert (tmp_path / "AGENTS.md").exists()
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
"""Regression tests for issue #563.
|
||||
|
||||
Two extractor bugs were inflating god-node centrality:
|
||||
|
||||
1. `_resolve_cross_file_imports` accepted rationale nodes as "importing
|
||||
classes", causing a phantom `<file>_rationale_N --uses--> ImportedThing`
|
||||
edge for every imported entity in every file with docstrings. Cross-file
|
||||
call resolution had the same leak via `global_label_to_nid`.
|
||||
|
||||
2. The `to_json` exporter serialized a NetworkX undirected graph and lost
|
||||
edge direction; `_src` / `_tgt` were stashed by `build` precisely to
|
||||
restore direction at export time, but were not consulted.
|
||||
|
||||
Both bugs are observable in the AST-only path (no LLM required).
|
||||
|
||||
Note: the fixture uses module name ``jobq`` rather than ``queue`` to avoid
|
||||
colliding with the Python stdlib ``queue`` module that graphify's update
|
||||
path imports.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def _write_repro(root: Path) -> None:
|
||||
(root / "jobq.py").write_text(textwrap.dedent('''
|
||||
"""Job-queue module — provides SQLiteQueue for idempotent job tracking."""
|
||||
|
||||
|
||||
class SQLiteQueue:
|
||||
"""Lightweight SQLite-backed queue.
|
||||
|
||||
Used by middleware routers and CLI commands to enqueue work and
|
||||
deduplicate via idempotency keys.
|
||||
"""
|
||||
|
||||
def check_idempotency(self, key):
|
||||
"""Return existing lead for key, or None."""
|
||||
return None
|
||||
|
||||
def enqueue(self, payload):
|
||||
"""Persist payload to the queue."""
|
||||
return True
|
||||
''').lstrip())
|
||||
|
||||
(root / "contact_form.py").write_text(textwrap.dedent('''
|
||||
"""HTTP router for the contact form endpoint."""
|
||||
from jobq import SQLiteQueue
|
||||
|
||||
q = SQLiteQueue()
|
||||
|
||||
|
||||
def contact_form(payload_obj):
|
||||
"""Handle a contact form submission.
|
||||
|
||||
Idempotency is keyed on payload_obj.idempotency_key.
|
||||
"""
|
||||
existing_lead = q.check_idempotency(payload_obj.idempotency_key)
|
||||
if existing_lead:
|
||||
return existing_lead
|
||||
q.enqueue(payload_obj)
|
||||
return {"ok": True}
|
||||
''').lstrip())
|
||||
|
||||
(root / "test_customer_dedup.py").write_text(textwrap.dedent('''
|
||||
"""Tests for customer dedup — exercises phone normalization and Odoo tagging."""
|
||||
from jobq import SQLiteQueue
|
||||
from contact_form import contact_form
|
||||
|
||||
|
||||
def test_us_phone_no_country_code():
|
||||
"""US phone without country code uses default region US -> +1 prefix."""
|
||||
assert True
|
||||
|
||||
|
||||
def test_uk_phone_with_prefix():
|
||||
"""UK phone with +44 prefix parses regardless of default region."""
|
||||
assert True
|
||||
|
||||
|
||||
def test_invalid_phone_returns_none():
|
||||
"""Phone that parses but isn't a valid number -> None."""
|
||||
assert True
|
||||
|
||||
|
||||
def test_odoo_tag_missing_still_chatter():
|
||||
"""If the tag isn't seeded, still post the chatter note."""
|
||||
queue = SQLiteQueue()
|
||||
queue.enqueue({})
|
||||
contact_form(None)
|
||||
''').lstrip())
|
||||
|
||||
|
||||
def _run_graphify_update(root: Path) -> dict:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "graphify", "update", str(root)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
cwd=str(root),
|
||||
)
|
||||
assert result.returncode == 0, (
|
||||
f"graphify update failed: {result.stderr}\nstdout: {result.stdout}"
|
||||
)
|
||||
graph_path = root / "graphify-out" / "graph.json"
|
||||
assert graph_path.exists(), f"graph.json not produced. stderr: {result.stderr}"
|
||||
return json.loads(graph_path.read_text())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repro_graph(tmp_path: Path) -> dict:
|
||||
_write_repro(tmp_path)
|
||||
return _run_graphify_update(tmp_path)
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Bug 1: rationale node leakage into cross-file resolvers
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _file_type_map(graph: dict) -> dict[str, str]:
|
||||
"""Map node id -> file_type from the serialized graph.
|
||||
|
||||
Identifying rationale nodes via node metadata (file_type == "rationale")
|
||||
is more durable than substring-matching on the id, which couples to the
|
||||
current `<stem>_rationale_<line>` naming scheme.
|
||||
"""
|
||||
return {n["id"]: n.get("file_type", "") for n in graph["nodes"]}
|
||||
|
||||
|
||||
def test_no_rationale_nodes_in_uses_or_calls_edges(repro_graph):
|
||||
"""Rationale nodes describe code; they cannot `use`, `call`, or `reference`
|
||||
anything. The only relation a rationale node may participate in is
|
||||
`rationale_for` (extractor emits `rationale --rationale_for--> parent`)."""
|
||||
ftype = _file_type_map(repro_graph)
|
||||
bad = [
|
||||
e for e in repro_graph["links"]
|
||||
if (ftype.get(e["source"]) == "rationale"
|
||||
or ftype.get(e["target"]) == "rationale")
|
||||
and e["relation"] != "rationale_for"
|
||||
]
|
||||
assert bad == [], (
|
||||
f"Rationale nodes must only appear in rationale_for edges. "
|
||||
f"Found {len(bad)} bad edges with relations "
|
||||
f"{sorted({e['relation'] for e in bad})}: {bad[:3]}"
|
||||
)
|
||||
|
||||
|
||||
def test_rationale_for_direction_is_rationale_to_parent(repro_graph):
|
||||
"""Rationale_for edges encode "this docstring fragment is the rationale
|
||||
for this code entity": source is the rationale node, target is the parent.
|
||||
The export-side direction restore (#563) was the only thing that made
|
||||
this hold under undirected NetworkX storage."""
|
||||
ftype = _file_type_map(repro_graph)
|
||||
rats = [e for e in repro_graph["links"] if e["relation"] == "rationale_for"]
|
||||
assert rats, "expected some rationale_for edges in the repro"
|
||||
bad = [e for e in rats if ftype.get(e["source"]) != "rationale"]
|
||||
assert bad == [], (
|
||||
f"rationale_for edges must have a rationale node as source. "
|
||||
f"Found {len(bad)} flipped: {bad[:3]}"
|
||||
)
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Bug 2: `calls` direction must be caller -> callee
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _calls(graph: dict) -> list[tuple[str, str]]:
|
||||
return [
|
||||
(e["source"], e["target"])
|
||||
for e in graph["links"]
|
||||
if e.get("relation") == "calls"
|
||||
]
|
||||
|
||||
|
||||
def test_calls_direction_is_caller_to_callee(repro_graph):
|
||||
"""The exact directions reported as inverted in #563 must hold."""
|
||||
calls = _calls(repro_graph)
|
||||
|
||||
# contact_form() calls SQLiteQueue.check_idempotency() and SQLiteQueue.enqueue()
|
||||
assert (
|
||||
"contact_form_contact_form",
|
||||
"jobq_sqlitequeue_check_idempotency",
|
||||
) in calls, f"expected caller->callee edge missing. got: {calls}"
|
||||
assert (
|
||||
"contact_form_contact_form",
|
||||
"jobq_sqlitequeue_enqueue",
|
||||
) in calls, f"contact_form->enqueue edge missing. got: {calls}"
|
||||
|
||||
# The test function calls contact_form()
|
||||
assert (
|
||||
"test_customer_dedup_test_odoo_tag_missing_still_chatter",
|
||||
"contact_form_contact_form",
|
||||
) in calls, f"test->contact_form edge missing. got: {calls}"
|
||||
|
||||
# And critically, none of the inversions exist:
|
||||
inversions = {
|
||||
("jobq_sqlitequeue_check_idempotency", "contact_form_contact_form"),
|
||||
("jobq_sqlitequeue_enqueue", "contact_form_contact_form"),
|
||||
("contact_form_contact_form",
|
||||
"test_customer_dedup_test_odoo_tag_missing_still_chatter"),
|
||||
}
|
||||
leaked = set(calls) & inversions
|
||||
assert not leaked, f"Found inverted calls edges: {leaked}"
|
||||
|
||||
|
||||
def test_calls_direction_on_existing_sample_calls_fixture():
|
||||
"""Pin the direction on the in-tree fixture too — adds direction
|
||||
coverage to the existing AST extractor tests."""
|
||||
from graphify.extract import extract_python
|
||||
|
||||
fixture = REPO_ROOT / "tests" / "fixtures" / "sample_calls.py"
|
||||
result = extract_python(fixture)
|
||||
|
||||
calls = [
|
||||
(e["source"], e["target"])
|
||||
for e in result["edges"]
|
||||
if e.get("relation") == "calls"
|
||||
]
|
||||
assert calls, "sample_calls.py must produce some calls edges"
|
||||
|
||||
# In sample_calls.py:
|
||||
# compute_score and normalize are LEAF functions — they call nothing.
|
||||
# They must appear as callees, never as callers.
|
||||
leaf_callers = [
|
||||
src for src, _ in calls
|
||||
if src.endswith("compute_score") or src.endswith("normalize")
|
||||
]
|
||||
assert leaf_callers == [], (
|
||||
f"Leaf functions appearing as callers means direction is inverted: "
|
||||
f"{leaf_callers}"
|
||||
)
|
||||
|
||||
# And they should appear at least once as callees.
|
||||
leaf_callees = [
|
||||
tgt for _, tgt in calls
|
||||
if "compute_score" in tgt or "normalize" in tgt
|
||||
]
|
||||
assert leaf_callees, f"leaf functions should appear as callees. got: {calls}"
|
||||
|
||||
|
||||
def test_src_tgt_metadata_not_leaked_into_graph_json(repro_graph):
|
||||
"""The _src/_tgt direction-preservation fields are an internal detail
|
||||
of the build path; they must be consumed by the exporter and stripped
|
||||
from graph.json."""
|
||||
leaks = [e for e in repro_graph["links"] if "_src" in e or "_tgt" in e]
|
||||
assert leaks == [], (
|
||||
f"_src/_tgt are internal; must not appear in graph.json. Leaks: {leaks[:3]}"
|
||||
)
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Bug 2 (HTML export): graph.html arrows must respect direction too
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _vis_edges_from_html(html: str) -> list[dict]:
|
||||
"""Extract the vis.js edges array embedded in graph.html.
|
||||
|
||||
`_html_script` emits `const RAW_EDGES = <json>;` — pull that JSON out
|
||||
directly rather than parsing the surrounding script.
|
||||
"""
|
||||
import re
|
||||
m = re.search(r"const RAW_EDGES = (\[.*?\]);", html, re.DOTALL)
|
||||
assert m, "could not locate RAW_EDGES in graph.html"
|
||||
return json.loads(m.group(1))
|
||||
|
||||
|
||||
def test_to_html_preserves_calls_and_rationale_for_direction(tmp_path: Path):
|
||||
"""to_html must read _src/_tgt before assigning vis.js `from`/`to`,
|
||||
otherwise undirected NetworkX storage flips arrows on render (#563)."""
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_html
|
||||
|
||||
_write_repro(tmp_path)
|
||||
repro_graph = _run_graphify_update(tmp_path)
|
||||
|
||||
G = build_from_json(repro_graph)
|
||||
out_html = tmp_path / "graph.html"
|
||||
to_html(G, communities={0: list(G.nodes())}, output_path=str(out_html))
|
||||
|
||||
vis_edges = _vis_edges_from_html(out_html.read_text(encoding="utf-8"))
|
||||
pairs = {(e["from"], e["to"]): e.get("label") for e in vis_edges}
|
||||
|
||||
# rationale_for: source must be the rationale node (file_type metadata
|
||||
# isn't on vis_edges, so we check via the json graph's node map).
|
||||
ftype = _file_type_map(repro_graph)
|
||||
rats_html = [
|
||||
(frm, to) for (frm, to), rel in pairs.items() if rel == "rationale_for"
|
||||
]
|
||||
assert rats_html, "expected rationale_for edges in graph.html"
|
||||
flipped_rats = [
|
||||
(frm, to) for (frm, to) in rats_html if ftype.get(frm) != "rationale"
|
||||
]
|
||||
assert flipped_rats == [], (
|
||||
f"rationale_for arrows in graph.html must point rationale->parent. "
|
||||
f"Flipped: {flipped_rats[:3]}"
|
||||
)
|
||||
|
||||
# calls: pin the same caller->callee directions asserted on graph.json.
|
||||
assert (
|
||||
"contact_form_contact_form",
|
||||
"jobq_sqlitequeue_check_idempotency",
|
||||
) in pairs, "contact_form->check_idempotency arrow missing in graph.html"
|
||||
assert (
|
||||
"contact_form_contact_form",
|
||||
"jobq_sqlitequeue_enqueue",
|
||||
) in pairs, "contact_form->enqueue arrow missing in graph.html"
|
||||
|
||||
# And the inversions must not be present.
|
||||
inversions = {
|
||||
("jobq_sqlitequeue_check_idempotency", "contact_form_contact_form"),
|
||||
("jobq_sqlitequeue_enqueue", "contact_form_contact_form"),
|
||||
}
|
||||
leaked = inversions & {
|
||||
(frm, to) for (frm, to), rel in pairs.items() if rel == "calls"
|
||||
}
|
||||
assert not leaked, f"Inverted calls arrows in graph.html: {leaked}"
|
||||
@@ -0,0 +1,177 @@
|
||||
"""
|
||||
Regression test for the cross-file member-call name-collision bug fixed by
|
||||
the `_MEMBER_CALL_NODE_TYPES` resolver guard.
|
||||
|
||||
Bug summary
|
||||
-----------
|
||||
graphify's per-language AST extractors strip member-expression callees
|
||||
(`this.logger.log(...)`, `obj.find(...)`, `Pkg::baz(...)`) down to the
|
||||
trailing identifier (`log`, `find`, `baz`) and queue them in `raw_calls`
|
||||
for cross-file resolution. The cross-file resolver then matches that bare
|
||||
identifier against a global lowercase name → id map. If any other file in
|
||||
the corpus defines a top-level helper with the same name (e.g. a
|
||||
`function log(id, name, pass) { ... }` in a smoke-test script), every
|
||||
unrelated `Logger.log` / `this.logger.log` / `logger.log` call across the
|
||||
codebase resolves to that single helper, producing a phantom god node with
|
||||
hundreds of bogus INFERRED edges.
|
||||
|
||||
Fix
|
||||
---
|
||||
Each `raw_calls.append(...)` now records `callee_node_type` (the AST node
|
||||
type of the callee). The cross-file resolver in `extract()` skips entries
|
||||
whose `callee_node_type` is in `_MEMBER_CALL_NODE_TYPES`.
|
||||
|
||||
Run with:
|
||||
pytest tests/test_member_call_resolution.py -v
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify.extract import extract
|
||||
|
||||
try:
|
||||
from graphify.extract import _MEMBER_CALL_NODE_TYPES
|
||||
except ImportError:
|
||||
_MEMBER_CALL_NODE_TYPES = None # patched constant absent on unpatched code
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Source fixtures — written verbatim to a tmp dir so tree-sitter sees real files
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_SMOKE_TEST_JS = """\
|
||||
const results = [];
|
||||
|
||||
function log(id, name, pass, detail = '') {
|
||||
const status = pass ? 'PASS' : 'FAIL';
|
||||
console.log(`${id} ${status} ${name}`);
|
||||
results.push({ id, name, pass });
|
||||
}
|
||||
|
||||
function testAuth() {
|
||||
log('A1', 'auth-login', true);
|
||||
log('A2', 'auth-refresh', true);
|
||||
}
|
||||
|
||||
testAuth();
|
||||
"""
|
||||
|
||||
_NESTJS_SERVICE_TS = """\
|
||||
import { Logger } from '@nestjs/common';
|
||||
|
||||
export class AppointmentsService {
|
||||
private readonly logger = new Logger('AppointmentsService');
|
||||
|
||||
async create(payload: unknown): Promise<void> {
|
||||
this.logger.log('Creating appointment');
|
||||
Logger.log('static-style log call');
|
||||
}
|
||||
|
||||
async cancel(id: string): Promise<void> {
|
||||
this.logger.log(`Cancelled ${id}`);
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
_NESTJS_OTHER_SERVICE_TS = """\
|
||||
import { Logger } from '@nestjs/common';
|
||||
|
||||
const logger = new Logger('eprescribing-metrics');
|
||||
|
||||
export function logTransmissionAttempt(rxId: string): void {
|
||||
logger.log({ event: 'tx-attempt', rxId });
|
||||
}
|
||||
|
||||
export function logWebhookReceived(payload: unknown): void {
|
||||
logger.log({ event: 'webhook', payload });
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project(tmp_path: Path) -> Path:
|
||||
(tmp_path / "validation").mkdir()
|
||||
(tmp_path / "src").mkdir()
|
||||
(tmp_path / "validation" / "smoke-test.mjs").write_text(_SMOKE_TEST_JS)
|
||||
(tmp_path / "src" / "appointments.service.ts").write_text(_NESTJS_SERVICE_TS)
|
||||
(tmp_path / "src" / "eprescribing-metrics.ts").write_text(_NESTJS_OTHER_SERVICE_TS)
|
||||
return tmp_path
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_member_call_node_types_constant_present() -> None:
|
||||
"""The constant must exist and cover every language extractor."""
|
||||
assert _MEMBER_CALL_NODE_TYPES is not None, (
|
||||
"_MEMBER_CALL_NODE_TYPES is missing from graphify.extract — patch not applied"
|
||||
)
|
||||
assert isinstance(_MEMBER_CALL_NODE_TYPES, frozenset)
|
||||
# Spot-check that the most important node types are tracked.
|
||||
for required in (
|
||||
"member_expression", # JS/TS
|
||||
"selector_expression", # Go
|
||||
"field_expression", # Rust / C++
|
||||
"navigation_expression", # Swift / Kotlin
|
||||
"dot", # Elixir
|
||||
):
|
||||
assert required in _MEMBER_CALL_NODE_TYPES, f"missing: {required}"
|
||||
|
||||
|
||||
def test_smoke_test_log_does_not_steal_nestjs_logger_calls(project: Path) -> None:
|
||||
"""
|
||||
Regression: with a corpus containing both `validation/smoke-test.mjs`
|
||||
(which defines `function log(...)`) AND NestJS service files (which
|
||||
call `this.logger.log(...)` / `Logger.log(...)` / `logger.log(...)`),
|
||||
NONE of the NestJS calls should resolve to the smoke-test `log` node.
|
||||
"""
|
||||
files = sorted(project.rglob("*.mjs")) + sorted(project.rglob("*.ts"))
|
||||
result = extract(files, cache_root=project)
|
||||
|
||||
log_nodes = [n for n in result["nodes"]
|
||||
if n.get("label", "").strip().rstrip("()") == "log"]
|
||||
assert len(log_nodes) == 1, "expected exactly one top-level log() symbol"
|
||||
|
||||
log_id = log_nodes[0]["id"]
|
||||
log_source_file = log_nodes[0]["source_file"]
|
||||
|
||||
# Every inbound edge to log() must come from the same file (validation/smoke-test.mjs).
|
||||
inbound = [e for e in result["edges"] if e.get("target") == log_id]
|
||||
cross_file = [e for e in inbound if e.get("source_file") != log_source_file]
|
||||
|
||||
assert not cross_file, (
|
||||
f"phantom edges leaked to log() from other files: "
|
||||
f"{[(e['source_file'], e['source_location']) for e in cross_file]}"
|
||||
)
|
||||
|
||||
# And we should still capture the legitimate intra-file calls
|
||||
# (testAuth → log in the smoke-test file).
|
||||
assert any(e for e in inbound if e.get("source_file") == log_source_file), (
|
||||
"lost legitimate intra-file call edges to log()"
|
||||
)
|
||||
|
||||
|
||||
def test_raw_calls_emit_callee_node_type_for_member_expressions(project: Path) -> None:
|
||||
"""
|
||||
Direct check on the raw-calls payload: any unresolved member-expression
|
||||
callee should carry a `callee_node_type` that's in _MEMBER_CALL_NODE_TYPES.
|
||||
|
||||
We can't easily inspect raw_calls after extract() returns (they get
|
||||
consumed by the resolver), so we test indirectly: the absence of phantom
|
||||
edges (above test) is the observable proof.
|
||||
"""
|
||||
# Sanity: just exercise extract() with something that triggers raw_calls
|
||||
# so we know our test corpus is meaningful.
|
||||
files = sorted(project.rglob("*.mjs")) + sorted(project.rglob("*.ts"))
|
||||
result = extract(files, cache_root=project)
|
||||
# We expect nodes from all three files.
|
||||
source_files = {n.get("source_file") for n in result["nodes"]}
|
||||
assert any("smoke-test" in (s or "") for s in source_files)
|
||||
assert any("appointments.service" in (s or "") for s in source_files)
|
||||
assert any("eprescribing-metrics" in (s or "") for s in source_files)
|
||||
@@ -137,3 +137,50 @@ def test_community_article_truncation_notice(tmp_path):
|
||||
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
|
||||
|
||||
|
||||
def test_to_wiki_clears_stale_articles(tmp_path):
|
||||
"""Regression: previous-run articles must be removed when labels change.
|
||||
|
||||
Real-world impact: community labels are LLM-generated (per skill.md Step 5)
|
||||
and non-deterministic across runs, so the same conceptual community gets a
|
||||
different 2-5 word name each rebuild. Without cleanup, every rebuild leaves
|
||||
the previous run's files as orphans, growing wiki/ unboundedly.
|
||||
"""
|
||||
G = _make_graph()
|
||||
|
||||
# First run with one set of labels
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels={0: "Old Name A", 1: "Old Name B"})
|
||||
assert (tmp_path / "Old_Name_A.md").exists()
|
||||
assert (tmp_path / "Old_Name_B.md").exists()
|
||||
|
||||
# Second run simulates LLM picking different names for the same communities
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels={0: "New Name A", 1: "New Name B"})
|
||||
|
||||
# Old files should be gone; new files should exist
|
||||
assert not (tmp_path / "Old_Name_A.md").exists(), "stale article from previous run not cleared"
|
||||
assert not (tmp_path / "Old_Name_B.md").exists(), "stale article from previous run not cleared"
|
||||
assert (tmp_path / "New_Name_A.md").exists()
|
||||
assert (tmp_path / "New_Name_B.md").exists()
|
||||
# index.md is always rewritten
|
||||
assert (tmp_path / "index.md").exists()
|
||||
|
||||
|
||||
def test_to_wiki_preserves_non_md_files(tmp_path):
|
||||
"""Cleanup only touches top-level .md files; subdirectories and other files survive.
|
||||
|
||||
Some users may keep auxiliary assets (images, .json sidecars) in wiki/ —
|
||||
cleanup must not be destructive beyond its own .md output domain.
|
||||
"""
|
||||
G = _make_graph()
|
||||
tmp_path.mkdir(parents=True, exist_ok=True)
|
||||
(tmp_path / "user_image.png").write_bytes(b"\x89PNG fake")
|
||||
(tmp_path / "user_data.json").write_text('{"key": "value"}')
|
||||
(tmp_path / "subdir").mkdir()
|
||||
(tmp_path / "subdir" / "nested.md").write_text("# user content")
|
||||
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS)
|
||||
|
||||
assert (tmp_path / "user_image.png").exists(), "non-.md file deleted"
|
||||
assert (tmp_path / "user_data.json").exists(), "non-.md file deleted"
|
||||
assert (tmp_path / "subdir" / "nested.md").exists(), "subdirectory .md deleted"
|
||||
Reference in new issue
Block a user