Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be83a8cc55 | ||
|
|
3fdae8f334 | ||
|
|
e73b6060b1 | ||
|
|
2dc759a951 | ||
|
|
14fd14a284 | ||
|
|
7f336acfd9 | ||
|
|
8a6306f769 | ||
|
|
6b68de140c | ||
|
|
17fb524a91 | ||
|
|
ad1e11a035 | ||
|
|
7d604e8141 | ||
|
|
0999822364 | ||
|
|
47a994ad5b | ||
|
|
5aaa268650 | ||
|
|
3755fdc885 | ||
|
|
4e871ad36c | ||
|
|
97099edc38 | ||
|
|
4360f9644b | ||
|
|
f755aca58f | ||
|
|
28b17d37f1 | ||
|
|
326c03e132 | ||
|
|
44fc32e3e2 | ||
|
|
744827166e | ||
|
|
c750582db4 | ||
|
|
71d1b394e9 | ||
|
|
a4ad901284 | ||
|
|
f9c344b546 | ||
|
|
59cbad3937 | ||
|
|
5904081d7a | ||
|
|
eceaaad61e | ||
|
|
dd86271312 | ||
|
|
7359cdace9 | ||
|
|
ee1df22b25 | ||
|
|
a566bfb566 | ||
|
|
4563b043f2 | ||
|
|
6175e0a8ea | ||
|
|
770d7f54c4 | ||
|
|
8bed332ff4 | ||
|
|
df9b7ec54f | ||
|
|
2faeed99a2 | ||
|
|
2c49da24f0 |
No files matched your search
@@ -2,6 +2,86 @@
|
||||
|
||||
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)
|
||||
|
||||
## 0.5.6 (2026-04-30)
|
||||
|
||||
- Fix: `NameError: name '_os' is not defined` crash after `graphify update` — this was fixed in v5 branch but not released to PyPI (#618, #612)
|
||||
|
||||
## 0.5.5 (2026-04-29)
|
||||
|
||||
- Feat: Kimi K2.6 backend — `pip install 'graphifyy[kimi]'` + `MOONSHOT_API_KEY` routes semantic extraction through Kimi K2.6. 3-6x richer relation extraction at ~3x lower cost. Claude remains default; Kimi is opt-in.
|
||||
- Fix: phantom god nodes (#598) — member-call callees (`this.logger.log()` → `log`) no longer cross-file resolved. Go package-qualified calls (`pkg.Func()`) correctly preserved. Affects JS/TS, Go, Rust, Swift, Kotlin, Scala, PHP, C++, C#, Zig, Elixir.
|
||||
- Fix: `concept` file_type no longer triggers validation warnings (#601)
|
||||
- Fix: `graphify update` remembers scan root via `graphify-out/.graphify_root` — no path argument needed on subsequent runs
|
||||
- Fix: Kimi K2.6 temperature 400 error — temperature param is now skipped for Kimi backends (model enforces its own fixed value) (#610)
|
||||
- Fix: community labels deleted in Step 9 cleanup — `.graphify_labels.json` is now preserved so wiki/obsidian/HTML retain human-readable names after re-cluster (#608)
|
||||
- Fix: `NameError: name '_os' is not defined` in `graphify update` Kimi tip (#612)
|
||||
- Fix: `SyntaxWarning` in `__main__.py` for shell glob pattern with backslash escapes
|
||||
- Fix: Python upper bound removed — `requires-python = ">=3.10"` now supports Python 3.14+ (#607)
|
||||
|
||||
## 0.5.4 (2026-04-28)
|
||||
|
||||
- Fix: SSRF DNS rebinding — `safe_fetch` now patches `socket.getaddrinfo` for the full request duration (#591)
|
||||
- Fix: yt-dlp SSRF bypass — `download_audio` now calls `validate_url` before handing URL to yt-dlp (#592)
|
||||
|
||||
## 0.5.3 (2026-04-27)
|
||||
|
||||
- Fix: cache namespace — AST and semantic entries now live in `cache/ast/` and `cache/semantic/` subdirectories; flat entries read as migration fallback
|
||||
|
||||
## 0.5.2 (2026-04-26)
|
||||
|
||||
- Fix: PreToolUse hook now matches on `Bash` instead of `Glob|Grep` for Claude Code v2.1.117+
|
||||
|
||||
## 0.5.1 (2026-04-25)
|
||||
|
||||
- Fix: node ID collision for same-named files in different directories
|
||||
- Fix: `source_file` paths relativized before return so `graph.json` is portable
|
||||
- Fix: desync guard — `to_json()` returns bool; report only written on successful JSON write
|
||||
- Feat: TypeScript `@/` path aliases resolved via `tsconfig.json`
|
||||
- Feat: Show All / Hide All buttons in HTML community panel
|
||||
|
||||
## 0.5.0 (2026-04-24)
|
||||
|
||||
- Feat: `graphify clone <github-url>` — clone and graph any public repo
|
||||
- Feat: `graphify merge-graphs` — combine multiple `graph.json` outputs into one cross-repo graph
|
||||
- Feat: `CLAUDE_CONFIG_DIR` support in `graphify install`
|
||||
- Feat: shrink guard — `to_json()` refuses to overwrite with a smaller graph
|
||||
- Feat: `build_merge()` for safe incremental updates
|
||||
- Feat: duplicate node deduplication via `deduplicate_by_label()`
|
||||
- Fix: `graphify-out/` excluded from source scanning
|
||||
|
||||
## 0.4.23 (2026-04-18)
|
||||
|
||||
- Fix: stale skill version warning persists after running `graphify install` when multiple platforms were previously installed — `graphify install` now refreshes `.graphify_version` in all other known skill directories so the warning clears across the board (#178)
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://safishamsi.gumroad.com/l/qetvlo"><img src="https://img.shields.io/badge/Book-The%20Memory%20Layer-2ea44f?style=flat&logo=gitbook&logoColor=white" alt="The Memory Layer"/></a>
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
@@ -22,7 +23,7 @@
|
||||
|
||||
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, or Google Antigravity - it reads your files, builds a knowledge graph, and gives you back structure you didn't know was there. Understand a codebase faster. Find the "why" behind architectural decisions.
|
||||
|
||||
Fully multimodal. Drop in code, PDFs, markdown, screenshots, diagrams, whiteboard photos, images in other languages, or video and audio files - graphify extracts concepts and relationships from all of it and connects them into one graph. Videos are transcribed with Whisper using a domain-aware prompt derived from your corpus. 25 languages supported via tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
|
||||
Fully multimodal. Drop in code, PDFs, markdown, screenshots, diagrams, whiteboard photos, images in other languages, or video and audio files - graphify extracts concepts and relationships from all of it and connects them into one graph. Videos are transcribed with Whisper using a domain-aware prompt derived from your corpus. YAML/YML files (Kubernetes, Kustomize, Helm, config) are indexed for semantic extraction. 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.
|
||||
|
||||
@@ -48,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
|
||||
|
||||
@@ -165,9 +166,15 @@ Think of it this way: the always-on hook gives your assistant a map. The `/graph
|
||||
**Recommended `.gitignore` additions:**
|
||||
```
|
||||
# keep graph outputs, skip heavy/local-only files
|
||||
graphify-out/cache/ # optional: commit for shared extraction speed, skip to keep repo small
|
||||
graphify-out/manifest.json # mtime-based, invalid after git clone — always gitignore this
|
||||
graphify-out/cost.json # local token tracking, not useful to share
|
||||
|
||||
# optional: commit for shared extraction speed, skip to keep repo small
|
||||
graphify-out/cache/
|
||||
|
||||
# mtime-based, invalid after git clone - always gitignore this
|
||||
graphify-out/manifest.json
|
||||
|
||||
# local token tracking, not useful to share
|
||||
graphify-out/cost.json
|
||||
```
|
||||
|
||||
**Shared setup:**
|
||||
@@ -327,6 +334,14 @@ graphify explain "SwinTransformer" # plain-language explanation of a n
|
||||
graphify add https://arxiv.org/abs/1706.03762 # fetch paper, save to ./raw, update graph
|
||||
graphify add https://... --author "Name" --contributor "Name"
|
||||
|
||||
# clone any GitHub repo and run the full pipeline on it
|
||||
graphify clone https://github.com/karpathy/nanoGPT # clones to ~/.graphify/repos/karpathy/nanoGPT
|
||||
graphify clone https://github.com/org/repo --branch dev --out ./my-clone
|
||||
|
||||
# cross-repo graphs — merge two or more graph.json outputs into one
|
||||
graphify merge-graphs repo1/graphify-out/graph.json repo2/graphify-out/graph.json
|
||||
graphify merge-graphs g1.json g2.json g3.json --out cross-repo.json
|
||||
|
||||
# incremental update and maintenance
|
||||
graphify watch ./src # auto-rebuild on code changes
|
||||
graphify check-update ./src # check if semantic re-extraction is pending (cron-safe)
|
||||
@@ -338,8 +353,8 @@ Works with any mix of file types:
|
||||
|
||||
| Type | Extensions | Extraction |
|
||||
|------|-----------|------------|
|
||||
| Code | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl .vue .svelte` | AST via tree-sitter + call-graph (cross-file for all languages) + Java extends/implements + docstring/comment rationale |
|
||||
| Docs | `.md .mdx .html .txt .rst` | Concepts + relationships + design rationale via Claude |
|
||||
| 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 |
|
||||
| Images | `.png .jpg .webp .gif` | Claude vision - screenshots, diagrams, any language |
|
||||
@@ -371,6 +386,8 @@ For better accuracy on technical content, use a larger model:
|
||||
|
||||
Audio never leaves your machine. All transcription runs locally.
|
||||
|
||||
> **Legal notice:** Only use `/graphify add <url>` to download content you have the rights to. graphify uses yt-dlp for audio extraction — the same terms of service and copyright rules apply.
|
||||
|
||||
## What you get
|
||||
|
||||
**God nodes** - highest-degree concepts (what everything connects through)
|
||||
|
||||
+156
-9
@@ -1,6 +1,7 @@
|
||||
"""graphify CLI - `graphify install` sets up the Claude Code skill."""
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
@@ -37,14 +38,22 @@ def _refresh_all_version_stamps() -> None:
|
||||
vf.write_text(__version__, encoding="utf-8")
|
||||
|
||||
_SETTINGS_HOOK = {
|
||||
"matcher": "Glob|Grep",
|
||||
# Claude Code v2.1.117+ removed dedicated Grep/Glob tools; searches now go through Bash.
|
||||
# We match on Bash and inspect the command string to avoid firing on every shell call.
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": (
|
||||
"[ -f graphify-out/graph.json ] && "
|
||||
r"""echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}}' """
|
||||
"|| true"
|
||||
"CMD=$(python3 -c \""
|
||||
"import json,sys; d=json.load(sys.stdin); "
|
||||
"print(d.get('tool_input',d).get('command',''))\" 2>/dev/null || true); "
|
||||
"case \"$CMD\" in "
|
||||
r"*grep*|*rg\ *|*ripgrep*|*find\ *|*fd\ *|*ack\ *|*ag\ *) "
|
||||
" [ -f graphify-out/graph.json ] && "
|
||||
r""" echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}}' """
|
||||
" || true ;; "
|
||||
"esac"
|
||||
),
|
||||
}
|
||||
],
|
||||
@@ -148,7 +157,12 @@ def install(platform: str = "claude") -> None:
|
||||
print(f"error: {cfg['skill_file']} not found in package - reinstall graphify", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
skill_dst = Path.home() / cfg["skill_dst"]
|
||||
import os as _os
|
||||
if platform in ("claude", "windows") and _os.environ.get("CLAUDE_CONFIG_DIR"):
|
||||
_claude_base = Path(_os.environ["CLAUDE_CONFIG_DIR"])
|
||||
skill_dst = _claude_base / "skills" / "graphify" / "SKILL.md"
|
||||
else:
|
||||
skill_dst = Path.home() / cfg["skill_dst"]
|
||||
skill_dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy(skill_src, skill_dst)
|
||||
(skill_dst.parent / ".graphify_version").write_text(__version__, encoding="utf-8")
|
||||
@@ -852,7 +866,7 @@ def _install_claude_hook(project_dir: Path) -> None:
|
||||
hooks = settings.setdefault("hooks", {})
|
||||
pre_tool = hooks.setdefault("PreToolUse", [])
|
||||
|
||||
hooks["PreToolUse"] = [h for h in pre_tool if not (h.get("matcher") == "Glob|Grep" and "graphify" in str(h))]
|
||||
hooks["PreToolUse"] = [h for h in pre_tool if not (h.get("matcher") in ("Glob|Grep", "Bash") and "graphify" in str(h))]
|
||||
hooks["PreToolUse"].append(_SETTINGS_HOOK)
|
||||
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
|
||||
print(f" .claude/settings.json -> PreToolUse hook registered")
|
||||
@@ -868,7 +882,7 @@ def _uninstall_claude_hook(project_dir: Path) -> None:
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
pre_tool = settings.get("hooks", {}).get("PreToolUse", [])
|
||||
filtered = [h for h in pre_tool if not (h.get("matcher") == "Glob|Grep" and "graphify" in str(h))]
|
||||
filtered = [h for h in pre_tool if not (h.get("matcher") in ("Glob|Grep", "Bash") and "graphify" in str(h))]
|
||||
if len(filtered) == len(pre_tool):
|
||||
return
|
||||
settings["hooks"]["PreToolUse"] = filtered
|
||||
@@ -906,6 +920,63 @@ def claude_uninstall(project_dir: Path | None = None) -> None:
|
||||
_uninstall_claude_hook(project_dir or Path("."))
|
||||
|
||||
|
||||
def _clone_repo(url: str, branch: str | None = None, out_dir: Path | None = None) -> Path:
|
||||
"""Clone a GitHub repo to a local cache dir and return the path.
|
||||
|
||||
Clones into ~/.graphify/repos/<owner>/<repo> by default so repeated
|
||||
runs on the same URL reuse the existing clone (git pull instead of clone).
|
||||
"""
|
||||
import subprocess as _sp
|
||||
import re as _re
|
||||
|
||||
# Normalise URL — strip trailing .git if present
|
||||
url = url.rstrip("/")
|
||||
if not url.endswith(".git"):
|
||||
git_url = url + ".git"
|
||||
else:
|
||||
git_url = url
|
||||
url = url[:-4]
|
||||
|
||||
# Extract owner/repo from URL
|
||||
m = _re.search(r"github\.com[:/]([^/]+)/([^/]+?)(?:\.git)?$", url)
|
||||
if not m:
|
||||
print(f"error: not a recognised GitHub URL: {url}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
owner, repo = m.group(1), m.group(2)
|
||||
|
||||
if out_dir:
|
||||
dest = out_dir
|
||||
else:
|
||||
dest = Path.home() / ".graphify" / "repos" / owner / repo
|
||||
|
||||
if 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]
|
||||
result = _sp.run(cmd, capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
print(f"warning: git pull failed:\n{result.stderr}", file=sys.stderr)
|
||||
else:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
print(f"Cloning {url} → {dest} ...", flush=True)
|
||||
cmd = ["git", "clone", "--depth", "1"]
|
||||
if branch:
|
||||
cmd += ["--branch", branch]
|
||||
cmd += ["--", git_url, str(dest)]
|
||||
result = _sp.run(cmd, capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
print(f"error: git clone failed:\n{result.stderr}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Ready at: {dest}", flush=True)
|
||||
return dest
|
||||
|
||||
|
||||
def main() -> None:
|
||||
# Check all known skill install locations for a stale version stamp.
|
||||
# Skip during install/uninstall (hook writes trigger a fresh check anyway).
|
||||
@@ -923,6 +994,11 @@ def main() -> None:
|
||||
print(" --graph <path> path to graph.json (default graphify-out/graph.json)")
|
||||
print(" explain \"X\" plain-language explanation of a node and its neighbors")
|
||||
print(" --graph <path> path to graph.json (default graphify-out/graph.json)")
|
||||
print(" clone <github-url> clone a GitHub repo locally and print its path for /graphify")
|
||||
print(" merge-graphs <g1> <g2> merge two or more graph.json files into one cross-repo graph")
|
||||
print(" --out <path> output path (default: graphify-out/merged-graph.json)")
|
||||
print(" --branch <branch> checkout a specific branch (default: repo default)")
|
||||
print(" --out <dir> clone to a custom directory (default: ~/.graphify/repos/<owner>/<repo>)")
|
||||
print(" add <url> fetch a URL and save it to ./raw, then update the graph")
|
||||
print(" --author \"Name\" tag the author of the content")
|
||||
print(" --contributor \"Name\" tag who added it to the corpus")
|
||||
@@ -1319,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)
|
||||
@@ -1339,7 +1416,15 @@ def main() -> None:
|
||||
print(f"Done — {len(communities)} communities. GRAPH_REPORT.md, graph.json and graph.html updated.")
|
||||
|
||||
elif cmd == "update":
|
||||
watch_path = Path(sys.argv[2]) if len(sys.argv) > 2 else Path(".")
|
||||
if len(sys.argv) > 2:
|
||||
watch_path = Path(sys.argv[2])
|
||||
else:
|
||||
# Try to recover the scan root saved by the last full build
|
||||
saved = Path("graphify-out/.graphify_root")
|
||||
if saved.exists():
|
||||
watch_path = Path(saved.read_text(encoding="utf-8").strip())
|
||||
else:
|
||||
watch_path = Path(".")
|
||||
if not watch_path.exists():
|
||||
print(f"error: path not found: {watch_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -1348,6 +1433,8 @@ def main() -> None:
|
||||
ok = _rebuild_code(watch_path)
|
||||
if ok:
|
||||
print("Code graph updated. For doc/paper/image changes run /graphify --update in your AI assistant.")
|
||||
if not os.environ.get("MOONSHOT_API_KEY") and not os.environ.get("GRAPHIFY_NO_TIPS"):
|
||||
print("Tip: set MOONSHOT_API_KEY to use Kimi K2.6 for semantic extraction — 3x cheaper, richer graphs. pip install 'graphifyy[kimi]'")
|
||||
else:
|
||||
print("Nothing to update or rebuild failed — check output above.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -1359,6 +1446,66 @@ def main() -> None:
|
||||
from graphify.watch import check_update
|
||||
check_update(Path(sys.argv[2]).resolve())
|
||||
sys.exit(0)
|
||||
elif cmd == "merge-graphs":
|
||||
# graphify merge-graphs graph1.json graph2.json ... --out merged.json
|
||||
args = sys.argv[2:]
|
||||
graph_paths: list[Path] = []
|
||||
out_path = Path("graphify-out/merged-graph.json")
|
||||
i = 0
|
||||
while i < len(args):
|
||||
if args[i] == "--out" and i + 1 < len(args):
|
||||
out_path = Path(args[i + 1]); i += 2
|
||||
else:
|
||||
graph_paths.append(Path(args[i])); i += 1
|
||||
if len(graph_paths) < 2:
|
||||
print("Usage: graphify merge-graphs <graph1.json> <graph2.json> [...] [--out merged.json]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
import networkx as _nx
|
||||
from networkx.readwrite import json_graph as _jg
|
||||
graphs = []
|
||||
for gp in graph_paths:
|
||||
if not gp.exists():
|
||||
print(f"error: not found: {gp}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
data = json.loads(gp.read_text(encoding="utf-8"))
|
||||
try:
|
||||
G = _jg.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
G = _jg.node_link_graph(data)
|
||||
# Tag every node with which repo it came from
|
||||
repo_tag = gp.parent.parent.name # graphify-out/../ → repo dir name
|
||||
for node in G.nodes:
|
||||
G.nodes[node].setdefault("repo", repo_tag)
|
||||
graphs.append(G)
|
||||
merged = _nx.compose_all(graphs)
|
||||
try:
|
||||
out_data = _jg.node_link_data(merged, edges="links")
|
||||
except TypeError:
|
||||
out_data = _jg.node_link_data(merged)
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_text(json.dumps(out_data, indent=2), encoding="utf-8")
|
||||
print(f"Merged {len(graphs)} graphs → {merged.number_of_nodes()} nodes, {merged.number_of_edges()} edges")
|
||||
print(f"Written to: {out_path}")
|
||||
|
||||
elif cmd == "clone":
|
||||
if len(sys.argv) < 3:
|
||||
print("Usage: graphify clone <github-url> [--branch <branch>] [--out <dir>]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
url = sys.argv[2]
|
||||
branch: str | None = None
|
||||
out_dir: Path | None = None
|
||||
args = sys.argv[3:]
|
||||
i = 0
|
||||
while i < len(args):
|
||||
if args[i] == "--branch" and i + 1 < len(args):
|
||||
branch = args[i + 1]; i += 2
|
||||
elif args[i] == "--out" and i + 1 < len(args):
|
||||
out_dir = Path(args[i + 1]); i += 2
|
||||
else:
|
||||
i += 1
|
||||
local_path = _clone_repo(url, branch=branch, out_dir=out_dir)
|
||||
print(local_path)
|
||||
|
||||
elif cmd == "benchmark":
|
||||
from graphify.benchmark import run_benchmark, print_benchmark
|
||||
graph_path = sys.argv[2] if len(sys.argv) > 2 else "graphify-out/graph.json"
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -21,8 +21,10 @@
|
||||
# before any graph construction happens.
|
||||
#
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
from .validate import validate_extraction
|
||||
|
||||
@@ -50,6 +52,18 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
|
||||
# Canonicalize legacy node/edge schema before validation.
|
||||
for node in extraction.get("nodes", []):
|
||||
if isinstance(node, dict) and "source" in node and "source_file" not in node:
|
||||
# Count edges that reference this node so the warning is actionable (#479)
|
||||
node_id = node.get("id", "?")
|
||||
affected_edges = sum(
|
||||
1 for e in extraction.get("edges", [])
|
||||
if e.get("source") == node_id or e.get("target") == node_id
|
||||
)
|
||||
print(
|
||||
f"[graphify] WARNING: node '{node_id}' uses field 'source' instead of "
|
||||
f"'source_file' — {affected_edges} edge(s) may be misrouted. "
|
||||
f"Rename the field to 'source_file' to silence this warning.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
node["source_file"] = node.pop("source")
|
||||
|
||||
errors = validate_extraction(extraction)
|
||||
@@ -111,3 +125,110 @@ def build(extractions: list[dict], *, directed: bool = False) -> nx.Graph:
|
||||
combined["input_tokens"] += ext.get("input_tokens", 0)
|
||||
combined["output_tokens"] += ext.get("output_tokens", 0)
|
||||
return build_from_json(combined, directed=directed)
|
||||
|
||||
|
||||
def _norm_label(label: str) -> str:
|
||||
"""Canonical dedup key — lowercase, alphanumeric only."""
|
||||
return re.sub(r"[^a-z0-9 ]", "", label.lower()).strip()
|
||||
|
||||
|
||||
def deduplicate_by_label(nodes: list[dict], edges: list[dict]) -> tuple[list[dict], list[dict]]:
|
||||
"""Merge nodes that share a normalised label, rewriting edge references.
|
||||
|
||||
Prefers IDs without chunk suffixes (_c\\d+) and shorter IDs when tied.
|
||||
Drops self-loops created by the merge. Called in build() automatically.
|
||||
"""
|
||||
_CHUNK_SUFFIX = re.compile(r"_c\d+$")
|
||||
canonical: dict[str, dict] = {} # norm_label -> surviving node
|
||||
remap: dict[str, str] = {} # old_id -> surviving_id
|
||||
|
||||
for node in nodes:
|
||||
key = _norm_label(node.get("label", node.get("id", "")))
|
||||
if not key:
|
||||
continue
|
||||
existing = canonical.get(key)
|
||||
if existing is None:
|
||||
canonical[key] = node
|
||||
else:
|
||||
has_suffix = bool(_CHUNK_SUFFIX.search(node["id"]))
|
||||
existing_has_suffix = bool(_CHUNK_SUFFIX.search(existing["id"]))
|
||||
if has_suffix and not existing_has_suffix:
|
||||
remap[node["id"]] = existing["id"]
|
||||
elif existing_has_suffix and not has_suffix:
|
||||
remap[existing["id"]] = node["id"]
|
||||
canonical[key] = node
|
||||
elif len(node["id"]) < len(existing["id"]):
|
||||
remap[existing["id"]] = node["id"]
|
||||
canonical[key] = node
|
||||
else:
|
||||
remap[node["id"]] = existing["id"]
|
||||
|
||||
if not remap:
|
||||
return nodes, edges
|
||||
|
||||
print(f"[graphify] Deduplicated {len(remap)} duplicate node(s) by label.", file=sys.stderr)
|
||||
deduped_nodes = list(canonical.values())
|
||||
deduped_edges = []
|
||||
for edge in edges:
|
||||
e = dict(edge)
|
||||
e["source"] = remap.get(e["source"], e["source"])
|
||||
e["target"] = remap.get(e["target"], e["target"])
|
||||
if e["source"] != e["target"]:
|
||||
deduped_edges.append(e)
|
||||
return deduped_nodes, deduped_edges
|
||||
|
||||
|
||||
def build_merge(
|
||||
new_chunks: list[dict],
|
||||
graph_path: str | Path = "graphify-out/graph.json",
|
||||
prune_sources: list[str] | None = None,
|
||||
*,
|
||||
directed: bool = False,
|
||||
) -> nx.Graph:
|
||||
"""Load existing graph.json, merge new chunks into it, and save back.
|
||||
|
||||
Never replaces — only grows (or prunes deleted-file nodes via prune_sources).
|
||||
Safe to call repeatedly: existing nodes and edges are preserved.
|
||||
"""
|
||||
from networkx.readwrite import json_graph as _jg
|
||||
|
||||
graph_path = Path(graph_path)
|
||||
if graph_path.exists():
|
||||
data = json.loads(graph_path.read_text(encoding="utf-8"))
|
||||
try:
|
||||
existing_G = _jg.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
existing_G = _jg.node_link_graph(data)
|
||||
# Reconstruct as a plain extraction dict so build() can merge it
|
||||
existing_nodes = [{"id": n, **existing_G.nodes[n]} for n in existing_G.nodes]
|
||||
existing_edges = [
|
||||
{"source": u, "target": v, **d} for u, v, d in existing_G.edges(data=True)
|
||||
]
|
||||
base = [{"nodes": existing_nodes, "edges": existing_edges}]
|
||||
else:
|
||||
base = []
|
||||
|
||||
all_chunks = base + list(new_chunks)
|
||||
G = build(all_chunks, directed=directed)
|
||||
|
||||
# Prune nodes from deleted source files
|
||||
if prune_sources:
|
||||
to_remove = [
|
||||
n for n, d in G.nodes(data=True)
|
||||
if d.get("source_file") in prune_sources
|
||||
]
|
||||
G.remove_nodes_from(to_remove)
|
||||
if to_remove:
|
||||
print(f"[graphify] Pruned {len(to_remove)} node(s) from deleted sources.", file=sys.stderr)
|
||||
|
||||
# Safety check: refuse to shrink the graph silently (#479)
|
||||
if graph_path.exists():
|
||||
existing_n = len(existing_nodes)
|
||||
new_n = G.number_of_nodes()
|
||||
if new_n < existing_n:
|
||||
raise ValueError(
|
||||
f"graphify: build_merge would shrink graph from {existing_n} → {new_n} nodes. "
|
||||
f"Pass prune_sources explicitly if you intend to remove nodes."
|
||||
)
|
||||
|
||||
return G
|
||||
+88
-32
@@ -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()
|
||||
@@ -43,37 +56,52 @@ def file_hash(path: Path, root: Path = Path(".")) -> str:
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def cache_dir(root: Path = Path(".")) -> Path:
|
||||
"""Returns graphify-out/cache/ - creates it if needed."""
|
||||
d = Path(root).resolve() / "graphify-out" / "cache"
|
||||
def cache_dir(root: Path = Path("."), kind: str = "ast") -> Path:
|
||||
"""Returns graphify-out/cache/{kind}/ - creates it if needed.
|
||||
|
||||
kind is "ast" or "semantic". Separate subdirectories prevent semantic cache
|
||||
entries from overwriting AST cache entries for the same source_file (#582).
|
||||
"""
|
||||
d = Path(root).resolve() / "graphify-out" / "cache" / kind
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def load_cached(path: Path, root: Path = Path(".")) -> dict | None:
|
||||
def load_cached(path: Path, root: Path = Path("."), kind: str = "ast") -> dict | None:
|
||||
"""Return cached extraction for this file if hash matches, else None.
|
||||
|
||||
Cache key: SHA256 of file contents.
|
||||
Cache value: stored as graphify-out/cache/{hash}.json
|
||||
Cache value: stored as graphify-out/cache/{kind}/{hash}.json
|
||||
|
||||
For kind="ast", also checks the legacy flat cache/ directory so users
|
||||
upgrading from pre-0.5.3 don't lose their existing AST cache entries.
|
||||
Returns None if no cache entry or file has changed.
|
||||
"""
|
||||
try:
|
||||
h = file_hash(path, root)
|
||||
except OSError:
|
||||
return None
|
||||
entry = cache_dir(root) / f"{h}.json"
|
||||
if not entry.exists():
|
||||
return None
|
||||
try:
|
||||
return json.loads(entry.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
entry = cache_dir(root, kind) / f"{h}.json"
|
||||
if entry.exists():
|
||||
try:
|
||||
return json.loads(entry.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
# Migration fallback: check legacy flat cache/ dir for AST entries
|
||||
if kind == "ast":
|
||||
legacy = Path(root).resolve() / "graphify-out" / "cache" / f"{h}.json"
|
||||
if legacy.exists():
|
||||
try:
|
||||
return json.loads(legacy.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
|
||||
def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "ast") -> None:
|
||||
"""Save extraction result for this file.
|
||||
|
||||
Stores as graphify-out/cache/{hash}.json where hash = SHA256 of current file contents.
|
||||
Stores as graphify-out/cache/{kind}/{hash}.json where hash = SHA256 of current file contents.
|
||||
result should be a dict with 'nodes' and 'edges' lists.
|
||||
|
||||
No-ops if `path` is not a regular file. Subagent-produced semantic fragments
|
||||
@@ -84,34 +112,60 @@ def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
|
||||
if not p.is_file():
|
||||
return
|
||||
h = file_hash(p, root)
|
||||
entry = cache_dir(root) / f"{h}.json"
|
||||
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
|
||||
|
||||
|
||||
def cached_files(root: Path = Path(".")) -> set[str]:
|
||||
"""Return set of file paths that have a valid cache entry (hash still matches)."""
|
||||
d = cache_dir(root)
|
||||
return {p.stem for p in d.glob("*.json")}
|
||||
"""Return set of file hashes that have a valid cache entry (any kind)."""
|
||||
base = Path(root).resolve() / "graphify-out" / "cache"
|
||||
hashes: set[str] = set()
|
||||
# Legacy flat entries
|
||||
if base.is_dir():
|
||||
hashes.update(p.stem for p in base.glob("*.json"))
|
||||
# Namespaced entries
|
||||
for kind in ("ast", "semantic"):
|
||||
d = base / kind
|
||||
if d.is_dir():
|
||||
hashes.update(p.stem for p in d.glob("*.json"))
|
||||
return hashes
|
||||
|
||||
|
||||
def clear_cache(root: Path = Path(".")) -> None:
|
||||
"""Delete all graphify-out/cache/*.json files."""
|
||||
d = cache_dir(root)
|
||||
for f in d.glob("*.json"):
|
||||
f.unlink()
|
||||
"""Delete all cache entries (ast/, semantic/, and legacy flat entries)."""
|
||||
base = Path(root).resolve() / "graphify-out" / "cache"
|
||||
# Legacy flat entries
|
||||
if base.is_dir():
|
||||
for f in base.glob("*.json"):
|
||||
f.unlink()
|
||||
# Namespaced entries
|
||||
for kind in ("ast", "semantic"):
|
||||
d = base / kind
|
||||
if d.is_dir():
|
||||
for f in d.glob("*.json"):
|
||||
f.unlink()
|
||||
|
||||
|
||||
def check_semantic_cache(
|
||||
@@ -129,7 +183,7 @@ def check_semantic_cache(
|
||||
uncached: list[str] = []
|
||||
|
||||
for fpath in files:
|
||||
result = load_cached(Path(fpath), root)
|
||||
result = load_cached(Path(fpath), root, kind="semantic")
|
||||
if result is not None:
|
||||
cached_nodes.extend(result.get("nodes", []))
|
||||
cached_edges.extend(result.get("edges", []))
|
||||
@@ -148,7 +202,9 @@ def save_semantic_cache(
|
||||
) -> int:
|
||||
"""Save semantic extraction results to cache, keyed by source_file.
|
||||
|
||||
Groups nodes and edges by source_file, then saves one cache entry per file.
|
||||
Groups nodes and edges by source_file, then saves one cache entry per file
|
||||
under cache/semantic/ (separate from AST entries in cache/ast/) to prevent
|
||||
hash-key collisions (#582).
|
||||
Returns the number of files cached.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
@@ -173,6 +229,6 @@ def save_semantic_cache(
|
||||
if not p.is_absolute():
|
||||
p = Path(root) / p
|
||||
if p.is_file():
|
||||
save_cached(p, result, root)
|
||||
save_cached(p, result, root, kind="semantic")
|
||||
saved += 1
|
||||
return saved
|
||||
+255
-48
@@ -18,8 +18,8 @@ class FileType(str, Enum):
|
||||
|
||||
_MANIFEST_PATH = "graphify-out/manifest.json"
|
||||
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.ejs', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.dart', '.v', '.sv'}
|
||||
DOC_EXTENSIONS = {'.md', '.mdx', '.txt', '.rst', '.html'}
|
||||
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'}
|
||||
OFFICE_EXTENSIONS = {'.docx', '.xlsx'}
|
||||
@@ -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.
|
||||
|
||||
@@ -241,6 +356,7 @@ _SKIP_DIRS = {
|
||||
"site-packages", "lib64",
|
||||
".pytest_cache", ".mypy_cache", ".ruff_cache",
|
||||
".tox", ".eggs", "*.egg-info",
|
||||
"graphify-out", # never treat own output as source input (#524)
|
||||
}
|
||||
|
||||
# Large generated files that are never useful to extract
|
||||
@@ -262,38 +378,87 @@ def _is_noise_dir(part: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
"""Read .graphifyignore from root **and ancestor directories**.
|
||||
_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 .graphifyignore 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:
|
||||
ignore_file = current / ".graphifyignore"
|
||||
if ignore_file.exists():
|
||||
for line in ignore_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
|
||||
|
||||
|
||||
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
"""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.
|
||||
|
||||
Walk ceiling: the nearest VCS root if inside a repo, otherwise the scan
|
||||
root itself (hermetic — no leakage across unrelated sibling projects).
|
||||
"""
|
||||
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 _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if path matches any .graphifyignore pattern."""
|
||||
"""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
|
||||
|
||||
@@ -310,27 +475,38 @@ def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> boo
|
||||
return True
|
||||
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 _matches(rel, p):
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
# Also try relative to the anchor dir (the .graphifyignore's location),
|
||||
# so patterns written at a parent level still fire when running on a subfolder
|
||||
if anchor != root:
|
||||
|
||||
matched = False
|
||||
if anchored:
|
||||
try:
|
||||
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
|
||||
if _matches(rel_anchor, p):
|
||||
return True
|
||||
matched = _matches(rel_anchor, p)
|
||||
except ValueError:
|
||||
pass
|
||||
return False
|
||||
else:
|
||||
try:
|
||||
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
|
||||
|
||||
if matched:
|
||||
result = not negated # last match wins; ! flips to un-ignore
|
||||
return result
|
||||
|
||||
|
||||
def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
@@ -444,8 +620,21 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
}
|
||||
|
||||
|
||||
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:
|
||||
@@ -453,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)
|
||||
@@ -468,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)
|
||||
@@ -487,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)
|
||||
|
||||
+48
-8
@@ -55,6 +55,9 @@ def _html_styles() -> str:
|
||||
.legend-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.legend-count { color: #666; font-size: 11px; }
|
||||
#stats { padding: 10px 14px; border-top: 1px solid #2a2a4e; font-size: 11px; color: #555; }
|
||||
#legend-controls { display: flex; gap: 6px; margin-bottom: 8px; }
|
||||
#legend-controls button { flex: 1; background: #0f0f1a; border: 1px solid #3a3a5e; color: #aaa; padding: 4px 0; border-radius: 4px; font-size: 11px; cursor: pointer; }
|
||||
#legend-controls button:hover { border-color: #4E79A7; color: #e0e0e0; }
|
||||
</style>"""
|
||||
|
||||
|
||||
@@ -240,6 +243,18 @@ document.addEventListener('click', e => {{
|
||||
}});
|
||||
|
||||
const hiddenCommunities = new Set();
|
||||
|
||||
function toggleAllCommunities(hide) {{
|
||||
document.querySelectorAll('.legend-item').forEach(item => {{
|
||||
hide ? item.classList.add('dimmed') : item.classList.remove('dimmed');
|
||||
}});
|
||||
LEGEND.forEach(c => {{
|
||||
if (hide) hiddenCommunities.add(c.cid); else hiddenCommunities.delete(c.cid);
|
||||
}});
|
||||
const updates = RAW_NODES.map(n => ({{ id: n.id, hidden: hide }}));
|
||||
nodesDS.update(updates);
|
||||
}}
|
||||
|
||||
const legendEl = document.getElementById('legend');
|
||||
LEGEND.forEach(c => {{
|
||||
const item = document.createElement('div');
|
||||
@@ -279,7 +294,27 @@ def attach_hyperedges(G: nx.Graph, hyperedges: list) -> None:
|
||||
G.graph["hyperedges"] = existing
|
||||
|
||||
|
||||
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) -> None:
|
||||
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *, force: bool = False) -> bool:
|
||||
# Safety check: refuse to silently shrink an existing graph (#479)
|
||||
existing_path = Path(output_path)
|
||||
if not force and existing_path.exists():
|
||||
try:
|
||||
existing_data = json.loads(existing_path.read_text(encoding="utf-8"))
|
||||
existing_n = len(existing_data.get("nodes", []))
|
||||
new_n = G.number_of_nodes()
|
||||
if new_n < existing_n:
|
||||
import sys as _sys
|
||||
print(
|
||||
f"[graphify] WARNING: new graph has {new_n} nodes but existing "
|
||||
f"graph.json has {existing_n}. Refusing to overwrite — you may be "
|
||||
f"missing chunk files from a previous session. "
|
||||
f"Pass force=True to override.",
|
||||
file=_sys.stderr,
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
pass # unreadable existing file — proceed with write
|
||||
|
||||
node_community = _node_community_map(communities)
|
||||
try:
|
||||
data = json_graph.node_link_data(G, edges="links")
|
||||
@@ -293,8 +328,9 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) ->
|
||||
conf = link.get("confidence", "EXTRACTED")
|
||||
link["confidence_score"] = _CONFIDENCE_SCORE_DEFAULTS.get(conf, 1.0)
|
||||
data["hyperedges"] = getattr(G, "graph", {}).get("hyperedges", [])
|
||||
with open(output_path, "w", encoding="utf-8") as f:
|
||||
with open(output_path, "w", encoding="utf-8") as f: # nosec
|
||||
json.dump(data, f, indent=2)
|
||||
return True
|
||||
|
||||
|
||||
def prune_dangling_edges(graph_data: dict) -> tuple[dict, int]:
|
||||
@@ -335,7 +371,7 @@ def to_cypher(G: nx.Graph, output_path: str) -> None:
|
||||
f"MATCH (a {{id: '{u_esc}'}}), (b {{id: '{v_esc}'}}) "
|
||||
f"MERGE (a)-[:{rel} {{confidence: '{conf}'}}]->(b);"
|
||||
)
|
||||
with open(output_path, "w", encoding="utf-8") as f:
|
||||
with open(output_path, "w", encoding="utf-8") as f: # nosec
|
||||
f.write("\n".join(lines))
|
||||
|
||||
|
||||
@@ -451,6 +487,10 @@ def to_html(
|
||||
</div>
|
||||
<div id="legend-wrap">
|
||||
<h3>Communities</h3>
|
||||
<div id="legend-controls">
|
||||
<button onclick="toggleAllCommunities(false)">Show All</button>
|
||||
<button onclick="toggleAllCommunities(true)">Hide All</button>
|
||||
</div>
|
||||
<div id="legend"></div>
|
||||
</div>
|
||||
<div id="stats">{stats}</div>
|
||||
@@ -460,7 +500,7 @@ def to_html(
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
Path(output_path).write_text(html, encoding="utf-8")
|
||||
Path(output_path).write_text(html, encoding="utf-8") # nosec
|
||||
|
||||
|
||||
# Keep backward-compatible alias - skill.md calls generate_html
|
||||
@@ -575,7 +615,7 @@ def to_obsidian(
|
||||
lines.append(inline_tags)
|
||||
|
||||
fname = node_filename[node_id] + ".md"
|
||||
(out / fname).write_text("\n".join(lines), encoding="utf-8")
|
||||
(out / fname).write_text("\n".join(lines), encoding="utf-8") # nosec
|
||||
|
||||
# Write one _COMMUNITY_name.md overview note per community
|
||||
# Build inter-community edge counts for "Connections to other communities"
|
||||
@@ -692,7 +732,7 @@ def to_obsidian(
|
||||
|
||||
community_safe = safe_name(community_name)
|
||||
fname = f"_COMMUNITY_{community_safe}.md"
|
||||
(out / fname).write_text("\n".join(lines), encoding="utf-8")
|
||||
(out / fname).write_text("\n".join(lines), encoding="utf-8") # nosec
|
||||
community_notes_written += 1
|
||||
|
||||
# Improvement 4: write .obsidian/graph.json to color nodes by community in graph view
|
||||
@@ -707,7 +747,7 @@ def to_obsidian(
|
||||
for cid, label in sorted((community_labels or {}).items())
|
||||
]
|
||||
}
|
||||
(obsidian_dir / "graph.json").write_text(json.dumps(graph_config, indent=2), encoding="utf-8")
|
||||
(obsidian_dir / "graph.json").write_text(json.dumps(graph_config, indent=2), encoding="utf-8") # nosec
|
||||
|
||||
return G.number_of_nodes() + community_notes_written
|
||||
|
||||
@@ -868,7 +908,7 @@ def to_canvas(
|
||||
})
|
||||
|
||||
canvas_data = {"nodes": canvas_nodes, "edges": canvas_edges}
|
||||
Path(output_path).write_text(json.dumps(canvas_data, indent=2), encoding="utf-8")
|
||||
Path(output_path).write_text(json.dumps(canvas_data, indent=2), encoding="utf-8") # nosec
|
||||
|
||||
|
||||
def push_to_neo4j(
|
||||
|
||||
+257
-18
@@ -18,6 +18,48 @@ def _make_id(*parts: str) -> str:
|
||||
return cleaned.strip("_").lower()
|
||||
|
||||
|
||||
def _file_stem(path: Path) -> str:
|
||||
"""Return a stem qualified with the parent directory name to avoid ID collisions
|
||||
when multiple files share the same filename in different directories (#550)."""
|
||||
parent = path.parent.name
|
||||
if parent and parent not in (".", ""):
|
||||
return f"{parent}.{path.stem}"
|
||||
return path.stem
|
||||
|
||||
|
||||
_TSCONFIG_ALIAS_CACHE: dict[str, dict[str, str]] = {}
|
||||
|
||||
|
||||
def _load_tsconfig_aliases(start_dir: Path) -> dict[str, str]:
|
||||
"""Walk up from start_dir to find tsconfig.json and return compilerOptions.paths aliases.
|
||||
|
||||
Returns a dict mapping alias prefix (e.g. "@/") to resolved base dir (e.g. "src/").
|
||||
Result is cached by tsconfig path string.
|
||||
"""
|
||||
current = start_dir.resolve()
|
||||
for candidate in [current, *current.parents]:
|
||||
tsconfig = candidate / "tsconfig.json"
|
||||
if tsconfig.exists():
|
||||
key = str(tsconfig)
|
||||
if key not in _TSCONFIG_ALIAS_CACHE:
|
||||
try:
|
||||
data = json.loads(tsconfig.read_text(encoding="utf-8"))
|
||||
paths = data.get("compilerOptions", {}).get("paths", {})
|
||||
aliases: dict[str, str] = {}
|
||||
for alias, targets in paths.items():
|
||||
if not targets:
|
||||
continue
|
||||
# Strip trailing /* from alias and target
|
||||
alias_prefix = alias.rstrip("/*")
|
||||
target_base = targets[0].rstrip("/*")
|
||||
aliases[alias_prefix] = str(candidate / target_base)
|
||||
_TSCONFIG_ALIAS_CACHE[key] = aliases
|
||||
except Exception:
|
||||
_TSCONFIG_ALIAS_CACHE[key] = {}
|
||||
return _TSCONFIG_ALIAS_CACHE[key]
|
||||
return {}
|
||||
|
||||
|
||||
# ── LanguageConfig dataclass ─────────────────────────────────────────────────
|
||||
|
||||
@dataclass
|
||||
@@ -156,11 +198,22 @@ def _import_js(node, source: bytes, file_nid: str, stem: str, edges: list, str_p
|
||||
resolved = resolved.with_suffix(".tsx")
|
||||
tgt_nid = _make_id(str(resolved))
|
||||
else:
|
||||
# Bare/scoped import (node_modules) - use last segment; dropped as external
|
||||
module_name = raw.split("/")[-1]
|
||||
if not module_name:
|
||||
break
|
||||
tgt_nid = _make_id(module_name)
|
||||
# Check tsconfig.json path aliases (e.g. "@/" → "src/") before treating as external (#575)
|
||||
aliases = _load_tsconfig_aliases(Path(str_path).parent)
|
||||
resolved_alias = None
|
||||
for alias_prefix, alias_base in aliases.items():
|
||||
if raw == alias_prefix or raw.startswith(alias_prefix + "/"):
|
||||
rest = raw[len(alias_prefix):].lstrip("/")
|
||||
resolved_alias = Path(os.path.normpath(Path(alias_base) / rest))
|
||||
break
|
||||
if resolved_alias is not None:
|
||||
tgt_nid = _make_id(str(resolved_alias))
|
||||
else:
|
||||
# Bare/scoped import (node_modules) - use last segment; dropped as external
|
||||
module_name = raw.split("/")[-1]
|
||||
if not module_name:
|
||||
break
|
||||
tgt_nid = _make_id(module_name)
|
||||
edges.append({
|
||||
"source": file_nid,
|
||||
"target": tgt_nid,
|
||||
@@ -676,7 +729,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -999,6 +1052,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
|
||||
if node.type in config.call_types:
|
||||
callee_name: str | None = None
|
||||
is_member_call: bool = False
|
||||
|
||||
# Special handling per language
|
||||
if config.ts_module == "tree_sitter_swift":
|
||||
@@ -1008,6 +1062,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
if first.type == "simple_identifier":
|
||||
callee_name = _read_text(first, source)
|
||||
elif first.type == "navigation_expression":
|
||||
is_member_call = True
|
||||
for child in first.children:
|
||||
if child.type == "navigation_suffix":
|
||||
for sc in child.children:
|
||||
@@ -1020,6 +1075,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
if first.type == "simple_identifier":
|
||||
callee_name = _read_text(first, source)
|
||||
elif first.type == "navigation_expression":
|
||||
is_member_call = True
|
||||
for child in reversed(first.children):
|
||||
if child.type == "simple_identifier":
|
||||
callee_name = _read_text(child, source)
|
||||
@@ -1031,6 +1087,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
if first.type == "identifier":
|
||||
callee_name = _read_text(first, source)
|
||||
elif first.type == "field_expression":
|
||||
is_member_call = True
|
||||
field = first.child_by_field_name("field")
|
||||
if field:
|
||||
callee_name = _read_text(field, source)
|
||||
@@ -1050,6 +1107,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
raw = _read_text(child, source)
|
||||
if "." in raw:
|
||||
callee_name = raw.split(".")[-1]
|
||||
is_member_call = True
|
||||
else:
|
||||
callee_name = raw
|
||||
break
|
||||
@@ -1065,6 +1123,8 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
if scope_node:
|
||||
callee_name = _read_text(scope_node, source)
|
||||
else:
|
||||
# member_call_expression: $obj->method()
|
||||
is_member_call = True
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node:
|
||||
callee_name = _read_text(name_node, source)
|
||||
@@ -1075,6 +1135,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
if func_node.type == "identifier":
|
||||
callee_name = _read_text(func_node, source)
|
||||
elif func_node.type in ("field_expression", "qualified_identifier"):
|
||||
is_member_call = True
|
||||
name = func_node.child_by_field_name("field") or func_node.child_by_field_name("name")
|
||||
if name:
|
||||
callee_name = _read_text(name, source)
|
||||
@@ -1085,6 +1146,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
if func_node.type == "identifier":
|
||||
callee_name = _read_text(func_node, source)
|
||||
elif func_node.type in config.call_accessor_node_types:
|
||||
is_member_call = True
|
||||
if config.call_accessor_field:
|
||||
attr = func_node.child_by_field_name(config.call_accessor_field)
|
||||
if attr:
|
||||
@@ -1114,6 +1176,7 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee_name,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
})
|
||||
@@ -1301,7 +1364,7 @@ def _extract_python_rationale(path: Path, result: dict) -> None:
|
||||
except Exception:
|
||||
return
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes = result["nodes"]
|
||||
edges = result["edges"]
|
||||
@@ -1560,7 +1623,7 @@ def extract_verilog(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -1647,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)
|
||||
@@ -1676,7 +1870,7 @@ def extract_julia(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -1888,7 +2082,7 @@ def extract_go(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
# Use directory name as package scope so methods on the same type across
|
||||
# multiple files in a package share one canonical type node.
|
||||
pkg_scope = path.parent.name or stem
|
||||
@@ -1897,6 +2091,7 @@ def extract_go(path: Path) -> dict:
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
function_bodies: list[tuple[str, object]] = []
|
||||
go_imported_pkgs: set[str] = set() # local names of imported packages
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
@@ -1994,12 +2189,21 @@ def extract_go(path: Path) -> dict:
|
||||
# don't collide with local files of the same basename.
|
||||
tgt_nid = _make_id("go", "pkg", raw)
|
||||
add_edge(file_nid, tgt_nid, "imports_from", spec.start_point[0] + 1)
|
||||
# Track local name (alias or last path segment)
|
||||
alias = spec.child_by_field_name("name")
|
||||
local_name = _read_text(alias, source) if alias else raw.split("/")[-1]
|
||||
if local_name and local_name != "_" and local_name != ".":
|
||||
go_imported_pkgs.add(local_name)
|
||||
elif child.type == "import_spec":
|
||||
path_node = child.child_by_field_name("path")
|
||||
if path_node:
|
||||
raw = _read_text(path_node, source).strip('"')
|
||||
tgt_nid = _make_id("go", "pkg", raw)
|
||||
add_edge(file_nid, tgt_nid, "imports_from", child.start_point[0] + 1)
|
||||
alias = child.child_by_field_name("name")
|
||||
local_name = _read_text(alias, source) if alias else raw.split("/")[-1]
|
||||
if local_name and local_name != "_" and local_name != ".":
|
||||
go_imported_pkgs.add(local_name)
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
@@ -2022,11 +2226,17 @@ def extract_go(path: Path) -> dict:
|
||||
if node.type == "call_expression":
|
||||
func_node = node.child_by_field_name("function")
|
||||
callee_name: str | None = None
|
||||
is_member_call: bool = False
|
||||
if func_node:
|
||||
if func_node.type == "identifier":
|
||||
callee_name = _read_text(func_node, source)
|
||||
elif func_node.type == "selector_expression":
|
||||
field = func_node.child_by_field_name("field")
|
||||
operand = func_node.child_by_field_name("operand")
|
||||
receiver_name = _read_text(operand, source) if operand else ""
|
||||
# Package-qualified call (e.g. fmt.Println) → allow cross-file resolution.
|
||||
# Receiver method call (e.g. s.logger.Log) → skip, no import evidence.
|
||||
is_member_call = receiver_name not in go_imported_pkgs
|
||||
if field:
|
||||
callee_name = _read_text(field, source)
|
||||
if callee_name:
|
||||
@@ -2049,6 +2259,7 @@ def extract_go(path: Path) -> dict:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee_name,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
})
|
||||
@@ -2087,7 +2298,7 @@ def extract_rust(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -2195,10 +2406,12 @@ def extract_rust(path: Path) -> dict:
|
||||
if node.type == "call_expression":
|
||||
func_node = node.child_by_field_name("function")
|
||||
callee_name: str | None = None
|
||||
is_member_call: bool = False
|
||||
if func_node:
|
||||
if func_node.type == "identifier":
|
||||
callee_name = _read_text(func_node, source)
|
||||
elif func_node.type == "field_expression":
|
||||
is_member_call = True
|
||||
field = func_node.child_by_field_name("field")
|
||||
if field:
|
||||
callee_name = _read_text(field, source)
|
||||
@@ -2226,6 +2439,7 @@ def extract_rust(path: Path) -> dict:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee_name,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
})
|
||||
@@ -2264,7 +2478,7 @@ def extract_zig(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -2380,7 +2594,9 @@ def extract_zig(path: Path) -> dict:
|
||||
if node.type == "call_expression":
|
||||
fn = node.child_by_field_name("function")
|
||||
if fn:
|
||||
callee = _read_text(fn, source).split(".")[-1]
|
||||
fn_text = _read_text(fn, source)
|
||||
callee = fn_text.split(".")[-1]
|
||||
is_member_call = "." in fn_text
|
||||
tgt_nid = next((n["id"] for n in nodes if n["label"] in
|
||||
(f"{callee}()", f".{callee}()")), None)
|
||||
if tgt_nid and tgt_nid != caller_nid:
|
||||
@@ -2394,6 +2610,7 @@ def extract_zig(path: Path) -> dict:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
})
|
||||
@@ -2427,7 +2644,7 @@ def extract_powershell(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -2558,6 +2775,7 @@ def extract_powershell(path: Path) -> dict:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": cmd_text,
|
||||
"is_member_call": False,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
})
|
||||
@@ -2621,7 +2839,7 @@ def _resolve_cross_file_imports(
|
||||
stem_to_path: dict[str, Path] = {p.stem: p for p in paths}
|
||||
|
||||
for file_result, path in zip(per_file, paths):
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
|
||||
# Find all classes defined in this file (the importers)
|
||||
@@ -2745,7 +2963,7 @@ def _resolve_cross_file_java_imports(
|
||||
new_edges: list[dict] = []
|
||||
seen_pairs: set[tuple[str, str]] = set()
|
||||
for path in paths:
|
||||
file_nid = _make_id(path.stem)
|
||||
file_nid = _make_id(str(path))
|
||||
try:
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
@@ -2809,7 +3027,7 @@ def extract_objc(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -3007,7 +3225,7 @@ def extract_elixir(path: Path) -> dict:
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = path.stem
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
@@ -3139,8 +3357,10 @@ def extract_elixir(path: Path) -> dict:
|
||||
return
|
||||
break
|
||||
callee_name: str | None = None
|
||||
is_member_call: bool = False
|
||||
for child in node.children:
|
||||
if child.type == "dot":
|
||||
is_member_call = True
|
||||
dot_text = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
|
||||
parts = dot_text.rstrip(".").split(".")
|
||||
if parts:
|
||||
@@ -3161,6 +3381,7 @@ def extract_elixir(path: Path) -> dict:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee_name,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
})
|
||||
@@ -3269,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)
|
||||
@@ -3358,6 +3580,10 @@ def extract(paths: list[Path], cache_root: Path | None = None) -> dict:
|
||||
callee = rc.get("callee", "")
|
||||
if not callee:
|
||||
continue
|
||||
# Skip member-call callees: obj.log() → "log" has no import evidence
|
||||
# and collides with any top-level function named "log" in the corpus.
|
||||
if rc.get("is_member_call"):
|
||||
continue
|
||||
tgt = global_label_to_nid.get(callee.lower())
|
||||
caller = rc["caller_nid"]
|
||||
if tgt and tgt != caller and (caller, tgt) not in existing_pairs:
|
||||
@@ -3373,6 +3599,19 @@ def extract(paths: list[Path], cache_root: Path | None = None) -> dict:
|
||||
"weight": 1.0,
|
||||
})
|
||||
|
||||
# Relativize source_file fields so paths are portable across machines (#555)
|
||||
for item in all_nodes + all_edges:
|
||||
sf = item.get("source_file")
|
||||
if not sf:
|
||||
continue
|
||||
sf_path = Path(sf)
|
||||
if not sf_path.is_absolute():
|
||||
continue
|
||||
try:
|
||||
item["source_file"] = str(sf_path.relative_to(root))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return {
|
||||
"nodes": all_nodes,
|
||||
"edges": all_edges,
|
||||
|
||||
+1
-1
@@ -145,7 +145,7 @@ def _hooks_dir(root: Path) -> Path:
|
||||
if result.returncode == 0:
|
||||
custom = result.stdout.strip()
|
||||
if custom:
|
||||
p = Path(custom)
|
||||
p = Path(custom).expanduser()
|
||||
if not p.is_absolute():
|
||||
p = root / p
|
||||
p.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
+8
-11
@@ -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]
|
||||
|
||||
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
# Direct LLM backend for semantic extraction — supports Claude and Kimi K2.6.
|
||||
# Used by `graphify . --backend kimi` and the benchmark scripts.
|
||||
# The default graphify pipeline uses Claude Code subagents via skill.md;
|
||||
# this module provides a direct API path for non-Claude-Code environments.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
BACKENDS: dict[str, dict] = {
|
||||
"claude": {
|
||||
"base_url": "https://api.anthropic.com",
|
||||
"default_model": "claude-sonnet-4-6",
|
||||
"env_key": "ANTHROPIC_API_KEY",
|
||||
"pricing": {"input": 3.0, "output": 15.0}, # USD per 1M tokens
|
||||
"temperature": 0,
|
||||
},
|
||||
"kimi": {
|
||||
"base_url": "https://api.moonshot.ai/v1",
|
||||
"default_model": "kimi-k2.6",
|
||||
"env_key": "MOONSHOT_API_KEY",
|
||||
"pricing": {"input": 0.74, "output": 4.66}, # USD per 1M tokens
|
||||
"temperature": None, # kimi-k2.6 enforces its own fixed temperature; sending any value raises 400
|
||||
},
|
||||
}
|
||||
|
||||
_EXTRACTION_SYSTEM = """\
|
||||
You are a graphify semantic extraction agent. Extract a knowledge graph fragment from the files provided.
|
||||
Output ONLY valid JSON — no explanation, no markdown fences, no preamble.
|
||||
|
||||
Rules:
|
||||
- EXTRACTED: relationship explicit in source (import, call, citation, reference)
|
||||
- INFERRED: reasonable inference (shared data structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain — flag for review, do not omit
|
||||
|
||||
Node ID format: lowercase, only [a-z0-9_], no dots or slashes.
|
||||
Format: {stem}_{entity} where stem = filename without extension, entity = symbol name (both normalised).
|
||||
|
||||
Output exactly this schema:
|
||||
{"nodes":[{"id":"stem_entity","label":"Human Readable Name","file_type":"code|document|paper|image|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[],"input_tokens":0,"output_tokens":0}
|
||||
"""
|
||||
|
||||
|
||||
def _read_files(paths: list[Path], root: Path) -> str:
|
||||
"""Return file contents formatted for the extraction prompt."""
|
||||
parts: list[str] = []
|
||||
for p in paths:
|
||||
try:
|
||||
rel = p.relative_to(root)
|
||||
except ValueError:
|
||||
rel = p
|
||||
try:
|
||||
content = p.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
continue
|
||||
parts.append(f"=== {rel} ===\n{content[:20000]}")
|
||||
return "\n\n".join(parts)
|
||||
|
||||
|
||||
def _parse_llm_json(raw: str) -> dict:
|
||||
"""Strip optional markdown fences and parse JSON. Returns empty fragment on failure."""
|
||||
if raw.startswith("```"):
|
||||
raw = raw.split("```", 2)[1]
|
||||
if raw.startswith("json"):
|
||||
raw = raw[4:]
|
||||
raw = raw.rsplit("```", 1)[0]
|
||||
try:
|
||||
return json.loads(raw.strip())
|
||||
except json.JSONDecodeError as exc:
|
||||
print(f"[graphify] LLM returned invalid JSON, skipping chunk: {exc}", file=sys.stderr)
|
||||
return {"nodes": [], "edges": [], "hyperedges": []}
|
||||
|
||||
|
||||
def _call_openai_compat(
|
||||
base_url: str,
|
||||
api_key: str,
|
||||
model: str,
|
||||
user_message: str,
|
||||
temperature: float | None = 0,
|
||||
) -> dict:
|
||||
"""Call any OpenAI-compatible API (Kimi, OpenAI, etc.) and return parsed JSON."""
|
||||
try:
|
||||
from openai import OpenAI
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Kimi/OpenAI-compatible extraction requires the openai package. "
|
||||
"Run: pip install openai"
|
||||
) from exc
|
||||
|
||||
client = OpenAI(api_key=api_key, base_url=base_url)
|
||||
kwargs: dict = {
|
||||
"model": model,
|
||||
"messages": [
|
||||
{"role": "system", "content": _EXTRACTION_SYSTEM},
|
||||
{"role": "user", "content": user_message},
|
||||
],
|
||||
"max_completion_tokens": 8192,
|
||||
}
|
||||
if temperature is not None:
|
||||
kwargs["temperature"] = temperature
|
||||
# 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
|
||||
result["output_tokens"] = resp.usage.completion_tokens if resp.usage else 0
|
||||
result["model"] = model
|
||||
return result
|
||||
|
||||
|
||||
def _call_claude(api_key: str, model: str, user_message: str) -> dict:
|
||||
"""Call Anthropic Claude directly (not via OpenAI compat layer)."""
|
||||
try:
|
||||
import anthropic
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Claude direct extraction requires the anthropic package. "
|
||||
"Run: pip install anthropic"
|
||||
) from exc
|
||||
|
||||
client = anthropic.Anthropic(api_key=api_key)
|
||||
resp = client.messages.create(
|
||||
model=model,
|
||||
max_tokens=8192,
|
||||
system=_EXTRACTION_SYSTEM,
|
||||
messages=[{"role": "user", "content": user_message}],
|
||||
)
|
||||
result = _parse_llm_json(resp.content[0].text if resp.content else "{}")
|
||||
result["input_tokens"] = resp.usage.input_tokens if resp.usage else 0
|
||||
result["output_tokens"] = resp.usage.output_tokens if resp.usage else 0
|
||||
result["model"] = model
|
||||
return result
|
||||
|
||||
|
||||
def extract_files_direct(
|
||||
files: list[Path],
|
||||
backend: str = "kimi",
|
||||
api_key: str | None = None,
|
||||
model: str | None = None,
|
||||
root: Path = Path("."),
|
||||
) -> dict:
|
||||
"""Extract semantic nodes/edges from a list of files using the given backend.
|
||||
|
||||
Returns dict with nodes, edges, hyperedges, input_tokens, output_tokens.
|
||||
Raises ValueError for unknown backends. Raises ImportError if SDK missing.
|
||||
"""
|
||||
if backend not in BACKENDS:
|
||||
raise ValueError(f"Unknown backend {backend!r}. Available: {sorted(BACKENDS)}")
|
||||
|
||||
cfg = BACKENDS[backend]
|
||||
key = api_key or os.environ.get(cfg["env_key"], "")
|
||||
if not key:
|
||||
raise ValueError(
|
||||
f"No API key for backend '{backend}'. "
|
||||
f"Set {cfg['env_key']} or pass api_key=."
|
||||
)
|
||||
mdl = model or cfg["default_model"]
|
||||
user_msg = _read_files(files, root)
|
||||
|
||||
if backend == "claude":
|
||||
return _call_claude(key, mdl, user_msg)
|
||||
else:
|
||||
return _call_openai_compat(cfg["base_url"], key, mdl, user_msg, temperature=cfg.get("temperature", 0))
|
||||
|
||||
|
||||
def extract_corpus_parallel(
|
||||
files: list[Path],
|
||||
backend: str = "kimi",
|
||||
api_key: str | None = None,
|
||||
model: str | None = None,
|
||||
root: Path = Path("."),
|
||||
chunk_size: int = 20,
|
||||
on_chunk_done: Callable | None = None,
|
||||
) -> dict:
|
||||
"""Extract a corpus in chunks, merging results.
|
||||
|
||||
on_chunk_done(idx, total, chunk_result) is called after each chunk if provided.
|
||||
Returns merged dict with nodes, edges, hyperedges, input_tokens, output_tokens.
|
||||
"""
|
||||
chunks = [files[i:i + chunk_size] for i in range(0, len(files), chunk_size)]
|
||||
merged: dict = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
|
||||
for idx, chunk in enumerate(chunks):
|
||||
t0 = time.time()
|
||||
result = extract_files_direct(chunk, backend=backend, api_key=api_key, model=model, root=root)
|
||||
result["elapsed_seconds"] = round(time.time() - t0, 2)
|
||||
merged["nodes"].extend(result.get("nodes", []))
|
||||
merged["edges"].extend(result.get("edges", []))
|
||||
merged["hyperedges"].extend(result.get("hyperedges", []))
|
||||
merged["input_tokens"] += result.get("input_tokens", 0)
|
||||
merged["output_tokens"] += result.get("output_tokens", 0)
|
||||
if callable(on_chunk_done):
|
||||
on_chunk_done(idx, len(chunks), result)
|
||||
|
||||
return merged
|
||||
|
||||
|
||||
def estimate_cost(backend: str, input_tokens: int, output_tokens: int) -> float:
|
||||
"""Estimate USD cost for a given token count using published pricing."""
|
||||
if backend not in BACKENDS:
|
||||
return 0.0
|
||||
p = BACKENDS[backend]["pricing"]
|
||||
return (input_tokens * p["input"] + output_tokens * p["output"]) / 1_000_000
|
||||
|
||||
|
||||
def detect_backend() -> str | None:
|
||||
"""Return the name of whichever backend has an API key set, or None.
|
||||
|
||||
Kimi is checked first (opt-in). Falls back to Claude if ANTHROPIC_API_KEY is set.
|
||||
Claude is the default for the skill.md subagent pipeline and is never forced here.
|
||||
"""
|
||||
if os.environ.get("MOONSHOT_API_KEY"):
|
||||
return "kimi"
|
||||
if os.environ.get("ANTHROPIC_API_KEY"):
|
||||
return "claude"
|
||||
return None
|
||||
+37
-3
@@ -1,6 +1,7 @@
|
||||
# Security helpers - URL validation, safe fetch, path guards, label sanitisation
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import html
|
||||
import re
|
||||
import urllib.error
|
||||
@@ -58,12 +59,45 @@ def validate_url(url: str) -> str:
|
||||
f"Blocked private/internal IP {addr} (resolved from '{hostname}'). "
|
||||
f"Got: {url!r}"
|
||||
)
|
||||
except socket.gaierror:
|
||||
pass # DNS failure will surface later during fetch
|
||||
except socket.gaierror as exc:
|
||||
raise ValueError(
|
||||
f"DNS resolution failed for '{hostname}': {exc}. Got: {url!r}"
|
||||
) from exc
|
||||
|
||||
return url
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _ssrf_guarded_socket():
|
||||
"""Patch socket.getaddrinfo for the duration of a fetch to catch DNS rebinding.
|
||||
|
||||
Validates every IP that urllib resolves so a DNS server cannot return a public IP
|
||||
for validate_url and swap to a private IP for the actual connection (TOCTOU fix).
|
||||
Not thread-safe, but graphify is a single-threaded CLI tool.
|
||||
"""
|
||||
original = socket.getaddrinfo
|
||||
|
||||
def _guarded(host, port, *args, **kwargs):
|
||||
results = original(host, port, *args, **kwargs)
|
||||
for info in results:
|
||||
addr = info[4][0]
|
||||
try:
|
||||
ip = ipaddress.ip_address(addr)
|
||||
except ValueError:
|
||||
continue
|
||||
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local:
|
||||
raise OSError(
|
||||
f"SSRF blocked: IP {addr} resolved from '{host}' is private/reserved"
|
||||
)
|
||||
return results
|
||||
|
||||
socket.getaddrinfo = _guarded
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
socket.getaddrinfo = original
|
||||
|
||||
|
||||
class _NoFileRedirectHandler(urllib.request.HTTPRedirectHandler):
|
||||
"""Redirect handler that re-validates every redirect target.
|
||||
|
||||
@@ -104,7 +138,7 @@ def safe_fetch(url: str, max_bytes: int = _MAX_FETCH_BYTES, timeout: int = 30) -
|
||||
opener = _build_opener()
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 graphify/1.0"})
|
||||
|
||||
with opener.open(req, timeout=timeout) as resp:
|
||||
with _ssrf_guarded_socket(), opener.open(req, timeout=timeout) as resp:
|
||||
# urllib raises HTTPError for non-2xx when using urlopen directly;
|
||||
# with a custom opener we check manually to be safe.
|
||||
status = getattr(resp, "status", None) or getattr(resp, "code", None)
|
||||
|
||||
+17
-4
@@ -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()
|
||||
|
||||
@@ -235,7 +235,7 @@ Process each file one at a time. For each file:
|
||||
- INFERRED: reasonable inference (shared structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain — flag it, do not omit
|
||||
- Code files: semantic edges AST cannot find. Do not re-extract imports.
|
||||
- Doc/paper files: named concepts, entities, citations, and rationale nodes (WHY decisions were made → `rationale_for` edges)
|
||||
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. When adding `calls` edges: source is caller, target is callee.
|
||||
- Image files: use vision — understand what the image IS, not just OCR
|
||||
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
|
||||
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
|
||||
|
||||
@@ -235,7 +235,7 @@ Process each file one at a time. For each file:
|
||||
- INFERRED: reasonable inference (shared structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain — flag it, do not omit
|
||||
- Code files: semantic edges AST cannot find. Do not re-extract imports.
|
||||
- Doc/paper files: named concepts, entities, citations, and rationale nodes (WHY decisions were made → `rationale_for` edges)
|
||||
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. When adding `calls` edges: source is caller, target is callee.
|
||||
- Image files: use vision — understand what the image IS, not just OCR
|
||||
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
|
||||
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
|
||||
|
||||
@@ -263,7 +263,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
|
||||
@@ -259,7 +259,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
|
||||
@@ -260,7 +260,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
|
||||
@@ -234,7 +234,7 @@ Process each file one at a time. For each file:
|
||||
- INFERRED: reasonable inference (shared structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain — flag it, do not omit
|
||||
- Code files: semantic edges AST cannot find. Do not re-extract imports.
|
||||
- Doc/paper files: named concepts, entities, citations, and rationale nodes (WHY decisions were made → `rationale_for` edges)
|
||||
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. When adding `calls` edges: source is caller, target is callee.
|
||||
- Image files: use vision — understand what the image IS, not just OCR
|
||||
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
|
||||
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
|
||||
|
||||
@@ -261,7 +261,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
|
||||
@@ -250,7 +250,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
|
||||
@@ -249,7 +249,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
|
||||
+41
-5
@@ -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
|
||||
---
|
||||
|
||||
@@ -13,6 +13,9 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
```
|
||||
/graphify # full pipeline on current directory → Obsidian vault
|
||||
/graphify <path> # full pipeline on specific path
|
||||
/graphify https://github.com/<owner>/<repo> # clone repo then run full pipeline on it
|
||||
/graphify https://github.com/<owner>/<repo> --branch <branch> # clone a specific branch
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
@@ -57,8 +60,33 @@ Use it for:
|
||||
|
||||
If no path was given, use `.` (current directory). Do not ask the user for a path.
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL — run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
|
||||
### Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given)
|
||||
|
||||
**Single repo:**
|
||||
```bash
|
||||
LOCAL_PATH=$(graphify clone <github-url> [--branch <branch>])
|
||||
# Use LOCAL_PATH as the target for all subsequent steps
|
||||
```
|
||||
|
||||
**Multiple repos (cross-repo graph):**
|
||||
```bash
|
||||
# Clone each repo, run the full pipeline on each, then merge
|
||||
graphify clone <url1> # → ~/.graphify/repos/<owner1>/<repo1>
|
||||
graphify clone <url2> # → ~/.graphify/repos/<owner2>/<repo2>
|
||||
# Run /graphify on each local path to produce their graph.json files
|
||||
# Then merge:
|
||||
graphify merge-graphs \
|
||||
~/.graphify/repos/<owner1>/<repo1>/graphify-out/graph.json \
|
||||
~/.graphify/repos/<owner2>/<repo2>/graphify-out/graph.json \
|
||||
--out graphify-out/cross-repo-graph.json
|
||||
```
|
||||
|
||||
Graphify clones into `~/.graphify/repos/<owner>/<repo>` and reuses existing clones on repeat runs. Each node in the merged graph carries a `repo` attribute so you can filter by origin.
|
||||
|
||||
### Step 1 - Ensure graphify is installed
|
||||
|
||||
```bash
|
||||
@@ -84,6 +112,8 @@ if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
|
||||
# Write interpreter path for all subsequent steps (persists across invocations)
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
# Save scan root so `graphify update` (no args) knows where to look next time
|
||||
echo "$(cd INPUT_PATH && pwd)" > graphify-out/.graphify_root
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
@@ -170,7 +200,12 @@ After transcription:
|
||||
|
||||
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
|
||||
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens).
|
||||
|
||||
**Before dispatching subagents:** check whether `MOONSHOT_API_KEY` is set. If it is NOT set, print this one-liner to the user:
|
||||
> Tip: set `MOONSHOT_API_KEY` to use Kimi K2.6 for semantic extraction — 3x cheaper, richer graphs (`pip install 'graphifyy[kimi]'`).
|
||||
|
||||
Print it once, then continue. If `MOONSHOT_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="kimi")` for semantic extraction instead of dispatching Claude subagents.
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
@@ -272,7 +307,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
@@ -307,7 +343,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
|
||||
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.
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the filename without extension and entity is the symbol name, both normalized (lowercase, non-alphanumeric chars replaced with `_`). Example: `src/auth/session.py` + `ValidateToken` → `session_validatetoken`. This must match the ID the AST extractor generates so cross-references between code and semantic nodes connect correctly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
@@ -768,7 +804,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
|
||||
"
|
||||
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_labels.json graphify-out/.graphify_chunk_*.json
|
||||
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
|
||||
@@ -51,6 +51,8 @@ def download_audio(url: str, output_dir: Path) -> Path:
|
||||
Returns the path to the downloaded audio file (.m4a or .opus).
|
||||
Uses cached file if already downloaded.
|
||||
"""
|
||||
from graphify.security import validate_url
|
||||
validate_url(url) # blocks private IPs, bad schemes before yt-dlp runs
|
||||
yt_dlp = _get_yt_dlp()
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# validate extraction JSON against the graphify schema before graph assembly
|
||||
from __future__ import annotations
|
||||
|
||||
VALID_FILE_TYPES = {"code", "document", "paper", "image", "rationale"}
|
||||
VALID_FILE_TYPES = {"code", "document", "paper", "image", "rationale", "concept"}
|
||||
VALID_CONFIDENCES = {"EXTRACTED", "INFERRED", "AMBIGUOUS"}
|
||||
REQUIRED_NODE_FIELDS = {"id", "label", "file_type", "source_file"}
|
||||
REQUIRED_EDGE_FIELDS = {"source", "target", "relation", "confidence", "source_file"}
|
||||
|
||||
+11
-1
@@ -98,11 +98,21 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
out.mkdir(exist_ok=True)
|
||||
(out / ".graphify_root").write_text(str(watch_root), encoding="utf-8")
|
||||
|
||||
json_written = to_json(G, communities, str(out / "graph.json"))
|
||||
if not json_written:
|
||||
return False
|
||||
|
||||
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")
|
||||
to_json(G, communities, str(out / "graph.json"))
|
||||
|
||||
# to_html raises ValueError for graphs > MAX_NODES_FOR_VIZ (5000).
|
||||
# Wrap so core outputs (graph.json + GRAPH_REPORT.md) always land.
|
||||
|
||||
+6
-4
@@ -4,12 +4,12 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "graphifyy"
|
||||
version = "0.4.31"
|
||||
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" }
|
||||
keywords = ["claude", "claude-code", "codex", "opencode", "cursor", "gemini", "aider", "kiro", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
|
||||
requires-python = ">=3.10,<3.14"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"networkx",
|
||||
"tree-sitter>=0.23.0",
|
||||
@@ -44,13 +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"]
|
||||
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper", "yt-dlp", "matplotlib"]
|
||||
kimi = ["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"
|
||||
|
||||
Vendored
+19
@@ -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;
|
||||
+5
-3
@@ -67,11 +67,13 @@ def test_cached_files(tmp_path, cache_root):
|
||||
|
||||
|
||||
def test_clear_cache(tmp_file, cache_root):
|
||||
"""clear_cache removes all .json files from graphify-out/cache/."""
|
||||
"""clear_cache removes all .json files from graphify-out/cache/ (all subdirs)."""
|
||||
save_cached(tmp_file, {"nodes": [], "edges": []}, root=cache_root)
|
||||
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) > 0
|
||||
# Since v0.5.3 entries go into cache/ast/, not the flat cache/ dir
|
||||
cache_base = cache_root / "graphify-out" / "cache"
|
||||
assert len(list(cache_base.rglob("*.json"))) > 0
|
||||
clear_cache(cache_root)
|
||||
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) == 0
|
||||
assert len(list(cache_base.rglob("*.json"))) == 0
|
||||
|
||||
|
||||
def test_md_frontmatter_only_change_same_hash(tmp_path):
|
||||
|
||||
@@ -109,7 +109,7 @@ def test_install_creates_settings_json(tmp_path):
|
||||
assert settings_path.exists()
|
||||
settings = json.loads(settings_path.read_text())
|
||||
hooks = settings.get("hooks", {}).get("PreToolUse", [])
|
||||
assert any("Glob|Grep" in h.get("matcher", "") for h in hooks)
|
||||
assert any(h.get("matcher") == "Bash" for h in hooks)
|
||||
|
||||
|
||||
def test_install_settings_json_idempotent(tmp_path):
|
||||
@@ -120,8 +120,8 @@ def test_install_settings_json_idempotent(tmp_path):
|
||||
settings_path = tmp_path / ".claude" / "settings.json"
|
||||
settings = json.loads(settings_path.read_text())
|
||||
hooks = settings.get("hooks", {}).get("PreToolUse", [])
|
||||
glob_grep_hooks = [h for h in hooks if "Glob|Grep" in h.get("matcher", "")]
|
||||
assert len(glob_grep_hooks) == 1
|
||||
bash_hooks = [h for h in hooks if h.get("matcher") == "Bash" and "graphify" in str(h)]
|
||||
assert len(bash_hooks) == 1
|
||||
|
||||
|
||||
def test_uninstall_removes_settings_hook(tmp_path):
|
||||
@@ -133,4 +133,4 @@ def test_uninstall_removes_settings_hook(tmp_path):
|
||||
if settings_path.exists():
|
||||
settings = json.loads(settings_path.read_text())
|
||||
hooks = settings.get("hooks", {}).get("PreToolUse", [])
|
||||
assert not any("Glob|Grep" in h.get("matcher", "") for h in hooks)
|
||||
assert not any(h.get("matcher") == "Bash" and "graphify" in str(h) for h in hooks)
|
||||
+21
-2
@@ -138,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)
|
||||
|
||||
+37
-2
@@ -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']}"
|
||||
Reference in new issue
Block a user