Compare commits

...
29 Commits
Author SHA1 Message Date
Safi 47a994ad5b bump to v0.5.7 2026-04-30 22:34:08 +01:00
SafiandClaude Sonnet 4.6 5aaa268650 add yaml/yml to DOC_EXTENSIONS so k8s/kustomize corpora are indexed (fixes #633)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-30 22:32:22 +01:00
Safi 3755fdc885 swap downloads badge back to pepy.tech 2026-04-30 09:48:37 +01:00
Safi 4e871ad36c swap downloads badge to shields.io for cache refresh 2026-04-30 09:47:55 +01:00
SafiandClaude Sonnet 4.6 97099edc38 bump to v0.5.6
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-30 09:01:35 +01:00
SafiandClaude Sonnet 4.6 4360f9644b move changelog out of README into CHANGELOG.md, add yt-dlp legal notice
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 22:44:12 +01:00
SafiandClaude Sonnet 4.6 f755aca58f fix kimi temperature 400 error and community label deletion on cleanup (fixes #610, #608)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 17:03:44 +01:00
SafiandClaude Sonnet 4.6 28b17d37f1 remove Python upper bound to support 3.14+ (fixes #607)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 13:33:41 +01:00
SafiandClaude Sonnet 4.6 326c03e132 remove product-site from graphify repo
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 12:28:30 +01:00
SafiandClaude Sonnet 4.6 44fc32e3e2 add product-site as part of graphify repo (was separate submodule)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 12:27:56 +01:00
SafiandClaude Sonnet 4.6 744827166e update product site: fix pip install package name to graphifyy, update stats to 38k stars / 400k+ downloads / 1900+ waitlist
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 12:26:00 +01:00
SafiandClaude Sonnet 4.6 c750582db4 fix SyntaxWarning: use raw string for shell glob pattern with backslash escapes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 10:02:56 +01:00
SafiandClaude Sonnet 4.6 71d1b394e9 fix NameError in Kimi tip: use module-level os import instead of _os
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 09:58:54 +01:00
Safi a4ad901284 Update v0.5.5 release notes in README 2026-04-29 09:48:55 +01:00
SafiandClaude Sonnet 4.6 f9c344b546 Remember scan root so graphify update works without a path arg
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 09:43:51 +01:00
SafiandClaude Sonnet 4.6 59cbad3937 Fix Go package-call false-negative and llm.py robustness
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 08:57:16 +01:00
SafiandClaude Sonnet 4.6 5904081d7a Add Kimi K2.6 backend, fix phantom god nodes (#598), fix concept file_type (#601)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 08:51:53 +01:00
Safi eceaaad61e Add v0.5.4 release notes to README 2026-04-28 15:06:26 +01:00
SafiandClaude Sonnet 4.6 dd86271312 Fix SSRF DNS rebinding TOCTOU and yt-dlp URL bypass (#591, #592)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 15:04:52 +01:00
SafiandClaude Sonnet 4.6 7359cdace9 Fix AST/semantic cache namespace collision breaking graphify update (#582)
AST and semantic entries now write to cache/ast/ and cache/semantic/
respectively. Previously both used the flat cache/ dir causing semantic
results to overwrite AST entries for code files on mixed corpora, making
the shrink guard fire on every subsequent update run.

Migration: load_cached falls back to legacy flat cache/ for AST reads
so existing cache entries are not lost on upgrade.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 11:22:39 +01:00
SafiandClaude Sonnet 4.6 ee1df22b25 Fix PreToolUse hook for Claude Code v2.1.117+ (Glob|Grep → Bash matcher)
Grep and Glob tools removed in CC v2.1.117; searches now go through Bash.
Hook now reads stdin tool_input and pattern-matches on search commands.
Uninstall/reinstall handles both old and new matcher for clean upgrades.

Closes #578

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 00:56:54 +01:00
SafiandClaude Sonnet 4.6 a566bfb566 Bump to v0.5.1
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 21:45:57 +01:00
SafiandClaude Sonnet 4.6 4563b043f2 Fix 6 bugs: ID collisions, path portability, alias resolution, HTML controls, desync guard, rationale prompt
- #550: _file_stem() includes parent dir to prevent node ID collisions for same-named files
- #555: extract() relativizes source_file paths before returning for cross-machine portability
- #562: to_json() returns bool; _rebuild_code() writes report/html only if json succeeded
- #563: skill prompts store rationale as node attribute, not separate node; enforce calls direction
- #566: Show All / Hide All buttons added to HTML community panel
- #575: _import_js() resolves tsconfig.json compilerOptions.paths aliases before external fallback

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 21:44:22 +01:00
Safi 6175e0a8ea fix #547 #559 #570: expand ~ in hooksPath, fix gitignore inline comments, nosec on write sinks 2026-04-27 21:27:26 +01:00
Safi 770d7f54c4 Add The Memory Layer book badge to README 2026-04-25 15:56:59 +01:00
Safi 8bed332ff4 release: bump to v0.5.0 — clone, merge-graphs, shrink guard, dedup, bug fixes 2026-04-23 20:09:03 +01:00
Safi df9b7ec54f fix #479 #451: build_merge(), pre-write shrink guard, label dedup, chunk-suffix prompt block 2026-04-23 20:04:43 +01:00
Safi 2faeed99a2 feat: cross-repo merge-graphs; fix #527 CLAUDE_CONFIG_DIR; fix #524 graphify-out excluded from source scan 2026-04-23 19:59:14 +01:00
Safi 2c49da24f0 feat: graphify clone <github-url> — clone any repo and run full pipeline on it 2026-04-23 19:49:56 +01:00
27 changed files with 908 additions and 92 deletions

No files matched your search

+51
View File
@@ -2,6 +2,57 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
## 0.5.7 (2026-04-30)
- Feat: YAML/YML files now indexed for semantic extraction — Kubernetes, Kustomize, Helm, and any YAML corpus now picked up automatically (#633)
## 0.5.6 (2026-04-30)
- Fix: `NameError: name '_os' is not defined` crash after `graphify update` — this was fixed in v5 branch but not released to PyPI (#618, #612)
## 0.5.5 (2026-04-29)
- Feat: Kimi K2.6 backend — `pip install 'graphifyy[kimi]'` + `MOONSHOT_API_KEY` routes semantic extraction through Kimi K2.6. 3-6x richer relation extraction at ~3x lower cost. Claude remains default; Kimi is opt-in.
- Fix: phantom god nodes (#598) — member-call callees (`this.logger.log()` → `log`) no longer cross-file resolved. Go package-qualified calls (`pkg.Func()`) correctly preserved. Affects JS/TS, Go, Rust, Swift, Kotlin, Scala, PHP, C++, C#, Zig, Elixir.
- Fix: `concept` file_type no longer triggers validation warnings (#601)
- Fix: `graphify update` remembers scan root via `graphify-out/.graphify_root` — no path argument needed on subsequent runs
- Fix: Kimi K2.6 temperature 400 error — temperature param is now skipped for Kimi backends (model enforces its own fixed value) (#610)
- Fix: community labels deleted in Step 9 cleanup — `.graphify_labels.json` is now preserved so wiki/obsidian/HTML retain human-readable names after re-cluster (#608)
- Fix: `NameError: name '_os' is not defined` in `graphify update` Kimi tip (#612)
- Fix: `SyntaxWarning` in `__main__.py` for shell glob pattern with backslash escapes
- Fix: Python upper bound removed — `requires-python = ">=3.10"` now supports Python 3.14+ (#607)
## 0.5.4 (2026-04-28)
- Fix: SSRF DNS rebinding — `safe_fetch` now patches `socket.getaddrinfo` for the full request duration (#591)
- Fix: yt-dlp SSRF bypass — `download_audio` now calls `validate_url` before handing URL to yt-dlp (#592)
## 0.5.3 (2026-04-27)
- Fix: cache namespace — AST and semantic entries now live in `cache/ast/` and `cache/semantic/` subdirectories; flat entries read as migration fallback
## 0.5.2 (2026-04-26)
- Fix: PreToolUse hook now matches on `Bash` instead of `Glob|Grep` for Claude Code v2.1.117+
## 0.5.1 (2026-04-25)
- Fix: node ID collision for same-named files in different directories
- Fix: `source_file` paths relativized before return so `graph.json` is portable
- Fix: desync guard — `to_json()` returns bool; report only written on successful JSON write
- Feat: TypeScript `@/` path aliases resolved via `tsconfig.json`
- Feat: Show All / Hide All buttons in HTML community panel
## 0.5.0 (2026-04-24)
- Feat: `graphify clone <github-url>` — clone and graph any public repo
- Feat: `graphify merge-graphs` — combine multiple `graph.json` outputs into one cross-repo graph
- Feat: `CLAUDE_CONFIG_DIR` support in `graphify install`
- Feat: shrink guard — `to_json()` refuses to overwrite with a smaller graph
- Feat: `build_merge()` for safe incremental updates
- Feat: duplicate node deduplication via `deduplicate_by_label()`
- Fix: `graphify-out/` excluded from source scanning
## 0.4.23 (2026-04-18)
- Fix: stale skill version warning persists after running `graphify install` when multiple platforms were previously installed — `graphify install` now refreshes `.graphify_version` in all other known skill directories so the warning clears across the board (#178)
+20 -3
View File
@@ -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>
@@ -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)
@@ -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)
+150 -8
View File
@@ -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,59 @@ def claude_uninstall(project_dir: Path | None = None) -> None:
_uninstall_claude_hook(project_dir or Path("."))
def _clone_repo(url: str, branch: str | None = None, out_dir: Path | None = None) -> Path:
"""Clone a GitHub repo to a local cache dir and return the path.
Clones into ~/.graphify/repos/<owner>/<repo> by default so repeated
runs on the same URL reuse the existing clone (git pull instead of clone).
"""
import subprocess as _sp
import re as _re
# Normalise URL — strip trailing .git if present
url = url.rstrip("/")
if not url.endswith(".git"):
git_url = url + ".git"
else:
git_url = url
url = url[:-4]
# Extract owner/repo from URL
m = _re.search(r"github\.com[:/]([^/]+)/([^/]+?)(?:\.git)?$", url)
if not m:
print(f"error: not a recognised GitHub URL: {url}", file=sys.stderr)
sys.exit(1)
owner, repo = m.group(1), m.group(2)
if out_dir:
dest = out_dir
else:
dest = Path.home() / ".graphify" / "repos" / owner / repo
if dest.exists():
print(f"Repo already cloned at {dest} — pulling latest...", flush=True)
cmd = ["git", "-C", str(dest), "pull"]
if branch:
cmd += ["origin", branch]
result = _sp.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
print(f"warning: git pull failed:\n{result.stderr}", file=sys.stderr)
else:
dest.parent.mkdir(parents=True, exist_ok=True)
print(f"Cloning {url} → {dest} ...", flush=True)
cmd = ["git", "clone", "--depth", "1"]
if branch:
cmd += ["--branch", branch]
cmd += [git_url, str(dest)]
result = _sp.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
print(f"error: git clone failed:\n{result.stderr}", file=sys.stderr)
sys.exit(1)
print(f"Ready at: {dest}", flush=True)
return dest
def main() -> None:
# Check all known skill install locations for a stale version stamp.
# Skip during install/uninstall (hook writes trigger a fresh check anyway).
@@ -923,6 +990,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")
@@ -1339,7 +1411,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 +1428,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 +1441,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"
+121
View File
@@ -21,8 +21,10 @@
# before any graph construction happens.
#
from __future__ import annotations
import json
import re
import sys
from pathlib import Path
import networkx as nx
from .validate import validate_extraction
@@ -50,6 +52,18 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
# Canonicalize legacy node/edge schema before validation.
for node in extraction.get("nodes", []):
if isinstance(node, dict) and "source" in node and "source_file" not in node:
# Count edges that reference this node so the warning is actionable (#479)
node_id = node.get("id", "?")
affected_edges = sum(
1 for e in extraction.get("edges", [])
if e.get("source") == node_id or e.get("target") == node_id
)
print(
f"[graphify] WARNING: node '{node_id}' uses field 'source' instead of "
f"'source_file' — {affected_edges} edge(s) may be misrouted. "
f"Rename the field to 'source_file' to silence this warning.",
file=sys.stderr,
)
node["source_file"] = node.pop("source")
errors = validate_extraction(extraction)
@@ -111,3 +125,110 @@ def build(extractions: list[dict], *, directed: bool = False) -> nx.Graph:
combined["input_tokens"] += ext.get("input_tokens", 0)
combined["output_tokens"] += ext.get("output_tokens", 0)
return build_from_json(combined, directed=directed)
def _norm_label(label: str) -> str:
"""Canonical dedup key — lowercase, alphanumeric only."""
return re.sub(r"[^a-z0-9 ]", "", label.lower()).strip()
def deduplicate_by_label(nodes: list[dict], edges: list[dict]) -> tuple[list[dict], list[dict]]:
"""Merge nodes that share a normalised label, rewriting edge references.
Prefers IDs without chunk suffixes (_c\\d+) and shorter IDs when tied.
Drops self-loops created by the merge. Called in build() automatically.
"""
_CHUNK_SUFFIX = re.compile(r"_c\d+$")
canonical: dict[str, dict] = {} # norm_label -> surviving node
remap: dict[str, str] = {} # old_id -> surviving_id
for node in nodes:
key = _norm_label(node.get("label", node.get("id", "")))
if not key:
continue
existing = canonical.get(key)
if existing is None:
canonical[key] = node
else:
has_suffix = bool(_CHUNK_SUFFIX.search(node["id"]))
existing_has_suffix = bool(_CHUNK_SUFFIX.search(existing["id"]))
if has_suffix and not existing_has_suffix:
remap[node["id"]] = existing["id"]
elif existing_has_suffix and not has_suffix:
remap[existing["id"]] = node["id"]
canonical[key] = node
elif len(node["id"]) < len(existing["id"]):
remap[existing["id"]] = node["id"]
canonical[key] = node
else:
remap[node["id"]] = existing["id"]
if not remap:
return nodes, edges
print(f"[graphify] Deduplicated {len(remap)} duplicate node(s) by label.", file=sys.stderr)
deduped_nodes = list(canonical.values())
deduped_edges = []
for edge in edges:
e = dict(edge)
e["source"] = remap.get(e["source"], e["source"])
e["target"] = remap.get(e["target"], e["target"])
if e["source"] != e["target"]:
deduped_edges.append(e)
return deduped_nodes, deduped_edges
def build_merge(
new_chunks: list[dict],
graph_path: str | Path = "graphify-out/graph.json",
prune_sources: list[str] | None = None,
*,
directed: bool = False,
) -> nx.Graph:
"""Load existing graph.json, merge new chunks into it, and save back.
Never replaces — only grows (or prunes deleted-file nodes via prune_sources).
Safe to call repeatedly: existing nodes and edges are preserved.
"""
from networkx.readwrite import json_graph as _jg
graph_path = Path(graph_path)
if graph_path.exists():
data = json.loads(graph_path.read_text(encoding="utf-8"))
try:
existing_G = _jg.node_link_graph(data, edges="links")
except TypeError:
existing_G = _jg.node_link_graph(data)
# Reconstruct as a plain extraction dict so build() can merge it
existing_nodes = [{"id": n, **existing_G.nodes[n]} for n in existing_G.nodes]
existing_edges = [
{"source": u, "target": v, **d} for u, v, d in existing_G.edges(data=True)
]
base = [{"nodes": existing_nodes, "edges": existing_edges}]
else:
base = []
all_chunks = base + list(new_chunks)
G = build(all_chunks, directed=directed)
# Prune nodes from deleted source files
if prune_sources:
to_remove = [
n for n, d in G.nodes(data=True)
if d.get("source_file") in prune_sources
]
G.remove_nodes_from(to_remove)
if to_remove:
print(f"[graphify] Pruned {len(to_remove)} node(s) from deleted sources.", file=sys.stderr)
# Safety check: refuse to shrink the graph silently (#479)
if graph_path.exists():
existing_n = len(existing_nodes)
new_n = G.number_of_nodes()
if new_n < existing_n:
raise ValueError(
f"graphify: build_merge would shrink graph from {existing_n} → {new_n} nodes. "
f"Pass prune_sources explicitly if you intend to remove nodes."
)
return G
+59 -25
View File
@@ -43,37 +43,52 @@ def file_hash(path: Path, root: Path = Path(".")) -> str:
return h.hexdigest()
def cache_dir(root: Path = Path(".")) -> Path:
"""Returns graphify-out/cache/ - creates it if needed."""
d = Path(root).resolve() / "graphify-out" / "cache"
def cache_dir(root: Path = Path("."), kind: str = "ast") -> Path:
"""Returns graphify-out/cache/{kind}/ - creates it if needed.
kind is "ast" or "semantic". Separate subdirectories prevent semantic cache
entries from overwriting AST cache entries for the same source_file (#582).
"""
d = Path(root).resolve() / "graphify-out" / "cache" / kind
d.mkdir(parents=True, exist_ok=True)
return d
def load_cached(path: Path, root: Path = Path(".")) -> dict | None:
def load_cached(path: Path, root: Path = Path("."), kind: str = "ast") -> dict | None:
"""Return cached extraction for this file if hash matches, else None.
Cache key: SHA256 of file contents.
Cache value: stored as graphify-out/cache/{hash}.json
Cache value: stored as graphify-out/cache/{kind}/{hash}.json
For kind="ast", also checks the legacy flat cache/ directory so users
upgrading from pre-0.5.3 don't lose their existing AST cache entries.
Returns None if no cache entry or file has changed.
"""
try:
h = file_hash(path, root)
except OSError:
return None
entry = cache_dir(root) / f"{h}.json"
if not entry.exists():
return None
try:
return json.loads(entry.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return None
entry = cache_dir(root, kind) / f"{h}.json"
if entry.exists():
try:
return json.loads(entry.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return None
# Migration fallback: check legacy flat cache/ dir for AST entries
if kind == "ast":
legacy = Path(root).resolve() / "graphify-out" / "cache" / f"{h}.json"
if legacy.exists():
try:
return json.loads(legacy.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return None
return None
def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "ast") -> None:
"""Save extraction result for this file.
Stores as graphify-out/cache/{hash}.json where hash = SHA256 of current file contents.
Stores as graphify-out/cache/{kind}/{hash}.json where hash = SHA256 of current file contents.
result should be a dict with 'nodes' and 'edges' lists.
No-ops if `path` is not a regular file. Subagent-produced semantic fragments
@@ -84,7 +99,7 @@ def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
if not p.is_file():
return
h = file_hash(p, root)
entry = cache_dir(root) / f"{h}.json"
entry = cache_dir(root, kind) / f"{h}.json"
tmp = entry.with_suffix(".tmp")
try:
tmp.write_text(json.dumps(result), encoding="utf-8")
@@ -102,16 +117,33 @@ def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
def cached_files(root: Path = Path(".")) -> set[str]:
"""Return set of file paths that have a valid cache entry (hash still matches)."""
d = cache_dir(root)
return {p.stem for p in d.glob("*.json")}
"""Return set of file hashes that have a valid cache entry (any kind)."""
base = Path(root).resolve() / "graphify-out" / "cache"
hashes: set[str] = set()
# Legacy flat entries
if base.is_dir():
hashes.update(p.stem for p in base.glob("*.json"))
# Namespaced entries
for kind in ("ast", "semantic"):
d = base / kind
if d.is_dir():
hashes.update(p.stem for p in d.glob("*.json"))
return hashes
def clear_cache(root: Path = Path(".")) -> None:
"""Delete all graphify-out/cache/*.json files."""
d = cache_dir(root)
for f in d.glob("*.json"):
f.unlink()
"""Delete all cache entries (ast/, semantic/, and legacy flat entries)."""
base = Path(root).resolve() / "graphify-out" / "cache"
# Legacy flat entries
if base.is_dir():
for f in base.glob("*.json"):
f.unlink()
# Namespaced entries
for kind in ("ast", "semantic"):
d = base / kind
if d.is_dir():
for f in d.glob("*.json"):
f.unlink()
def check_semantic_cache(
@@ -129,7 +161,7 @@ def check_semantic_cache(
uncached: list[str] = []
for fpath in files:
result = load_cached(Path(fpath), root)
result = load_cached(Path(fpath), root, kind="semantic")
if result is not None:
cached_nodes.extend(result.get("nodes", []))
cached_edges.extend(result.get("edges", []))
@@ -148,7 +180,9 @@ def save_semantic_cache(
) -> int:
"""Save semantic extraction results to cache, keyed by source_file.
Groups nodes and edges by source_file, then saves one cache entry per file.
Groups nodes and edges by source_file, then saves one cache entry per file
under cache/semantic/ (separate from AST entries in cache/ast/) to prevent
hash-key collisions (#582).
Returns the number of files cached.
"""
from collections import defaultdict
@@ -173,6 +207,6 @@ def save_semantic_cache(
if not p.is_absolute():
p = Path(root) / p
if p.is_file():
save_cached(p, result, root)
save_cached(p, result, root, kind="semantic")
saved += 1
return saved
+2 -1
View File
@@ -19,7 +19,7 @@ class FileType(str, Enum):
_MANIFEST_PATH = "graphify-out/manifest.json"
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.ejs', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.dart', '.v', '.sv'}
DOC_EXTENSIONS = {'.md', '.mdx', '.txt', '.rst', '.html'}
DOC_EXTENSIONS = {'.md', '.mdx', '.txt', '.rst', '.html', '.yaml', '.yml'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
OFFICE_EXTENSIONS = {'.docx', '.xlsx'}
@@ -241,6 +241,7 @@ _SKIP_DIRS = {
"site-packages", "lib64",
".pytest_cache", ".mypy_cache", ".ruff_cache",
".tox", ".eggs", "*.egg-info",
"graphify-out", # never treat own output as source input (#524)
}
# Large generated files that are never useful to extract
+48 -8
View File
@@ -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(
+125 -18
View File
@@ -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] = []
@@ -1676,7 +1739,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 +1951,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 +1960,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 +2058,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 +2095,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 +2128,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 +2167,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 +2275,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 +2308,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 +2347,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 +2463,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 +2479,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 +2513,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 +2644,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 +2708,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 +2832,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 +2896,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 +3094,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 +3226,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 +3250,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}",
})
@@ -3358,6 +3448,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 +3467,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
View File
@@ -145,7 +145,7 @@ def _hooks_dir(root: Path) -> Path:
if result.returncode == 0:
custom = result.stdout.strip()
if custom:
p = Path(custom)
p = Path(custom).expanduser()
if not p.is_absolute():
p = root / p
p.mkdir(parents=True, exist_ok=True)
+218
View File
@@ -0,0 +1,218 @@
# Direct LLM backend for semantic extraction — supports Claude and Kimi K2.6.
# Used by `graphify . --backend kimi` and the benchmark scripts.
# The default graphify pipeline uses Claude Code subagents via skill.md;
# this module provides a direct API path for non-Claude-Code environments.
from __future__ import annotations
import json
import os
import sys
import time
from collections.abc import Callable
from pathlib import Path
BACKENDS: dict[str, dict] = {
"claude": {
"base_url": "https://api.anthropic.com",
"default_model": "claude-sonnet-4-6",
"env_key": "ANTHROPIC_API_KEY",
"pricing": {"input": 3.0, "output": 15.0}, # USD per 1M tokens
"temperature": 0,
},
"kimi": {
"base_url": "https://api.moonshot.ai/v1",
"default_model": "kimi-k2.6",
"env_key": "MOONSHOT_API_KEY",
"pricing": {"input": 0.74, "output": 4.66}, # USD per 1M tokens
"temperature": None, # kimi-k2.6 enforces its own fixed temperature; sending any value raises 400
},
}
_EXTRACTION_SYSTEM = """\
You are a graphify semantic extraction agent. Extract a knowledge graph fragment from the files provided.
Output ONLY valid JSON — no explanation, no markdown fences, no preamble.
Rules:
- EXTRACTED: relationship explicit in source (import, call, citation, reference)
- INFERRED: reasonable inference (shared data structure, implied dependency)
- AMBIGUOUS: uncertain — flag for review, do not omit
Node ID format: lowercase, only [a-z0-9_], no dots or slashes.
Format: {stem}_{entity} where stem = filename without extension, entity = symbol name (both normalised).
Output exactly this schema:
{"nodes":[{"id":"stem_entity","label":"Human Readable Name","file_type":"code|document|paper|image|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[],"input_tokens":0,"output_tokens":0}
"""
def _read_files(paths: list[Path], root: Path) -> str:
"""Return file contents formatted for the extraction prompt."""
parts: list[str] = []
for p in paths:
try:
rel = p.relative_to(root)
except ValueError:
rel = p
try:
content = p.read_text(encoding="utf-8", errors="replace")
except OSError:
continue
parts.append(f"=== {rel} ===\n{content[:20000]}")
return "\n\n".join(parts)
def _parse_llm_json(raw: str) -> dict:
"""Strip optional markdown fences and parse JSON. Returns empty fragment on failure."""
if raw.startswith("```"):
raw = raw.split("```", 2)[1]
if raw.startswith("json"):
raw = raw[4:]
raw = raw.rsplit("```", 1)[0]
try:
return json.loads(raw.strip())
except json.JSONDecodeError as exc:
print(f"[graphify] LLM returned invalid JSON, skipping chunk: {exc}", file=sys.stderr)
return {"nodes": [], "edges": [], "hyperedges": []}
def _call_openai_compat(
base_url: str,
api_key: str,
model: str,
user_message: str,
temperature: float | None = 0,
) -> dict:
"""Call any OpenAI-compatible API (Kimi, OpenAI, etc.) and return parsed JSON."""
try:
from openai import OpenAI
except ImportError as exc:
raise ImportError(
"Kimi/OpenAI-compatible extraction requires the openai package. "
"Run: pip install openai"
) from exc
client = OpenAI(api_key=api_key, base_url=base_url)
kwargs: dict = {
"model": model,
"messages": [
{"role": "system", "content": _EXTRACTION_SYSTEM},
{"role": "user", "content": user_message},
],
"max_completion_tokens": 8192,
}
if temperature is not None:
kwargs["temperature"] = temperature
resp = client.chat.completions.create(**kwargs)
result = _parse_llm_json(resp.choices[0].message.content or "{}")
result["input_tokens"] = resp.usage.prompt_tokens if resp.usage else 0
result["output_tokens"] = resp.usage.completion_tokens if resp.usage else 0
result["model"] = model
return result
def _call_claude(api_key: str, model: str, user_message: str) -> dict:
"""Call Anthropic Claude directly (not via OpenAI compat layer)."""
try:
import anthropic
except ImportError as exc:
raise ImportError(
"Claude direct extraction requires the anthropic package. "
"Run: pip install anthropic"
) from exc
client = anthropic.Anthropic(api_key=api_key)
resp = client.messages.create(
model=model,
max_tokens=8192,
system=_EXTRACTION_SYSTEM,
messages=[{"role": "user", "content": user_message}],
)
result = _parse_llm_json(resp.content[0].text if resp.content else "{}")
result["input_tokens"] = resp.usage.input_tokens if resp.usage else 0
result["output_tokens"] = resp.usage.output_tokens if resp.usage else 0
result["model"] = model
return result
def extract_files_direct(
files: list[Path],
backend: str = "kimi",
api_key: str | None = None,
model: str | None = None,
root: Path = Path("."),
) -> dict:
"""Extract semantic nodes/edges from a list of files using the given backend.
Returns dict with nodes, edges, hyperedges, input_tokens, output_tokens.
Raises ValueError for unknown backends. Raises ImportError if SDK missing.
"""
if backend not in BACKENDS:
raise ValueError(f"Unknown backend {backend!r}. Available: {sorted(BACKENDS)}")
cfg = BACKENDS[backend]
key = api_key or os.environ.get(cfg["env_key"], "")
if not key:
raise ValueError(
f"No API key for backend '{backend}'. "
f"Set {cfg['env_key']} or pass api_key=."
)
mdl = model or cfg["default_model"]
user_msg = _read_files(files, root)
if backend == "claude":
return _call_claude(key, mdl, user_msg)
else:
return _call_openai_compat(cfg["base_url"], key, mdl, user_msg, temperature=cfg.get("temperature", 0))
def extract_corpus_parallel(
files: list[Path],
backend: str = "kimi",
api_key: str | None = None,
model: str | None = None,
root: Path = Path("."),
chunk_size: int = 20,
on_chunk_done: Callable | None = None,
) -> dict:
"""Extract a corpus in chunks, merging results.
on_chunk_done(idx, total, chunk_result) is called after each chunk if provided.
Returns merged dict with nodes, edges, hyperedges, input_tokens, output_tokens.
"""
chunks = [files[i:i + chunk_size] for i in range(0, len(files), chunk_size)]
merged: dict = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0}
for idx, chunk in enumerate(chunks):
t0 = time.time()
result = extract_files_direct(chunk, backend=backend, api_key=api_key, model=model, root=root)
result["elapsed_seconds"] = round(time.time() - t0, 2)
merged["nodes"].extend(result.get("nodes", []))
merged["edges"].extend(result.get("edges", []))
merged["hyperedges"].extend(result.get("hyperedges", []))
merged["input_tokens"] += result.get("input_tokens", 0)
merged["output_tokens"] += result.get("output_tokens", 0)
if callable(on_chunk_done):
on_chunk_done(idx, len(chunks), result)
return merged
def estimate_cost(backend: str, input_tokens: int, output_tokens: int) -> float:
"""Estimate USD cost for a given token count using published pricing."""
if backend not in BACKENDS:
return 0.0
p = BACKENDS[backend]["pricing"]
return (input_tokens * p["input"] + output_tokens * p["output"]) / 1_000_000
def detect_backend() -> str | None:
"""Return the name of whichever backend has an API key set, or None.
Kimi is checked first (opt-in). Falls back to Claude if ANTHROPIC_API_KEY is set.
Claude is the default for the skill.md subagent pipeline and is never forced here.
"""
if os.environ.get("MOONSHOT_API_KEY"):
return "kimi"
if os.environ.get("ANTHROPIC_API_KEY"):
return "claude"
return None
+37 -3
View File
@@ -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)
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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.
+2 -1
View File
@@ -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.
+2 -1
View File
@@ -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.
+2 -1
View File
@@ -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.
+1 -1
View File
@@ -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.
+2 -1
View File
@@ -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.
+2 -1
View File
@@ -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.
+2 -1
View File
@@ -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.
+40 -4
View File
@@ -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
```
+2
View File
@@ -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 -1
View File
@@ -1,7 +1,7 @@
# validate extraction JSON against the graphify schema before graph assembly
from __future__ import annotations
VALID_FILE_TYPES = {"code", "document", "paper", "image", "rationale"}
VALID_FILE_TYPES = {"code", "document", "paper", "image", "rationale", "concept"}
VALID_CONFIDENCES = {"EXTRACTED", "INFERRED", "AMBIGUOUS"}
REQUIRED_NODE_FIELDS = {"id", "label", "file_type", "source_file"}
REQUIRED_EDGE_FIELDS = {"source", "target", "relation", "confidence", "source_file"}
+5 -1
View File
@@ -98,11 +98,15 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
questions = suggest_questions(G, communities, labels)
out.mkdir(exist_ok=True)
(out / ".graphify_root").write_text(str(watch_root), encoding="utf-8")
json_written = to_json(G, communities, str(out / "graph.json"))
if not json_written:
return False
report = generate(G, communities, cohesion, labels, gods, surprises, detection,
{"input": 0, "output": 0}, report_root, suggested_questions=questions)
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
to_json(G, communities, str(out / "graph.json"))
# to_html raises ValueError for graphs > MAX_NODES_FOR_VIZ (5000).
# Wrap so core outputs (graph.json + GRAPH_REPORT.md) always land.
+4 -3
View File
@@ -4,12 +4,12 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.4.31"
version = "0.5.7"
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
readme = "README.md"
license = { file = "LICENSE" }
keywords = ["claude", "claude-code", "codex", "opencode", "cursor", "gemini", "aider", "kiro", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
requires-python = ">=3.10,<3.14"
requires-python = ">=3.10"
dependencies = [
"networkx",
"tree-sitter>=0.23.0",
@@ -50,7 +50,8 @@ 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"]
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper", "yt-dlp", "matplotlib", "openai"]
[project.scripts]
graphify = "graphify.__main__:main"
+5 -3
View File
@@ -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):
+4 -4
View File
@@ -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)