Compare commits

..
11 Commits
Author SHA1 Message Date
Safi be83a8cc55 bump to v0.6.2 2026-05-01 22:18:18 +01:00
SafiandClaude Sonnet 4.6 3fdae8f334 fix #623 #621 #605 #638 #589 #586 #593: kimi thinking, manifest, inline comments, query boost, cache race, markdownify, content hash
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 22:15:24 +01:00
SafiandClaude Sonnet 4.6 e73b6060b1 fix #590 #628 #629 #630 #619 #617: directed graph, negation patterns, Windows paths, cross-lang noise, shebang, R
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 21:56:17 +01:00
Safi 2dc759a951 bump to v0.6.1 2026-05-01 18:50:12 +01:00
Safi 14fd14a284 combine what+when in skill description 2026-05-01 18:47:40 +01:00
SafiandClaude Sonnet 4.6 7f336acfd9 fix .graphifyignore: correct gitignore semantics + hermetic non-VCS scan + skill auto-invoke
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 18:45:12 +01:00
SafiandClaude Sonnet 4.6 8a6306f769 make .graphifyignore hermetic: stop at VCS root, not project boundaries (closes #643)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 15:28:33 +01:00
Safi 6b68de140c stop .graphifyignore walk at any VCS root or home dir, not just .git (fixes #643) 2026-05-01 14:54:04 +01:00
Safi 17fb524a91 bump to v0.6.0 2026-05-01 10:18:37 +01:00
Safi ad1e11a035 update README: add SQL support to file type table and feature description 2026-05-01 10:16:20 +01:00
SafiandClaude Sonnet 4.6 7d604e8141 v6: SQL AST extractor + xlsx structural extraction utility (fixes #349)
- extract_sql(): deterministic tree-sitter extraction of tables, views,
  functions, foreign key references, and FROM/JOIN reads_from edges
- .sql added to CODE_EXTENSIONS and dispatch table
- tree-sitter-sql added as optional dep under [sql] extra
- xlsx_extract_structure(): extracts sheet/table/column nodes from .xlsx
  (utility — pipeline wiring in follow-up)
- 6 new SQL tests, 447 total passing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 10:15:06 +01:00
35 changed files with 682 additions and 1427 deletions

No files matched your search

+5 -15
View File
@@ -2,25 +2,16 @@ name: CI
on:
push:
branches: ["v1", "v2", "v3", "v4", "v5", "main"]
branches: ["v1", "v2", "v3", "v4", "main"]
pull_request:
branches: ["v1", "v2", "v3", "v4", "v5", "main"]
workflow_dispatch:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
branches: ["v1", "v2", "v3", "v4", "main"]
jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13"]
python-version: ["3.10", "3.12"]
steps:
- uses: actions/checkout@v4
@@ -29,12 +20,11 @@ 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 ".[all,test]"
pip install -e ".[mcp,pdf,watch]"
pip install pytest
- name: Run tests
run: |
+29
View File
@@ -2,6 +2,35 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
## 0.6.2 (2026-05-01)
- Fix: Kimi K2.6 reasoning mode consumed entire token budget leaving `content` empty — thinking now disabled on Moonshot calls so graphs actually populate (#623)
- Fix: `graphify update` / `graphify watch` never persisted the manifest, so every subsequent `--update` re-extracted all files — manifest now saved after each rebuild (#621)
- Fix: inline comments in `.graphifyignore` (e.g. `vendor/ # legacy`) now stripped correctly — whitespace + `#` suffix is treated as a comment, `path#hash.py` preserved (#605)
- Fix: `graphify query "FunctionName"` now returns the exact matching node first instead of high-degree hub modules hijacking the output — 100-point exact-match bonus + seeds render before BFS expansion (#638)
- Fix: concurrent AST extractors raced on a shared `.tmp` cache file — each writer now gets a unique tempfile via `mkstemp`, eliminating cache corruption under parallel extraction (#589)
- Fix: `_clone_repo` branch names starting with `-` could be interpreted as git flags — validation added, `--` separator inserted before positional args (#589)
- Fix: replaced `html2text` (GPL-3.0) with `markdownify` (MIT) — removes the only copyleft dependency from a MIT project (#586)
- Fix: `--update` re-extracted files whose mtime was bumped by sync tools (Obsidian, Nextcloud) without content changes — manifest now stores content hash alongside mtime; mtime bump triggers an MD5 check before re-extraction (#593)
- Feat: R language support — `.r` files classified as code and processed via LLM semantic extraction (#617)
- Feat: extensionless shell scripts now detected via shebang (`#!/bin/bash`, `#!/usr/bin/env python3`, etc.) and included as code (#619)
- Fix: cross-language INFERRED `calls` edges (e.g. Python→TypeScript name collision) no longer appear as top surprising connections in GRAPH_REPORT.md (#630)
- Fix: `cluster-only` CLI silently flipped directed graphs to undirected — `directed` flag now read from graph.json and preserved through re-clustering (#590)
- Fix: Windows UNC / extended-length paths (`\\?\C:\...`) now normalize to consistent cache keys (#629)
- Fix: `.graphifyignore` negation patterns (`!src/lib/secrets.ts`) now work — full last-match-wins evaluation with `!` un-ignore support (#628)
## 0.6.1 (2026-05-01)
- Fix: `.graphifyignore` discovery now uses correct gitignore semantics — outer rules are loaded first so inner (closer) rules always win via last-match-wins, matching standard gitignore behavior (#643)
- Fix: without a VCS root, `.graphifyignore` discovery is now hermetic to the scan folder — no leakage across sibling projects in a shared workspace (#643)
- Fix: anchored patterns (leading `/`) in a parent `.graphifyignore` now correctly apply only relative to their own directory, not the scan root (#643)
- Fix: trailing spaces in patterns are now handled per gitignore spec — unescaped trailing spaces are stripped, `vendor\ ` (escaped) is preserved (#643)
## 0.6.0 (2026-05-01)
- Feat: SQL AST extractor — `.sql` files now processed deterministically via tree-sitter. Extracts tables, views, functions/procedures, foreign key references, and FROM/JOIN reads_from edges. No LLM needed. Requires `pip install 'graphifyy[sql]'` (#349)
- Feat: `xlsx_extract_structure()` utility — extracts sheet names, named tables, and column headers from .xlsx files as structural nodes
## 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)
+6 -14
View File
@@ -23,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. 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).
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. SQL files are AST-extracted deterministically — tables, views, functions, foreign keys, and FROM/JOIN relationships map directly into the graph with no LLM needed. 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.
@@ -49,7 +49,7 @@ dist/
*.generated.py
```
Same syntax as `.gitignore`. You can keep a single `.graphifyignore` at your repo root — patterns work correctly even when graphify is run on a subfolder.
Same syntax as `.gitignore` — including `!` negation patterns to re-include specific files. You can keep a single `.graphifyignore` at your repo root — patterns work correctly even when graphify is run on a subfolder. Discovery never crosses a VCS boundary (`.git`, `.hg`, etc.), so sibling projects in a shared workspace don't leak rules into each other. Without a VCS root, only the scan folder's own `.graphifyignore` applies. Inline comments are supported: `vendor/ # legacy deps`.
## How it works
@@ -97,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 UserPromptSubmit 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 PreToolUse hooks — `graphify codex install` installs one in `.codex/hooks.json` in addition to writing AGENTS.md.
Then open your AI coding assistant and type:
@@ -131,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 **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.
**Codex** writes to `AGENTS.md` and also installs a **PreToolUse hook** in `.codex/hooks.json` that fires before every Bash tool call — same always-on mechanism as Claude Code.
**OpenCode** 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.
@@ -299,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 + UserPromptSubmit hook in .codex/hooks.json (Codex)
graphify codex install # AGENTS.md + PreToolUse 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
@@ -353,7 +353,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 |
| 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 .sql` | AST via tree-sitter + call-graph (cross-file for all languages) + Java extends/implements + docstring/comment rationale. SQL: tables, views, functions, foreign keys, FROM/JOIN edges (requires `pip install graphifyy[sql]`) |
| 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 |
@@ -426,14 +426,6 @@ 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.
-170
View File
@@ -1,170 +0,0 @@
# 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
```
+29 -105
View File
@@ -712,14 +712,15 @@ def _uninstall_opencode_plugin(project_dir: Path) -> None:
_CODEX_HOOK = {
"hooks": {
"UserPromptSubmit": [
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": (
"[ -f graphify-out/graph.json ] && "
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."}}' """
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"
),
}
@@ -730,103 +731,40 @@ _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 UserPromptSubmit hook to .codex/hooks.json."""
"""Add graphify PreToolUse 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:
loaded = json.loads(hooks_path.read_text(encoding="utf-8"))
existing = json.loads(hooks_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
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
existing = {}
else:
existing = {}
_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"])
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"])
hooks_path.write_text(json.dumps(existing, indent=2), encoding="utf-8")
print(f" .codex/hooks.json -> UserPromptSubmit hook registered")
print(f" .codex/hooks.json -> PreToolUse hook registered")
def _uninstall_codex_hook(project_dir: Path) -> None:
"""Remove graphify Codex hooks from .codex/hooks.json."""
"""Remove graphify PreToolUse hook from .codex/hooks.json."""
hooks_path = project_dir / ".codex" / "hooks.json"
if not hooks_path.exists():
return
try:
loaded = json.loads(hooks_path.read_text(encoding="utf-8"))
existing = json.loads(hooks_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return
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")
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")
def _agents_install(project_dir: Path, platform: str) -> None:
@@ -1011,11 +949,15 @@ def _clone_repo(url: str, branch: str | None = None, out_dir: Path | None = None
else:
dest = Path.home() / ".graphify" / "repos" / owner / repo
if branch and branch.startswith("-"):
print(f"error: invalid branch name: {branch!r}", file=sys.stderr)
sys.exit(1)
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]
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)
@@ -1025,7 +967,7 @@ def _clone_repo(url: str, branch: str | None = None, out_dir: Path | None = None
cmd = ["git", "clone", "--depth", "1"]
if branch:
cmd += ["--branch", branch]
cmd += [git_url, str(dest)]
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)
@@ -1064,7 +1006,6 @@ 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)")
@@ -1086,8 +1027,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 AGENTS.md section + UserPromptSubmit hook (Codex)")
print(" codex uninstall remove AGENTS.md section + graphify Codex hook")
print(" codex install write graphify section to AGENTS.md (Codex)")
print(" codex uninstall remove graphify section from AGENTS.md")
print(" opencode install write graphify section to AGENTS.md + 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)")
@@ -1442,7 +1383,6 @@ 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)
@@ -1455,7 +1395,8 @@ def main() -> None:
from graphify.export import to_json, to_html
print("Loading existing graph...")
_raw = json.loads(graph_json.read_text(encoding="utf-8"))
G = build_from_json(_raw)
_directed = bool(_raw.get("directed", False))
G = build_from_json(_raw, directed=_directed)
print(f"Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
print("Re-clustering...")
communities = cluster(G)
@@ -1471,25 +1412,8 @@ 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"))
# 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.")
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.")
elif cmd == "update":
if len(sys.argv) > 2:
+33
View File
@@ -1,7 +1,34 @@
"""Graph analysis: god nodes (most connected), surprising connections (cross-community), suggested questions."""
from __future__ import annotations
from pathlib import Path
import networkx as nx
# Language families — extensions sharing a runtime can legitimately call each other
_LANG_FAMILY: dict[str, str] = {
**{e: "python" for e in (".py", ".pyw")},
**{e: "js" for e in (".js", ".jsx", ".mjs", ".ejs", ".ts", ".tsx", ".vue", ".svelte")},
**{e: "go" for e in (".go",)},
**{e: "rust" for e in (".rs",)},
**{e: "jvm" for e in (".java", ".kt", ".kts", ".scala")},
**{e: "c" for e in (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp")},
**{e: "ruby" for e in (".rb",)},
**{e: "swift" for e in (".swift",)},
**{e: "dotnet" for e in (".cs",)},
**{e: "php" for e in (".php",)},
**{e: "r" for e in (".r",)},
}
def _cross_language(src_a: str, src_b: str) -> bool:
"""Return True if two source files belong to different language families."""
ext_a = Path(src_a).suffix.lower()
ext_b = Path(src_b).suffix.lower()
fam_a = _LANG_FAMILY.get(ext_a)
fam_b = _LANG_FAMILY.get(ext_b)
if fam_a is None or fam_b is None:
return False
return fam_a != fam_b
def _node_community_map(communities: dict[int, list[str]]) -> dict[str, int]:
"""Invert communities dict: node_id -> community_id."""
@@ -143,7 +170,13 @@ def _surprise_score(
# 1. Confidence weight - uncertain connections are more noteworthy
conf = data.get("confidence", "EXTRACTED")
relation = data.get("relation", "")
conf_bonus = {"AMBIGUOUS": 3, "INFERRED": 2, "EXTRACTED": 1}.get(conf, 1)
# Cross-language INFERRED calls are likely resolver pollution, not real surprises
if conf == "INFERRED" and relation == "calls" and _cross_language(u_source, v_source):
conf_bonus = 0 # downgrade: don't promote likely false positives
score += conf_bonus
if conf in ("AMBIGUOUS", "INFERRED"):
reasons.append(f"{conf.lower()} connection - not explicitly stated in source")
+30 -8
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import hashlib
import json
import os
import tempfile
from pathlib import Path
@@ -17,6 +18,17 @@ def _body_content(content: bytes) -> bytes:
return content
def _normalize_path(path: Path) -> Path:
"""Normalize path for consistent cache keys across Windows path spellings."""
import sys
if sys.platform != "win32":
return path
s = str(path)
if s.startswith("\\\\?\\"):
s = s[4:] # strip extended-length prefix \\?\
return Path(os.path.normcase(s))
def file_hash(path: Path, root: Path = Path(".")) -> str:
"""SHA256 of file contents + path relative to root.
@@ -27,7 +39,8 @@ def file_hash(path: Path, root: Path = Path(".")) -> str:
For Markdown files (.md), only the body below the YAML frontmatter is hashed,
so metadata-only changes (e.g. reviewed, status, tags) do not invalidate the cache.
"""
p = Path(path)
p = _normalize_path(Path(path))
root = _normalize_path(Path(root))
if not p.is_file():
raise IsADirectoryError(f"file_hash requires a file, got: {p}")
raw = p.read_bytes()
@@ -99,20 +112,29 @@ def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "a
if not p.is_file():
return
h = file_hash(p, root)
entry = cache_dir(root, kind) / f"{h}.json"
tmp = entry.with_suffix(".tmp")
target_dir = cache_dir(root, kind)
entry = target_dir / f"{h}.json"
fd, tmp_path = tempfile.mkstemp(dir=target_dir, prefix=f"{h}.", suffix=".tmp")
try:
tmp.write_text(json.dumps(result), encoding="utf-8")
os.write(fd, json.dumps(result).encode())
os.close(fd)
try:
os.replace(tmp, entry)
os.replace(tmp_path, entry)
except PermissionError:
# Windows: os.replace can fail with WinError 5 if the target is
# briefly locked. Fall back to copy-then-delete.
import shutil
shutil.copy2(tmp, entry)
tmp.unlink(missing_ok=True)
shutil.copy2(tmp_path, entry)
os.unlink(tmp_path)
except Exception:
tmp.unlink(missing_ok=True)
try:
os.close(fd)
except OSError:
pass
try:
os.unlink(tmp_path)
except OSError:
pass
raise
+256 -121
View File
@@ -18,7 +18,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'}
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', '.sql', '.r'}
DOC_EXTENSIONS = {'.md', '.mdx', '.txt', '.rst', '.html', '.yaml', '.yml'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
@@ -78,11 +78,42 @@ def _looks_like_paper(path: Path) -> bool:
_ASSET_DIR_MARKERS = {".imageset", ".xcassets", ".appiconset", ".colorset", ".launchimage"}
_SHEBANG_CODE_INTERPRETERS = {
"python", "python3", "python2",
"ruby", "perl", "node", "nodejs",
"bash", "sh", "dash", "zsh", "fish", "ksh", "tcsh",
"lua", "php", "julia", "Rscript",
}
def _shebang_file_type(path: Path) -> FileType | None:
"""Peek at the first line of an extensionless file for a shebang."""
try:
with path.open("rb") as f:
first = f.read(128)
if not first.startswith(b"#!"):
return None
line = first.split(b"\n")[0].decode(errors="replace")
parts = line[2:].strip().split()
if not parts:
return None
interp = parts[0].split("/")[-1] # /usr/bin/env → env
if interp == "env" and len(parts) > 1:
interp = parts[1].split("/")[-1]
if interp in _SHEBANG_CODE_INTERPRETERS:
return FileType.CODE
except OSError:
pass
return None
def classify_file(path: Path) -> FileType | None:
# Compound extensions must be checked before simple suffix lookup
if path.name.lower().endswith(".blade.php"):
return FileType.CODE
ext = path.suffix.lower()
if not ext:
return _shebang_file_type(path)
if ext in CODE_EXTENSIONS:
return FileType.CODE
if ext in PAPER_EXTENSIONS:
@@ -169,7 +200,6 @@ def xlsx_to_markdown(path: Path) -> str:
ws = wb[sheet_name]
rows = []
for row in ws.iter_rows(values_only=True):
# Skip entirely empty rows
if all(cell is None for cell in row):
continue
rows.append([str(cell) if cell is not None else "" for cell in row])
@@ -190,6 +220,91 @@ def xlsx_to_markdown(path: Path) -> str:
return ""
def xlsx_extract_structure(path: Path) -> dict:
"""Extract structural nodes (sheets, named tables, column headers) from an .xlsx file.
Returns a nodes/edges dict compatible with the graphify extract pipeline.
Used in addition to xlsx_to_markdown so Claude sees both structure and content.
"""
def _nid(*parts: str) -> str:
return re.sub(r"[^a-z0-9_]", "_", "_".join(p.lower() for p in parts).strip("_"))
try:
import openpyxl
except ImportError:
return {"nodes": [], "edges": []}
try:
wb = openpyxl.load_workbook(str(path), read_only=False, data_only=True)
except Exception:
return {"nodes": [], "edges": []}
stem = _re.sub(r"[^a-z0-9]", "_", path.stem.lower())
str_path = str(path)
file_nid = _nid(str_path)
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "document",
"source_file": str_path, "source_location": None}]
edges: list[dict] = []
seen: set[str] = {file_nid}
def _add(nid: str, label: str) -> None:
if nid not in seen:
seen.add(nid)
nodes.append({"id": nid, "label": label, "file_type": "document",
"source_file": str_path, "source_location": None})
def _edge(src: str, tgt: str, relation: str) -> None:
edges.append({"source": src, "target": tgt, "relation": relation,
"confidence": "EXTRACTED", "source_file": str_path,
"source_location": None, "weight": 1.0})
for sheet_name in wb.sheetnames:
ws = wb[sheet_name]
sheet_nid = _nid(stem, sheet_name)
_add(sheet_nid, f"{sheet_name} (sheet)")
_edge(file_nid, sheet_nid, "contains")
# Named Excel Tables (ListObjects)
if hasattr(ws, "tables"):
for tbl in ws.tables.values():
tbl_nid = _nid(stem, sheet_name, tbl.name)
_add(tbl_nid, tbl.name)
_edge(sheet_nid, tbl_nid, "contains")
# Column headers from table header row
ref = tbl.ref # e.g. "A1:D10"
if ref:
try:
from openpyxl.utils import range_boundaries
min_col, min_row, max_col, _ = range_boundaries(ref)
header_row = list(ws.iter_rows(min_row=min_row, max_row=min_row,
min_col=min_col, max_col=max_col,
values_only=True))
if header_row:
for col_name in header_row[0]:
if col_name:
col_nid = _nid(stem, tbl.name, str(col_name))
_add(col_nid, str(col_name))
_edge(tbl_nid, col_nid, "contains")
except Exception:
pass
else:
# Fallback: first non-empty row as column headers
for row in ws.iter_rows(max_row=1, values_only=True):
for cell in row:
if cell:
col_nid = _nid(stem, sheet_name, str(cell))
_add(col_nid, str(cell))
_edge(sheet_nid, col_nid, "contains")
break
try:
wb.close()
except Exception:
pass
return {"nodes": nodes, "edges": edges}
def convert_office_file(path: Path, out_dir: Path) -> Path | None:
"""Convert a .docx or .xlsx to a markdown sidecar in out_dir.
@@ -263,59 +378,92 @@ def _is_noise_dir(part: str) -> bool:
return False
def _load_pattern_file(root: Path, filename: str) -> list[tuple[Path, str]]:
"""Read a Graphify pattern file from root **and ancestor directories**.
_VCS_MARKERS = (".git", ".hg", ".svn", "_darcs", ".fossil")
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 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.
def _parse_gitignore_line(raw: str) -> str:
"""Parse one raw line from a .graphifyignore file per gitignore spec.
- Strip newline chars
- Strip inline comments (whitespace + # suffix), but only when # is
preceded by whitespace — so path#with#hash.py is preserved
- Unescape \\# to literal #
- Remove trailing spaces unless escaped with backslash
- Strip leading whitespace
- Return empty string for blank lines and full-line comments
"""
patterns: list[tuple[Path, str]] = []
current = root.resolve()
line = raw.rstrip("\n\r")
line = line.lstrip()
if not line or line.startswith("#"):
return ""
# Strip inline comments: require whitespace before # (gitignore extension)
line = re.sub(r"\s+#+[^\\].*$", "", line)
# Unescape \# → literal #
line = line.replace("\\#", "#")
# Remove unescaped trailing spaces (per gitignore spec)
line = re.sub(r"(?<!\\) +$", "", line)
return line
def _find_vcs_root(start: Path) -> Path | None:
"""Walk upward from start; return the first directory containing a VCS marker."""
current = start.resolve()
home = Path.home()
while True:
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))
# Stop climbing once we've processed the git repo root
if (current / ".git").exists():
break
if any((current / m).exists() for m in _VCS_MARKERS):
return current
parent = current.parent
if parent == current:
break # filesystem root
if parent == current or current == home:
return None
current = parent
return patterns
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
"""Read .graphifyignore patterns from root and ancestor directories."""
return _load_pattern_file(root, ".graphifyignore")
"""Read .graphifyignore files and return (anchor_dir, pattern) pairs.
Patterns are returned outer-first so that inner (closer) rules are
appended last and win via last-match-wins semantics — matching gitignore
behavior exactly.
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.
Walk ceiling: the nearest VCS root if inside a repo, otherwise the scan
root itself (hermetic — no leakage across unrelated sibling projects).
"""
return _load_pattern_file(root, ".graphifyinclude")
root = root.resolve()
ceiling = _find_vcs_root(root) or root
# Collect ancestor dirs from ceiling down to root (outer → inner)
dirs: list[Path] = []
current = root
while True:
dirs.append(current)
if current == ceiling:
break
current = current.parent
dirs.reverse() # ceiling first, scan root last
patterns: list[tuple[Path, str]] = []
for d in dirs:
ignore_file = d / ".graphifyignore"
if ignore_file.exists():
for raw in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
line = _parse_gitignore_line(raw)
if line:
patterns.append((d, line))
return patterns
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:
def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
"""Return True if the path should be ignored per .graphifyignore patterns.
Uses gitignore last-match-wins semantics: all patterns are evaluated in
order; the final matching pattern determines the result. Negation patterns
(starting with !) un-ignore a previously ignored path.
"""
if not patterns:
return False
def _matches(rel: str, p: str) -> bool:
parts = rel.split("/")
if fnmatch.fnmatch(rel, p):
return True
if fnmatch.fnmatch(path.name, p):
@@ -325,77 +473,40 @@ def _pattern_matches(path: Path, rel: str, pattern: str) -> bool:
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
result = False
for anchor, pattern in patterns:
p = pattern.strip("/")
negated = pattern.startswith("!")
raw = pattern[1:] if negated else pattern
anchored = raw.startswith("/")
p = raw.strip("/")
if not p:
continue
# Try path relative to the scan root
try:
rel = str(path.relative_to(root)).replace(os.sep, "/")
if _pattern_matches(path, rel, p):
return True
except ValueError:
pass
# 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:
matched = False
if anchored:
try:
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
if _pattern_matches(path, rel_anchor, p):
return True
matched = _matches(rel_anchor, p)
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:
else:
try:
rels.append(str(path.relative_to(anchor)).replace(os.sep, "/"))
rel = str(path.relative_to(root)).replace(os.sep, "/")
matched = _matches(rel, p)
except ValueError:
pass
if not matched and anchor != root:
try:
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
matched = _matches(rel_anchor, p)
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
if matched:
result = not negated # last match wins; ! flips to un-ignore
return result
def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
@@ -411,7 +522,6 @@ 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"
@@ -433,13 +543,11 @@ 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.
# Hidden dirs remain skipped by default, but .graphifyinclude can
# opt in the exact hidden subtrees needed to reach allowlisted files.
# Prune noise dirs in-place so os.walk never descends into them
dirnames[:] = [
d for d in dirnames
if not _is_noise_dir(d)
and (not d.startswith(".") or _could_contain_included_path(dp / d, root, include_patterns))
if not d.startswith(".")
and not _is_noise_dir(d)
and not _is_ignored(dp / d, root, ignore_patterns)
]
for fname in filenames:
@@ -456,12 +564,9 @@ 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:
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):
# Hidden files are already excluded via dir pruning above,
# but catch hidden files at the root level
if p.name.startswith("."):
continue
# Skip files inside our own converted/ dir (avoid re-processing sidecars)
if str(p).startswith(str(converted_dir)):
@@ -512,12 +617,24 @@ 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),
}
def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict[str, float]:
"""Load the file modification time manifest from a previous run."""
def _md5_file(path: Path) -> str:
"""MD5 of file contents streamed in 64KB chunks — for change detection only."""
import hashlib as _hl
h = _hl.md5()
try:
with path.open("rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
except OSError:
return ""
return h.hexdigest()
def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict:
"""Load the manifest from a previous run. Returns {} on any error."""
try:
return json.loads(Path(manifest_path).read_text(encoding="utf-8"))
except Exception:
@@ -525,12 +642,13 @@ def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict[str, float]:
def save_manifest(files: dict[str, list[str]], manifest_path: str = _MANIFEST_PATH) -> None:
"""Save current file mtimes so the next --update run can diff against them."""
manifest: dict[str, float] = {}
"""Save current file mtimes + content hashes for change detection on --update."""
manifest: dict[str, dict] = {}
for file_list in files.values():
for f in file_list:
try:
manifest[f] = Path(f).stat().st_mtime
p = Path(f)
manifest[f] = {"mtime": p.stat().st_mtime, "hash": _md5_file(p)}
except OSError:
pass # file deleted between detect() and manifest write - skip it
Path(manifest_path).parent.mkdir(parents=True, exist_ok=True)
@@ -540,8 +658,11 @@ def save_manifest(files: dict[str, list[str]], manifest_path: str = _MANIFEST_PA
def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
"""Like detect(), but returns only new or modified files since the last run.
Compares current file mtimes against the stored manifest.
Use for --update mode: re-extract only what changed, merge into existing graph.
Fast path: mtime unchanged → unchanged (free, no hash).
Slow path: mtime bumped → compare MD5. Same hash = sync tool touched mtime,
treat as unchanged. Different hash = actually changed, re-extract.
Backwards compatible with legacy manifests storing plain float mtime values.
"""
full = detect(root)
manifest = load_manifest(manifest_path)
@@ -559,12 +680,26 @@ def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
for ftype, file_list in full["files"].items():
for f in file_list:
stored_mtime = manifest.get(f)
stored = manifest.get(f)
try:
current_mtime = Path(f).stat().st_mtime
except Exception:
current_mtime = 0
if stored_mtime is None or current_mtime > stored_mtime:
# Legacy manifest: plain float value
if isinstance(stored, (int, float)):
changed = stored is None or current_mtime > stored
elif isinstance(stored, dict):
stored_mtime = stored.get("mtime")
if stored_mtime is None or current_mtime != stored_mtime:
# mtime bumped — verify with content hash before re-extracting
changed = _md5_file(Path(f)) != stored.get("hash", "")
else:
changed = False
else:
changed = True # unknown format, re-extract to be safe
if changed:
new_files[ftype].append(f)
else:
unchanged_files[ftype].append(f)
+7 -40
View File
@@ -25,22 +25,6 @@ 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; }
@@ -343,15 +327,6 @@ 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: # nosec
json.dump(data, f, indent=2)
@@ -411,18 +386,15 @@ 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 the effective viz node limit
(MAX_NODES_FOR_VIZ by default; overridable via GRAPHIFY_VIZ_NODE_LIMIT env var).
Raises ValueError if graph exceeds MAX_NODES_FOR_VIZ.
If member_counts is provided (aggregated community view), node sizes are
based on community member counts rather than graph degree.
"""
limit = _viz_node_limit()
if G.number_of_nodes() > limit:
if G.number_of_nodes() > MAX_NODES_FOR_VIZ:
raise ValueError(
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."
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz. "
f"Use --no-viz or reduce input size."
)
node_community = _node_community_map(communities)
@@ -459,19 +431,14 @@ def to_html(
"degree": deg,
})
# 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).
# Build edges list
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": true_src,
"to": true_tgt,
"from": u,
"to": v,
"label": relation,
"title": _html.escape(f"{relation} [{confidence}]"),
"dashes": confidence != "EXTRACTED",
+136 -68
View File
@@ -11,29 +11,6 @@ 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)
@@ -1195,16 +1172,13 @@ 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().
# Track the AST node type so the cross-file resolver can refuse to
# name-match member-expression callees (`x.foo()`).
# Callee not in this file — save for cross-file resolution in extract()
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"
@@ -1736,6 +1710,137 @@ def extract_verilog(path: Path) -> dict:
return {"nodes": nodes, "edges": edges}
def extract_sql(path: Path) -> dict:
"""Extract tables, views, functions, and relationships from .sql files via tree-sitter."""
try:
import tree_sitter_sql as tssql
from tree_sitter import Language, Parser
except ImportError:
return {"nodes": [], "edges": [], "error": "tree_sitter_sql not installed. Run: pip install tree-sitter-sql"}
try:
language = Language(tssql.language())
parser = Parser(language)
source = path.read_bytes()
tree = parser.parse(source)
root = tree.root_node
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
stem = re.sub(r"[^a-z0-9]", "_", path.stem.lower())
str_path = str(path)
file_nid = _make_id(str_path)
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
"source_file": str_path, "source_location": None}]
edges: list[dict] = []
seen_ids: set[str] = {file_nid}
table_nids: dict[str, str] = {} # name → nid for reference resolution
def _read(n) -> str:
return source[n.start_byte:n.end_byte].decode("utf-8", errors="replace")
def _obj_name(n) -> str | None:
for c in n.children:
if c.type == "object_reference":
for cc in c.children:
if cc.type == "identifier":
return _read(cc)
return None
def _add_node(nid: str, label: str, line: int) -> None:
if nid not in seen_ids:
seen_ids.add(nid)
nodes.append({"id": nid, "label": label, "file_type": "code",
"source_file": str_path, "source_location": f"L{line}"})
edges.append({"source": file_nid, "target": nid, "relation": "contains",
"confidence": "EXTRACTED", "source_file": str_path,
"source_location": f"L{line}", "weight": 1.0})
def _add_edge(src: str, tgt: str, relation: str, line: int) -> None:
edges.append({"source": src, "target": tgt, "relation": relation,
"confidence": "EXTRACTED", "source_file": str_path,
"source_location": f"L{line}", "weight": 1.0})
def walk(node) -> None:
t = node.type
line = node.start_point[0] + 1
if t == "create_table":
name = _obj_name(node)
if name:
nid = _make_id(stem, name)
_add_node(nid, name, line)
table_nids[name.lower()] = nid
# Foreign key REFERENCES
for col in node.children:
if col.type == "column_definitions":
for cd in col.children:
if cd.type != "column_definition":
continue
ref_name: str | None = None
found_ref = False
for cc in cd.children:
if cc.type == "keyword_references":
found_ref = True
elif found_ref and cc.type == "object_reference":
for ccc in cc.children:
if ccc.type == "identifier":
ref_name = _read(ccc)
break
if ref_name:
ref_nid = _make_id(stem, ref_name)
_add_edge(nid, ref_nid, "references", line)
elif t == "create_view":
name = _obj_name(node)
if name:
nid = _make_id(stem, name)
_add_node(nid, name, line)
table_nids[name.lower()] = nid
# FROM/JOIN table references inside view body
_walk_from_refs(node, nid, line)
elif t == "create_function":
name = _obj_name(node)
if name:
nid = _make_id(stem, name)
_add_node(nid, f"{name}()", line)
_walk_from_refs(node, nid, line)
elif t == "create_procedure":
name = _obj_name(node)
if name:
nid = _make_id(stem, name)
_add_node(nid, f"{name}()", line)
_walk_from_refs(node, nid, line)
for child in node.children:
walk(child)
def _walk_from_refs(node, caller_nid: str, line: int) -> None:
"""Recursively find FROM/JOIN table references inside a node."""
if node.type in ("from", "join"):
for c in node.children:
if c.type == "relation":
for cc in c.children:
if cc.type == "object_reference":
for ccc in cc.children:
if ccc.type == "identifier":
tbl = _read(ccc)
tbl_nid = _make_id(stem, tbl)
_add_edge(caller_nid, tbl_nid, "reads_from",
c.start_point[0] + 1)
for child in node.children:
_walk_from_refs(child, caller_nid, line)
for stmt in root.children:
if stmt.type == "statement":
for child in stmt.children:
walk(child)
return {"nodes": nodes, "edges": edges}
def extract_lua(path: Path) -> dict:
"""Extract functions, methods, require() imports, and calls from a .lua file."""
return _extract_generic(path, _LUA_CONFIG)
@@ -2157,7 +2262,6 @@ def extract_go(path: Path) -> dict:
"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)
@@ -2338,7 +2442,6 @@ def extract_rust(path: Path) -> dict:
"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)
@@ -2510,13 +2613,6 @@ def extract_zig(path: Path) -> dict:
"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)
@@ -2682,7 +2778,6 @@ def extract_powershell(path: Path) -> dict:
"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)
@@ -2735,17 +2830,8 @@ def _resolve_cross_file_imports(
stem = Path(src).stem
label = node.get("label", "")
nid = node.get("id", "")
# 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"
):
# Only index real classes/functions (not file nodes, not method stubs)
if label and not label.endswith((")", ".py")) and "_" not in label[:1]:
stem_to_entities.setdefault(stem, {})[label] = nid
# Pass 2: for each file, find `from .X import A, B, C` and resolve
@@ -2756,15 +2842,12 @@ def _resolve_cross_file_imports(
stem = _file_stem(path)
str_path = str(path)
# 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).
# Find all classes defined in this file (the importers)
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
@@ -3301,9 +3384,6 @@ def extract_elixir(path: Path) -> dict:
"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)
@@ -3410,6 +3490,7 @@ def extract(paths: list[Path], cache_root: Path | None = None) -> dict:
".dart": extract_dart,
".v": extract_verilog,
".sv": extract_verilog,
".sql": extract_sql,
}
total = len(paths)
@@ -3486,13 +3567,8 @@ 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:
@@ -3501,14 +3577,6 @@ 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
+8 -11
View File
@@ -49,19 +49,16 @@ def _fetch_html(url: str) -> str:
def _html_to_markdown(html: str, url: str) -> str:
"""Convert HTML to clean markdown. Uses html2text if available, else basic strip."""
"""Convert HTML to clean markdown. Uses markdownify if available, else basic strip."""
# Always pre-strip script/style so their text content never leaks into output
html = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
html = re.sub(r"<style[^>]*>.*?</style>", "", html, flags=re.DOTALL | re.IGNORECASE)
try:
import html2text
h = html2text.HTML2Text()
h.ignore_links = False
h.ignore_images = True
h.body_width = 0
return h.handle(html)
from markdownify import markdownify
return markdownify(html, heading_style="ATX", bullets="-", strip=["img"])
except ImportError:
# Fallback: strip tags
text = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
text = re.sub(r"<style[^>]*>.*?</style>", "", text, flags=re.DOTALL | re.IGNORECASE)
text = re.sub(r"<[^>]+>", " ", text)
# Fallback: basic tag strip
text = re.sub(r"<[^>]+>", " ", html)
text = re.sub(r"\s+", " ", text).strip()
return text[:8000]
+3
View File
@@ -102,6 +102,9 @@ def _call_openai_compat(
}
if temperature is not None:
kwargs["temperature"] = temperature
# Kimi-k2.6 is a reasoning model — disable thinking so content isn't empty
if "moonshot" in base_url:
kwargs["extra_body"] = {"thinking": {"type": "disabled"}}
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
+17 -4
View File
@@ -45,6 +45,9 @@ def _strip_diacritics(text: str) -> str:
return "".join(c for c in nfkd if not unicodedata.combining(c))
_EXACT_MATCH_BONUS = 100.0
def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
scored = []
norm_terms = [_strip_diacritics(t).lower() for t in terms]
@@ -52,6 +55,9 @@ def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
norm_label = data.get("norm_label") or _strip_diacritics(data.get("label") or "").lower()
source = (data.get("source_file") or "").lower()
score = sum(1 for t in norm_terms if t in norm_label) + sum(0.5 for t in norm_terms if t in source)
# Exact match: single term equals the full label (strip trailing () for functions)
if any(t == norm_label or t == norm_label.rstrip("()") for t in norm_terms):
score += _EXACT_MATCH_BONUS
if score > 0:
scored.append((score, nid))
return sorted(scored, reverse=True)
@@ -89,11 +95,18 @@ def _dfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], lis
return visited, edges_seen
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000) -> str:
"""Render subgraph as text, cutting at token_budget (approx 3 chars/token)."""
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000, *, seeds: list[str] | None = None) -> str:
"""Render subgraph as text, cutting at token_budget (approx 3 chars/token).
seeds: exact-match nodes rendered first before the degree-sorted expansion,
so the queried symbol always appears at the top of the output.
"""
char_budget = token_budget * 3
lines = []
for nid in sorted(nodes, key=lambda n: G.degree(n), reverse=True):
seed_set = set(seeds or [])
ordered = [n for n in (seeds or []) if n in nodes] + \
sorted(nodes - seed_set, key=lambda n: G.degree(n), reverse=True)
for nid in ordered:
d = G.nodes[nid]
line = f"NODE {sanitize_label(d.get('label', nid))} [src={d.get('source_file', '')} loc={d.get('source_location', '')} community={d.get('community', '')}]"
lines.append(line)
@@ -246,7 +259,7 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
return "No matching nodes found."
nodes, edges = _dfs(G, start_nodes, depth) if mode == "dfs" else _bfs(G, start_nodes, depth)
header = f"Traversal: {mode.upper()} depth={depth} | Start: {[G.nodes[n].get('label', n) for n in start_nodes]} | {len(nodes)} nodes found\n\n"
return header + _subgraph_to_text(G, nodes, edges, budget)
return header + _subgraph_to_text(G, nodes, edges, budget, seeds=start_nodes)
def _tool_get_node(arguments: dict) -> str:
label = arguments["label"].lower()
+1 -1
View File
@@ -240,7 +240,7 @@ Process each file one at a time. For each file:
- 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.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
- confidence_score REQUIRED on every edge: EXTRACTED=1.0, INFERRED=0.6-0.9 (reason individually), AMBIGUOUS=0.1-0.3
3. Accumulate results across all files
Schema for each file's output:
+1 -1
View File
@@ -240,7 +240,7 @@ Process each file one at a time. For each file:
- 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.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
- confidence_score REQUIRED on every edge: EXTRACTED=1.0, INFERRED=0.6-0.9 (reason individually), AMBIGUOUS=0.1-0.3
3. Accumulate results across all files
Schema for each file's output:
+4 -10
View File
@@ -293,16 +293,10 @@ 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: 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.
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
+5 -22
View File
@@ -289,16 +289,10 @@ 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: 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.
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
@@ -825,22 +819,11 @@ 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)
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.')
print(f'Pruned {len(to_remove)} ghost nodes from {len(deleted)} deleted file(s)')
# 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.')
"
```
+4 -10
View File
@@ -290,16 +290,10 @@ 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: 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.
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
+1 -1
View File
@@ -239,7 +239,7 @@ Process each file one at a time. For each file:
- 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.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
- confidence_score REQUIRED on every edge: EXTRACTED=1.0, INFERRED=0.6-0.9 (reason individually), AMBIGUOUS=0.1-0.3
3. Accumulate results across all files
Schema for each file's output:
+4 -10
View File
@@ -291,16 +291,10 @@ 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: 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.
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
+4 -10
View File
@@ -280,16 +280,10 @@ 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: 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.
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
+4 -10
View File
@@ -279,16 +279,10 @@ 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: 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.
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
+6 -23
View File
@@ -1,6 +1,6 @@
---
name: graphify
description: "any input (code, docs, papers, images) - knowledge graph - clustered communities - HTML + JSON + audit report"
description: "any input (code, docs, papers, images, videos) to knowledge graph. Use when user asks any question about a codebase, documents, or project content - especially if graphify-out/ exists, treat the question as a /graphify query."
trigger: /graphify
---
@@ -337,16 +337,10 @@ 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: 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.
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- AMBIGUOUS edges: 0.1-0.3
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.
@@ -929,10 +923,7 @@ 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)
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.')
print(f'Pruned {len(to_remove)} ghost nodes from {len(deleted)} deleted file(s)')
# Merge: new nodes/edges into existing graph
G_existing.update(G_new)
@@ -948,14 +939,6 @@ 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.')
"
```
+6
View File
@@ -104,6 +104,12 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
if not json_written:
return False
try:
from graphify.detect import save_manifest
save_manifest(detected["files"])
except Exception:
pass
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")
+1 -21
View File
@@ -7,18 +7,7 @@ import networkx as nx
def _safe_filename(name: str) -> str:
"""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'
return name.replace("/", "-").replace(" ", "_").replace(":", "-")
def _cross_community_links(G: nx.Graph, nodes: list[str], own_cid: int, labels: dict[int, str]) -> list[tuple[str, int]]:
@@ -196,15 +185,6 @@ 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 []
+4 -4
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.5.7"
version = "0.6.2"
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" }
@@ -44,15 +44,15 @@ Issues = "https://github.com/safishamsi/graphify/issues"
[project.optional-dependencies]
mcp = ["mcp"]
neo4j = ["neo4j"]
pdf = ["pypdf", "html2text"]
pdf = ["pypdf", "markdownify"]
watch = ["watchdog"]
svg = ["matplotlib"]
leiden = ["graspologic; python_version < '3.13'"]
office = ["python-docx", "openpyxl"]
video = ["faster-whisper", "yt-dlp"]
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"]
sql = ["tree-sitter-sql"]
all = ["mcp", "neo4j", "pypdf", "markdownify", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper", "yt-dlp", "matplotlib", "openai", "tree-sitter-sql"]
[project.scripts]
graphify = "graphify.__main__:main"
+19
View File
@@ -0,0 +1,19 @@
CREATE TABLE organizations (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email TEXT NOT NULL,
org_id INT REFERENCES organizations(id)
);
CREATE VIEW active_users AS
SELECT * FROM users WHERE active = true;
CREATE FUNCTION get_user(user_id INT) RETURNS users AS $$
BEGIN
RETURN QUERY SELECT * FROM users WHERE id = user_id;
END;
$$ LANGUAGE plpgsql;
+21 -38
View File
@@ -104,42 +104,6 @@ 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")
@@ -174,8 +138,27 @@ def test_detect_follows_symlinked_file(tmp_path):
assert any("link.py" in f for f in code)
def test_graphifyignore_discovered_from_parent(tmp_path):
"""A .graphifyignore in a parent directory applies to subdirectory scans."""
def test_graphifyignore_hermetic_without_vcs(tmp_path):
"""Without a VCS root, parent .graphifyignore does NOT apply (hermetic)."""
(tmp_path / ".graphifyignore").write_text("vendor/\n")
sub = tmp_path / "packages" / "mylib"
sub.mkdir(parents=True)
(sub / "main.py").write_text("x = 1")
vendor = sub / "vendor"
vendor.mkdir()
(vendor / "dep.py").write_text("y = 2")
result = detect(sub)
code_files = result["files"]["code"]
assert any("main.py" in f for f in code_files)
# parent .graphifyignore must NOT leak into a non-VCS scan
assert any("vendor" in f for f in code_files)
assert result["graphifyignore_patterns"] == 0
def test_graphifyignore_discovered_from_parent_in_vcs(tmp_path):
"""Inside a VCS repo, parent .graphifyignore applies to subdirectory scans."""
(tmp_path / ".git").mkdir()
(tmp_path / ".graphifyignore").write_text("vendor/\n")
sub = tmp_path / "packages" / "mylib"
sub.mkdir(parents=True)
+1 -67
View File
@@ -1,19 +1,9 @@
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,
_viz_node_limit,
MAX_NODES_FOR_VIZ,
)
from graphify.export import to_json, to_cypher, to_graphml, to_html, to_canvas
FIXTURES = Path(__file__).parent / "fixtures"
@@ -137,62 +127,6 @@ 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()
-27
View File
@@ -123,30 +123,3 @@ 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"
)
-64
View File
@@ -1,5 +1,4 @@
"""Tests for graphify install --platform routing."""
import json
from pathlib import Path
from unittest.mock import patch
import pytest
@@ -130,69 +129,6 @@ 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()
-326
View File
@@ -1,326 +0,0 @@
"""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}"
-177
View File
@@ -1,177 +0,0 @@
"""
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)
+37 -2
View File
@@ -1,9 +1,9 @@
"""Tests for multi-language AST extraction: JS/TS, Go, Rust."""
"""Tests for multi-language AST extraction: JS/TS, Go, Rust, SQL."""
from __future__ import annotations
import shutil
from pathlib import Path
import pytest
from graphify.extract import extract_js, extract_go, extract_rust, extract
from graphify.extract import extract_js, extract_go, extract_rust, extract, extract_sql
FIXTURES = Path(__file__).parent / "fixtures"
@@ -171,3 +171,38 @@ def test_cache_miss_after_file_change(tmp_path):
# bar() should appear in the second result
labels2 = [n["label"] for n in r2["nodes"]]
assert any("bar" in l for l in labels2)
# ── SQL ───────────────────────────────────────────────────────────────────────
def test_sql_finds_tables():
r = extract_sql(FIXTURES / "sample.sql")
labels = [n["label"] for n in r["nodes"]]
assert any("users" in l for l in labels)
assert any("organizations" in l for l in labels)
def test_sql_finds_view():
r = extract_sql(FIXTURES / "sample.sql")
labels = [n["label"] for n in r["nodes"]]
assert any("active_users" in l for l in labels)
def test_sql_finds_function():
r = extract_sql(FIXTURES / "sample.sql")
labels = [n["label"] for n in r["nodes"]]
assert any("get_user" in l for l in labels)
def test_sql_emits_foreign_key_edge():
r = extract_sql(FIXTURES / "sample.sql")
relations = {e["relation"] for e in r["edges"]}
assert "references" in relations
def test_sql_emits_reads_from_edge():
r = extract_sql(FIXTURES / "sample.sql")
relations = {e["relation"] for e in r["edges"]}
assert "reads_from" in relations
def test_sql_no_dangling_edges():
r = extract_sql(FIXTURES / "sample.sql")
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids, f"dangling source: {e['source']}"
-47
View File
@@ -137,50 +137,3 @@ 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"