Compare commits

..
128 Commits
Author SHA1 Message Date
Safi 5843ffc277 gitignore: exclude local benchmark scripts from repo 2026-04-23 19:38:54 +01:00
Safi b326aa83c4 update README: add check-update command, Java inheritance note 2026-04-22 23:32:25 +01:00
Safi e915a877e2 bump to v0.4.31 2026-04-22 23:28:22 +01:00
Safi 64f38acf3e implement #488 #482 #472 #490: legacy schema canonicalization, Java inheritance, aggregated HTML viz, check-update subcommand 2026-04-22 23:28:09 +01:00
Safi e4bdcc2487 add tests for canvas vault-relative paths and hook .exe skip 2026-04-22 23:04:40 +01:00
Safi 8981f7c8ef bump to v0.4.30 2026-04-22 23:02:41 +01:00
Safi 4bc20527c3 fix #513 #514: skip head -1 on .exe hook binary, fix to_canvas() hardcoded obsidian path 2026-04-22 23:01:53 +01:00
Safi 85e713644e bump to v0.4.29 2026-04-22 09:28:41 +01:00
Safi 52ad45bd27 fix #504: export PYTHONUTF8=1 in Step 1 to prevent garbled CJK output on Windows 2026-04-22 09:28:26 +01:00
Safi 86d6d9317f fix #498: opencode config to .opencode/opencode.json, fix skill temp file paths, add --wiki step 2026-04-22 09:19:53 +01:00
SafiandClaude Sonnet 4.6 d9b2928da1 fix: deterministic GRAPH_REPORT on large graphs, stable edge node IDs, correct common-root inference
- analyze.py: add seed=42 to betweenness_centrality() — eliminates non-deterministic GRAPH_REPORT.md diffs on graphs >1000 nodes (#499)
- extract.py: fix common-root inference to stop at first diverging segment not sum of all matches (#502)
- extract.py: resolve root to absolute path; post-process file node IDs to project-relative after extraction so graph.json edge endpoints are stable across machines (#502)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 09:04:38 +01:00
SafiandClaude Sonnet 4.6 f8fd8f8479 fix: wiki encoding+collisions, hook rebase guard, detect path resolve, readme gitignore docs
- wiki.py: add encoding="utf-8" to all write_text() calls (fixes Windows cp1252 crash #496)
- wiki.py: deduplicate filenames with _unique_slug() to prevent silent article overwrites (#497)
- hooks.py: skip post-commit/post-checkout during rebase/merge/cherry-pick (#485)
- detect.py: resolve root path at detect() entry so .graphifyignore patterns match consistently (#495)
- README.md: document manifest.json, cost.json gitignore and .graphifyignore platform file examples (#369)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 06:26:15 +01:00
Safi f938714df0 make logo link to graphifylabs.ai 2026-04-21 22:51:21 +01:00
SafiandClaude Sonnet 4.6 7cb639ae5d fix(report): complete empty-community fix — hubs, summary count, thin-community gaps; add graph-query CLI rules to install sections
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 22:42:53 +01:00
SafiandClaude Sonnet 4.6 39bf0a3f80 Move translations/ to docs/translations/
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 22:36:20 +01:00
SafiandClaude Sonnet 4.6 e241ce96cf Bump version to 0.4.24
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 22:30:44 +01:00
SafiandClaude Sonnet 4.6 dbde78ca03 Fix four bugs from community PRs
- cache: skip directory source_file in save_cached to prevent IsADirectoryError (#444)
- report: skip structural-only communities with no real nodes (#443)
- hooks: allow @ in python path allowlist for Homebrew paths (#474)
- watch: keep source_file paths project-relative after rebuild (#434)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 22:26:17 +01:00
SafiandClaude Sonnet 4.6 9c3d0fa517 Fix chunk temp files not cleaned up after graph build
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 22:21:37 +01:00
SafiandClaude Sonnet 4.6 69d4d7e9c3 Move 27 translation READMEs to translations/ subdirectory
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 22:14:53 +01:00
SafiandClaude Sonnet 4.6 2a35d7fd38 Add 17 language translations and expand language bar to 28 languages
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 22:12:55 +01:00
SafiandClaude Sonnet 4.6 ed4f12ab82 add country flags to language links, remove Trendshift badge
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 21:53:36 +01:00
SafiandClaude Sonnet 4.6 de136676ef add Trendshift badge and move star history to top of README
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 21:51:22 +01:00
SafiandClaude Sonnet 4.6 339d9783fb add multilingual READMEs: de, fr, es, hi, pt, ru, ar; fix .agents refs in README
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 21:47:46 +01:00
SafiandClaude Sonnet 4.6 4738e88aaf fix #453 antigravity install uses .agents not .agent, fix #436 _is_sensitive false positives on directory names, fix #433 update command writes absolute paths in artifacts
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 21:33:33 +01:00
Safi 81b6e7d7b4 fix #455 #448 IsADirectoryError in file_hash and save_semantic_cache, fix #454 sanitize_label crash on None source_file 2026-04-21 21:25:13 +01:00
Safi f0ebd07fd5 Improve packaging: uv tool install support, fix interpreter detection on Mac/Linux 2026-04-21 21:11:27 +01:00
Safi 2fd15115d9 Center language links and badges 2026-04-21 11:37:13 +01:00
Safi 0973af2be0 Add dark background to text logo 2026-04-21 11:34:33 +01:00
Safi 3bf096438f Add Graphify text logo to README 2026-04-21 11:33:35 +01:00
Safi 45643380d1 Add logo to README 2026-04-21 11:31:28 +01:00
Safi 0f30cfb6ad Add logo icon SVG 2026-04-20 19:13:40 +01:00
Safi cc53e00bcc readme: revert to pepy.tech total downloads badge 2026-04-18 16:52:36 +01:00
Safi 3f5df2513b readme: show 200k+ total downloads badge 2026-04-18 16:51:36 +01:00
Safi 6892fd9309 readme: swap pepy badge for shields.io downloads 2026-04-18 16:50:15 +01:00
Safi 9c2275ad82 fix #432 to_html crash on large graphs, fix #431 Go import node ID collision 2026-04-18 10:54:39 +01:00
Safi d67436c065 v0.4.23: fix #178 stale version stamp, fix #260 add .html to DOC_EXTENSIONS 2026-04-18 10:47:37 +01:00
Safi f8a5328197 readme: add pipx as alternative install method 2026-04-18 09:51:38 +01:00
Safi 8171abf583 readme: add .mdx to docs extensions table 2026-04-18 09:50:14 +01:00
Safi c24cde9d9e v0.4.22: fix #429 AST cache root, fix #428 add .mdx to DOC_EXTENSIONS 2026-04-18 09:47:06 +01:00
Safi d0d8d80581 bump to 0.4.21, changelog 2026-04-17 20:33:28 +01:00
Safi 8666c6994c v0.4.21: fix #422 cluster-only KeyError total_files, fix #423 --update drops existing nodes 2026-04-17 20:33:06 +01:00
Safi 72d9779aaf readme: clarify graph.html opens in any browser 2026-04-17 15:50:05 +01:00
Safi 1805813a56 bump to 0.4.20, changelog 2026-04-17 15:48:30 +01:00
Safi a507c97822 v0.4.20: fix #414 JS imports_from path normalisation, fix #418 graph.html missing from CLI 2026-04-17 15:47:56 +01:00
Safi 826fd0ece1 remove superpowers specs from repo (should be local only) 2026-04-17 12:56:57 +01:00
Safi bdfb917935 changelog and readme for v0.4.19 2026-04-17 12:49:27 +01:00
SafiandClaude Sonnet 4.6 8a474eb1b3 v0.4.19: fix #390 #298 #410 #401 #385, team workflow docs, Windows/pipx tips
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 12:46:42 +01:00
Safi 022feee5fb docs: v5.0 and v5.1 design specs -- enterprise foundation 2026-04-16 13:25:02 +01:00
Safi 2a4608cbb0 docs: revise v5 spec after senior engineering review -- GraphBundle, correct rustworkx APIs, git fetch strategy 2026-04-16 11:23:08 +01:00
Safi c8a9a6cdbc docs: v5 design spec -- rustworkx backend + GitHub repo ingestion 2026-04-16 11:12:34 +01:00
SafiandClaude Sonnet 4.6 b2523fcdec v0.4.16: fix watch NameError, .mjs dispatch, exclude llm.py from wheel
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-16 07:01:04 +01:00
SafiandClaude Sonnet 4.6 429e46a665 v0.4.15: VS Code Copilot Chat, OpenCode/Gemini Windows fixes, .mjs/.ejs, macOS watch, god_nodes degree rename
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-15 23:08:43 +01:00
SafiandClaude Sonnet 4.6 7ec92ecc6d Update CHANGELOG for 0.4.14, fix AGENTS.md rebuild command
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-15 00:32:02 +01:00
SafiandClaude Sonnet 4.6 dc41eceb9e Bump to 0.4.14, README: cross-file call-graph note
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-15 00:28:18 +01:00
SafiandClaude Sonnet 4.6 01fb51ba78 Fix 9 issues: kiro package data, betweenness perf, wiki step, opencode plugin, cache root, PHP missing edges, Windows stability, cross-file calls
- #352: add skill-kiro.md to pyproject.toml package-data
- #341: guard edge_betweenness at >5000 nodes; use approximate k=100 for suggest_questions on large graphs
- #354/#229: add Step 6b in skill.md to call to_wiki() when --wiki given (before Step 9 cleanup)
- #356: call _install_opencode_plugin() from install --platform opencode path
- #350: add cache_root param to extract() so subdirectory runs keep cache at ./graphify-out/cache/
- #230: PHP class_constant_access_expression emits references_constant edges
- #232: PHP scoped_call_expression (static method calls) emits calls edges
- #287: os.replace fallback for Windows WinError 5; graphify update exits 1 on failure; templates use graphify update . instead of python3 -c
- #348: cross-file call resolution for all languages via raw_calls + global label map pass in extract()

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-15 00:26:11 +01:00
Safi ac265ec495 docs: add Verilog/SystemVerilog to language count and list 2026-04-14 09:36:57 +01:00
SafiandClaude Sonnet 4.6 b85184002c v0.4.13: Verilog support, HiDPI hyperedge fix, null label guards, AGENTS.md python3 fix
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 09:28:01 +01:00
SafiandClaude Sonnet 4.6 50afb69859 Update pyproject.toml description and keywords to include all platforms
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 22:49:01 +01:00
SafiandClaude Sonnet 4.6 2993cce8b2 v0.4.12: add Kiro IDE/CLI support, fix cache portability across machines
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 22:46:13 +01:00
SafiandClaude Sonnet 4.6 521487aa2e Fix README: Codex does have PreToolUse hook support (#299)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 22:33:33 +01:00
SafiandClaude Sonnet 4.6 b00813bcb2 v0.4.11: fix query crash on MultiGraph, NoneType in serve.py, MCP CWD path bug, .graphifyignore subfolder patterns; v0.4.10: Dart, Hermes, 6 CLI commands, PHP improvements
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 12:48:47 +01:00
Safi e737f5bf58 docs: add Hermes platform, Dart to language list, 22→23 languages 2026-04-13 08:46:20 +01:00
SafiandClaude Sonnet 4.6 1fbcaf840f release: v0.4.9 — PHP extractor improvements, Dart, diacritics, Hermes, fixes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 08:39:28 +01:00
SafiandClaude Sonnet 4.6 1dd4c41413 Remove Claude-specific language from platform skill files (0.4.8)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 21:18:20 +01:00
SafiandClaude Sonnet 4.6 4210de270f Fix watch edge key, claw path, Blade support, WSL MCP docs (0.4.7)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 20:49:24 +01:00
SafiandClaude Sonnet 4.6 f8c91a987f Add Google Antigravity platform support (0.4.6)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 19:16:49 +01:00
SafiandClaude Sonnet 4.6 6724350665 fix MCP ValidationError on blank stdin lines and bump to 0.4.5
Some MCP clients send blank lines between JSON messages. The stdio
transport tried to parse every line as JSONRPCMessage, crashing with
a Pydantic ValidationError. _filter_blank_stdin() installs an OS-level
pipe that relays stdin while silently dropping blank-only lines.

Closes #201

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 18:48:29 +01:00
SafiandClaude Sonnet 4.6 5ab8eb34c5 fix #261, #249, #266 and bump to 0.4.4
- watch.py: preserve INFERRED/AMBIGUOUS edges (code<->doc) across rebuilds (#261)
- __main__.py: fix Codex hook - use additionalContext instead of permissionDecision:allow (#249)
- detect.py: skip common lockfiles (package-lock.json, yarn.lock, Cargo.lock etc.) (#266)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 18:37:54 +01:00
Safi 8070909c04 update README: 22 languages, add .vue and .svelte to file types table 2026-04-12 13:02:45 +01:00
SafiandClaude Sonnet 4.6 d1808bab8c fix bugs #256, #253, #244, #226, #254 and bump to 0.4.3
- extract.py: resolve relative JS/TS imports to full-path IDs (fixes 0 import edges on TS codebases) (#256)
- extract.py: resolve relative Python imports to full-path IDs (#256)
- watch.py: merge fresh AST with existing semantic nodes instead of overwriting (#253)
- hooks.py: add python fallback after python3 for Windows; exit 0 if neither found (#244)
- analyze.py: guard stale _src/_tgt hints with node membership check (#226)
- detect.py + extract.py: add .vue and .svelte to CODE_EXTENSIONS and _DISPATCH (#254)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 12:59:15 +01:00
Safi b23e5de5a1 add LinkedIn badge to README 2026-04-11 21:15:32 +01:00
Safi 457e2a1b1b add 0.4.2 CHANGELOG entry 2026-04-11 21:10:45 +01:00
SafiandClaude Sonnet 4.6 8c17230586 cherry-pick PRs #212, #220, #204, #221 into 0.4.2
- build/validate: accept NetworkX <=3.1 "links" key alongside "edges" (#212)
- __main__: skip version check during install/uninstall, deduplicate paths (#220)
- all file IO: explicit encoding="utf-8" to prevent crashes on Windows CJK locales (#204)
- hooks: add newline="\n" on write to prevent CRLF shebang breakage on Windows (#204)
- export: strip trailing .md from safe_name so "CLAUDE.md" doesn't become "CLAUDE.md.md" (#221)
- report: add Community Hubs navigation block so Obsidian vault stays connected (#221)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-11 21:07:39 +01:00
SafiandClaude Sonnet 4.6 1cb882a156 fix bugs #211, #216, #217, #222 and bump to 0.4.2
- extract.py: use str(path) for node IDs to prevent same-basename collision (#211)
- build.py: normalize from/to edge keys before KeyError (#216)
- export.py: guard ZeroDivisionError when graph has no edges (#217)
- hooks.py: remove stale CODE_EXTS filter, rebuild on any changed file (#222)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-11 20:53:08 +01:00
SafiandClaude Sonnet 4.6 68abce8a04 Bump to 0.4.1
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 18:43:18 +01:00
SafiandClaude Sonnet 4.6 cede5b6ca6 Fix #188: collect_files() now respects .graphifyignore; fix #195: skill.md requires general-purpose subagent type for extraction dispatch
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 18:41:48 +01:00
SafiandClaude Sonnet 4.6 75c08a5b32 Remove YouTube URL references from README, use generic <video-url> placeholder
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 16:24:13 +01:00
SafiandClaude Sonnet 4.6 899bdd09e4 Add dedicated video and audio corpus section to README
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 16:22:53 +01:00
SafiandClaude Sonnet 4.6 74cb9ce197 Security: fix YAML injection in ingest.py, </script> injection in export.py, bound collision loop
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 16:07:51 +01:00
SafiandClaude Sonnet 4.6 4b87e67ff3 Add v4 to CI branch triggers
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 16:01:14 +01:00
SafiandClaude Sonnet 4.6 1929495a99 Bump to 0.4.0, set v4 as working branch, update CI badge and skill URL
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 15:59:43 +01:00
SafiandClaude Sonnet 4.6 2a7d2f4fdc Remove Anthropic API call from transcribe.py - agent generates Whisper prompt itself
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 15:55:22 +01:00
SafiandClaude Sonnet 4.6 db07e9f93a Fix CI: mock lazy anthropic import via sys.modules instead of module attribute
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 15:48:54 +01:00
SafiandClaude Sonnet 4.6 53d0ceb471 Add YouTube URL example to README usage, update repo about with pip install
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 15:44:44 +01:00
SafiandClaude Sonnet 4.6 de6e341b07 Update README and descriptions to mention video/audio and YouTube support
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 15:42:35 +01:00
SafiandClaude Sonnet 4.6 cf5d721bee Add video/audio corpus support with yt-dlp download and Whisper transcription
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 15:40:18 +01:00
Safi e3adc0417a fix hook reinstall, CRLF labels, skill-windows missing commands (0.3.28) 2026-04-10 10:07:11 +01:00
Safi 4ff85debf1 switch downloads badge to pepy.tech to avoid shields.io rate limit 2026-04-10 09:49:50 +01:00
Safi 2ea824533c update README Gemini CLI description to mention skill file copy 2026-04-10 01:29:05 +01:00
Safi 6b6d90ac0f fix gemini install missing skill file copy (0.3.27) 2026-04-10 01:28:19 +01:00
Safi 8b96d05da6 update README to list all platforms including Aider, Copilot CLI, Cursor, Gemini in CLI section 2026-04-10 01:09:35 +01:00
Safi 6d39432058 fix MCP server path validation security issue (0.3.26) 2026-04-10 01:08:15 +01:00
SafiandClaude Sonnet 4.6 9c829d7a2e release 0.3.25: Aider + Copilot CLI, directed graphs, frontmatter cache, graphifyignore parent discovery, MCP fixes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 00:56:22 +01:00
Safi 32986da448 Remove Trendshift badge (API not available) 2026-04-09 22:46:47 +01:00
Safi 16e36c7337 Add Trendshift badge to README 2026-04-09 22:45:52 +01:00
Safi f18ea01530 Fix codex/opencode install idempotency — always run hook step (#153) 2026-04-09 17:59:16 +01:00
Safi efefd3960a Switch star history to star-history.com for faster updates 2026-04-09 17:46:34 +01:00
Safi 244478bcee Update README: add Cursor and Gemini CLI to all platform sections 2026-04-09 17:44:59 +01:00
SafiandClaude Sonnet 4.6 df26f85648 Add Gemini CLI support and sponsor nudge at pipeline completion (#105)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 17:40:45 +01:00
Safi 38381597d6 Add Cursor to description, README intro, and PyPI keywords 2026-04-09 17:25:36 +01:00
SafiandClaude Sonnet 4.6 df77d5f8ce Add Cursor support, fix _rebuild_code KeyError and node_link_data crash (#137, #148, #149)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 17:19:40 +01:00
Safi c99ac6c2df Add monthly PyPI downloads badge to README 2026-04-09 14:46:13 +01:00
SafiandClaude Sonnet 4.6 45e407db35 Fix Codex hook JSON schema (#138) and use #!/bin/sh for Windows git hooks (#140)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:12:36 +01:00
SafiandClaude Sonnet 4.6 95f6c104d4 Pin tree-sitter>=0.23.0, add version guard, confidence=EXTRACTED for AST calls
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 09:36:32 +01:00
SafiandClaude Sonnet 4.6 ca842472e5 Fix AST call edges confidence: INFERRED/0.8 -> EXTRACTED/1.0 (#127)
Tree-sitter resolves call targets directly from source — marking them
INFERRED was incorrect. Cross-file class-level uses edges remain INFERRED.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 09:22:12 +01:00
SafiandClaude Sonnet 4.6 bb2049cec1 Fix XSS in HTML viz: escape node labels, types, source files, and edge relations in innerHTML (#sec)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 09:06:02 +01:00
SafiandClaude Sonnet 4.6 036d904e31 Update README for OpenCode tool.execute.before plugin
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 08:56:44 +01:00
SafiandClaude Sonnet 4.6 e5760e6b03 Add OpenCode tool.execute.before plugin via graphify opencode install (#71)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 08:55:07 +01:00
SafiandClaude Sonnet 4.6 2a550a3fe6 Release v0.3.19
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 08:46:26 +01:00
SafiandClaude Sonnet 4.6 be2058d5d5 Fix install step: try plain pip before --break-system-packages (#126)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 08:40:17 +01:00
SafiandClaude Sonnet 4.6 33482b0827 Update CHANGELOG for v0.3.18 with PR fixes (#82 #93 #102 #109)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 08:24:29 +01:00
SafiandClaude Sonnet 4.6 c3817d6144 Apply PRs #82 #93 #102 #109: extension drift, click detection, skill coverage, .graphify_python persistence
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 08:22:01 +01:00
Safi 91cbc74bb1 release 0.3.18: fix watch .graphifyignore, codex hook, trae link, Korean README, save-result CLI 2026-04-09 08:09:36 +01:00
Safi 9cfaa3339b add Korean README and fix trae.com link across all READMEs 2026-04-09 08:00:07 +01:00
Safi 267f8d28c4 add Penpax link to README 2026-04-09 01:14:08 +01:00
SafiandClaude Sonnet 4.6 dbcb1253e8 docs: add .jsx .tsx .jl to extensions table, bump to 20 languages
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 22:57:46 +01:00
SafiandClaude Sonnet 4.6 7ff7bd2e8f v0.3.17: Julia support, smarter chunking, tree-sitter pin, progress output
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 22:54:18 +01:00
SafiandClaude Sonnet 4.6 1896379283 v0.3.16: NetworkX <3.4 compat, .jsx support, pipx follow-up fix
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 22:27:08 +01:00
Safi b4180a50dc fix: switch star history chart to starchart.cc (no auth required) 2026-04-08 20:06:06 +01:00
Safi a25f7629bd release: 0.3.15 — Trae platform, security hardening, pipx hooks, PowerShell fix 2026-04-08 20:00:05 +01:00
Safi 359ef86dd4 fix: shebang allowlist validation in all skill files 2026-04-08 19:57:33 +01:00
Safi 2b3accfe66 fix: XSS in legend innerHTML and shebang allowlist in hooks 2026-04-08 19:53:10 +01:00
Safi 21a081b514 fix: skill-droid.md missing from package-data, louvain kwargs version-safe 2026-04-08 19:47:07 +01:00
ljinshuanandlijinshuan 76bbb37c74 feat: add Trae and Trae CN platform support
- Register 'trae' and 'trae-cn' in _PLATFORM_CONFIG (skill-trae.md,
  ~/.trae/skills/ and ~/.trae-cn/skills/, claude_md=False)
- Add CLI subcommands: graphify trae install/uninstall,
  graphify trae-cn install/uninstall (routes to _agents_install/uninstall)
- Update help text with new platform entries
- Create skill-trae.md (Agent-tool based extraction, AGENTS.md integration,
  no PreToolUse hook support per Trae limitations)
- Update README.md and README.zh-CN.md with Trae platform docs

Co-authored-by: lijinshuan <lijinshuan@bytedance.com>
2026-04-08 19:44:19 +01:00
Ikko Eltociear Ashimine a87be4143a docs: add Japanese README 2026-04-08 19:40:33 +01:00
gdesai23 f937fc6ce1 docs: add graph.json + LLM workflow example to README 2026-04-08 19:40:29 +01:00
azizur100389andClaude Opus 4.6 22f79db72f fix: suppress graspologic ANSI output that corrupts PowerShell scroll buffer
* fix: suppress graspologic ANSI output that breaks PowerShell scrolling

graspologic's leiden() emits ANSI escape sequences (progress bars,
colored warnings) that corrupt PowerShell 5.1's scroll buffer on
Windows, disabling vertical scrolling. Redirect stdout/stderr to
StringIO during leiden() calls to prevent any escape codes from
reaching the terminal.

Add 2 tests verifying cluster() produces no stdout/stderr output.

Fixes #19

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: add PowerShell troubleshooting section to Windows skill

Document the PowerShell 5.1 scrolling issue and provide 4
workarounds: upgrade graphify, use Windows Terminal, reset
terminal, or uninstall graspologic to use Louvain fallback.

Fixes #19

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-08 19:40:10 +01:00
Minidoracat ba7c395ce3 fix: detect correct Python interpreter for pipx installs in git hooks
* fix: git hooks fail when graphify is installed via pipx

When installed via pipx, the graphify module is only available in
pipx's isolated venv, not the system python3. The git hooks
(post-commit, post-checkout) hardcoded `python3` which cannot import
graphify in this case.

Detect the correct Python interpreter from the graphify binary's
shebang line, matching the approach already used in skill.md Step 1.
Falls back to python3 for system installs.

* fix: handle env-style shebangs and improve interpreter detection

- Use POSIX `command -v` instead of non-standard `which`
- Parse `#!/usr/bin/env python3` shebangs correctly (previous
  `tr -d ' '` would produce `/usr/bin/envpython3`)
- Add import validation fallback to python3 if resolved interpreter
  cannot import graphify
2026-04-08 19:39:43 +01:00
21 changed files with 451 additions and 902 deletions

No files matched your search

+6 -1
View File
@@ -21,4 +21,9 @@ skills/
docs/superpowers/
.vscode/
openspec/
uv.lock
uv.lock
# Local benchmark scripts — never commit
scripts/run_k2_*.py
scripts/llm.py
scripts/benchmark_kimi*.json
scripts/benchmark_kimi*.py
+2 -1
View File
@@ -329,6 +329,7 @@ graphify add https://... --author "Name" --contributor "Name"
# 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)
graphify update ./src # re-extract code files, no LLM needed
graphify cluster-only ./my-project # rerun clustering on existing graph.json
```
@@ -337,7 +338,7 @@ Works with any mix of file types:
| Type | Extensions | Extraction |
|------|-----------|------------|
| Code | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl .vue .svelte` | AST via tree-sitter + call-graph (cross-file for all languages) + docstring/comment rationale |
| Code | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl .vue .svelte` | 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 |
| Office | `.docx .xlsx` | Converted to markdown then extracted via Claude (requires `pip install graphifyy[office]`) |
| Papers | `.pdf` | Citation mining + concept extraction |
+9 -1
View File
@@ -643,7 +643,7 @@ export const GraphifyPlugin = async ({ directory }) => {
"""
_OPENCODE_PLUGIN_PATH = Path(".opencode") / "plugins" / "graphify.js"
_OPENCODE_CONFIG_PATH = Path("opencode.json")
_OPENCODE_CONFIG_PATH = Path(".opencode") / "opencode.json"
def _install_opencode_plugin(project_dir: Path) -> None:
@@ -940,6 +940,7 @@ def main() -> None:
print(" --type T query type: query|path_query|explain (default: query)")
print(" --nodes N1 N2 ... source node labels cited in the answer")
print(" --memory-dir DIR memory directory (default: graphify-out/memory)")
print(" check-update <path> check needs_update flag and notify if semantic re-extraction is pending (cron-safe)")
print(" benchmark [graph.json] measure token reduction vs naive full-corpus approach")
print(" hook install install post-commit/post-checkout git hooks (all platforms)")
print(" hook uninstall remove git hooks")
@@ -1351,6 +1352,13 @@ def main() -> None:
print("Nothing to update or rebuild failed — check output above.", file=sys.stderr)
sys.exit(1)
elif cmd == "check-update":
if len(sys.argv) < 3:
print("Usage: graphify check-update <path>", file=sys.stderr)
sys.exit(1)
from graphify.watch import check_update
check_update(Path(sys.argv[2]).resolve())
sys.exit(0)
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"
+6
View File
@@ -46,6 +46,12 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
# NetworkX <= 3.1 serialised edges as "links"; remap to "edges" for compatibility.
if "edges" not in extraction and "links" in extraction:
extraction = dict(extraction, edges=extraction["links"])
# 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:
node["source_file"] = node.pop("source")
errors = validate_extraction(extraction)
# Dangling edges (stdlib/external imports) are expected - only warn about real schema errors.
real_errors = [e for e in errors if "does not match any node id" not in e]
+15 -5
View File
@@ -344,12 +344,16 @@ def to_html(
communities: dict[int, list[str]],
output_path: str,
community_labels: dict[int, str] | None = None,
member_counts: dict[int, int] | None = None,
) -> None:
"""Generate an interactive vis.js HTML visualization of the graph.
Features: node size by degree, click-to-inspect panel, search box,
community filter, physics clustering by community, confidence-styled edges.
Raises ValueError if graph exceeds MAX_NODES_FOR_VIZ.
If member_counts is provided (aggregated community view), node sizes are
based on community member counts rather than graph degree.
"""
if G.number_of_nodes() > MAX_NODES_FOR_VIZ:
raise ValueError(
@@ -360,6 +364,7 @@ def to_html(
node_community = _node_community_map(communities)
degree = dict(G.degree())
max_deg = max(degree.values(), default=1) or 1
max_mc = (max(member_counts.values(), default=1) or 1) if member_counts else 1
# Build nodes list for vis.js
vis_nodes = []
@@ -368,9 +373,14 @@ def to_html(
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
label = sanitize_label(data.get("label", node_id))
deg = degree.get(node_id, 1)
size = 10 + 30 * (deg / max_deg)
# Only show label for high-degree nodes by default; others show on hover
font_size = 12 if deg >= max_deg * 0.15 else 0
if member_counts:
mc = member_counts.get(cid, 1)
size = 10 + 30 * (mc / max_mc)
font_size = 12
else:
size = 10 + 30 * (deg / max_deg)
# Only show label for high-degree nodes by default; others show on hover
font_size = 12 if deg >= max_deg * 0.15 else 0
vis_nodes.append({
"id": node_id,
"label": label,
@@ -406,7 +416,7 @@ def to_html(
for cid in sorted((community_labels or {}).keys()):
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
lbl = _html.escape(sanitize_label((community_labels or {}).get(cid, f"Community {cid}")))
n = len(communities.get(cid, []))
n = member_counts.get(cid, len(communities.get(cid, []))) if member_counts else len(communities.get(cid, []))
legend_data.append({"cid": cid, "color": color, "label": lbl, "count": n})
# Escape </script> sequences so embedded JSON cannot break out of the script tag
@@ -831,7 +841,7 @@ def to_canvas(
canvas_nodes.append({
"id": f"n_{node_id}",
"type": "file",
"file": f"graphify/obsidian/{fname}.md",
"file": f"{fname}.md",
"x": nx_x,
"y": nx_y,
"width": 180,
+138
View File
@@ -803,6 +803,49 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
seen_ids.add(base_nid)
add_edge(class_nid, base_nid, "inherits", line)
# Java-specific: extends (superclass) / implements (interfaces) / interface-extends
if config.ts_module == "tree_sitter_java":
def _emit_java_parent(base_name: str, rel: str, at_line: int) -> None:
if not base_name:
return
base_nid = _make_id(stem, base_name)
if base_nid not in seen_ids:
base_nid = _make_id(base_name)
if base_nid not in seen_ids:
nodes.append({
"id": base_nid,
"label": base_name,
"file_type": "code",
"source_file": "",
"source_location": "",
})
seen_ids.add(base_nid)
add_edge(class_nid, base_nid, rel, at_line)
sup = node.child_by_field_name("superclass")
if sup is not None:
for sub in sup.children:
if sub.type == "type_identifier":
_emit_java_parent(_read_text(sub, source), "extends", line)
break
ifs = node.child_by_field_name("interfaces")
if ifs is not None:
for sub in ifs.children:
if sub.type == "type_list":
for tid in sub.children:
if tid.type == "type_identifier":
_emit_java_parent(_read_text(tid, source), "implements", line)
if t == "interface_declaration":
for child in node.children:
if child.type == "extends_interfaces":
for sub in child.children:
if sub.type == "type_list":
for tid in sub.children:
if tid.type == "type_identifier":
_emit_java_parent(_read_text(tid, source), "extends", line)
# Find body and recurse
body = _find_body(node, config)
if body:
@@ -2664,6 +2707,91 @@ def _resolve_cross_file_imports(
return new_edges
def _resolve_cross_file_java_imports(
per_file: list[dict],
paths: list[Path],
) -> list[dict]:
"""Two-pass Java import resolution.
Pass 1: build a global index {ClassName: [node_id, ...]} across all Java nodes.
Pass 2: re-parse each Java file; for every `import a.b.C;`, resolve C against
the index. Wildcard and stdlib imports produce no edge.
"""
try:
import tree_sitter_java as tsjava
from tree_sitter import Language, Parser
except ImportError:
return []
language = Language(tsjava.language())
parser = Parser(language)
# Pass 1: class-name → node_id index (only internal, uppercase-starting names)
name_to_ids: dict[str, list[str]] = {}
for file_result in per_file:
for node in file_result.get("nodes", []):
label = node.get("label", "")
nid = node.get("id", "")
src = node.get("source_file", "")
if not label or not nid or not src:
continue
if label.endswith(")") or label.endswith(".java"):
continue
if not label[0].isalpha() or not label[0].isupper():
continue
name_to_ids.setdefault(label, []).append(nid)
# Pass 2: resolve imports to real node IDs
new_edges: list[dict] = []
seen_pairs: set[tuple[str, str]] = set()
for path in paths:
file_nid = _make_id(path.stem)
try:
source = path.read_bytes()
tree = parser.parse(source)
except Exception:
continue
def walk(n) -> None:
if n.type == "import_declaration":
raw = _read_text(n, source).strip()
body = raw[len("import"):].strip().rstrip(";").strip()
if body.startswith("static "):
body = body[len("static "):].strip()
if body.endswith(".*"):
return
parts = body.split(".")
if not parts:
return
last = parts[-1]
if last and last[0].islower() and len(parts) >= 2:
last = parts[-2]
at_line = n.start_point[0] + 1
for tgt_nid in name_to_ids.get(last, []):
if tgt_nid == file_nid:
continue
key = (file_nid, tgt_nid)
if key in seen_pairs:
continue
seen_pairs.add(key)
new_edges.append({
"source": file_nid,
"target": tgt_nid,
"relation": "imports",
"confidence": "EXTRACTED",
"confidence_score": 1.0,
"source_file": str(path),
"source_location": f"L{at_line}",
"weight": 1.0,
})
for child in n.children:
walk(child)
walk(tree.root_node)
return new_edges
def extract_objc(path: Path) -> dict:
"""Extract interfaces, implementations, protocols, methods, and imports from .m/.mm/.h files."""
try:
@@ -3204,6 +3332,16 @@ def extract(paths: list[Path], cache_root: Path | None = None) -> dict:
import logging
logging.getLogger(__name__).warning("Cross-file import resolution failed, skipping: %s", exc)
# Cross-file Java import resolution
java_paths = [p for p in paths if p.suffix == ".java"]
if java_paths:
java_results = [r for r, p in zip(per_file, paths) if p.suffix == ".java"]
try:
all_edges.extend(_resolve_cross_file_java_imports(java_results, java_paths))
except Exception as exc:
import logging
logging.getLogger(__name__).warning("Java cross-file import resolution failed, skipping: %s", exc)
# Cross-file call resolution for all languages
# Each extractor saved unresolved calls in raw_calls. Now that we have all
# nodes from all files, resolve any callee that exists in another file.
+4 -1
View File
@@ -13,7 +13,10 @@ _PYTHON_DETECT = """\
# Detect the correct Python interpreter (handles pipx, venv, system installs)
GRAPHIFY_BIN=$(command -v graphify 2>/dev/null)
if [ -n "$GRAPHIFY_BIN" ]; then
_SHEBANG=$(head -1 "$GRAPHIFY_BIN" | sed 's/^#![[:space:]]*//')
case "$GRAPHIFY_BIN" in
*.exe) _SHEBANG="" ;;
*) _SHEBANG=$(head -1 "$GRAPHIFY_BIN" | sed 's/^#![[:space:]]*//') ;;
esac
case "$_SHEBANG" in
*/env\\ *) GRAPHIFY_PYTHON="${_SHEBANG#*/env }" ;;
*) GRAPHIFY_PYTHON="$_SHEBANG" ;;
+143 -89
View File
@@ -72,22 +72,24 @@ fi
# Write interpreter path for all subsequent steps
mkdir -p graphify-out
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
# Force UTF-8 I/O on Windows (prevents garbled CJK/non-ASCII output)
export PYTHONUTF8=1
```
If the import succeeds, print nothing and move straight to Step 2.
**In every subsequent bash block, replace `python3` with `$(cat .graphify_python)` to use the correct interpreter.**
**In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
### Step 2 - Detect files
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.detect import detect
from pathlib import Path
result = detect(Path('INPUT_PATH'))
print(json.dumps(result))
" > .graphify_detect.json
" > graphify-out/.graphify_detect.json
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
@@ -168,23 +170,23 @@ Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is determin
For any code files detected, run AST extraction in parallel with Part B subagents:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.extract import collect_files, extract
from pathlib import Path
import json
code_files = []
detect = json.loads(Path('.graphify_detect.json').read_text())
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
result = extract(code_files)
Path('.graphify_ast.json').write_text(json.dumps(result, indent=2))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2))
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
Path('.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
print('No code files - skipping AST extraction')
"
```
@@ -196,7 +198,7 @@ else:
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
Before dispatching subagents, print a timing estimate:
- Load `total_words` and file counts from `.graphify_detect.json`
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
@@ -206,28 +208,28 @@ Before dispatching subagents, print a timing estimate:
Before dispatching any subagents, check which files already have cached extraction results:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
detect = json.loads(Path('.graphify_detect.json').read_text())
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
all_files = [f for files in detect['files'].values() for f in files]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
if cached_nodes or cached_edges or cached_hyperedges:
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
Path('.graphify_uncached.txt').write_text('\n'.join(uncached))
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached))
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
"
```
Only dispatch subagents for files listed in `.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
**Step B1 - Split into chunks**
Load files from `.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
**Step B2 - Dispatch ALL subagents in a single message (OpenCode)**
@@ -241,7 +243,7 @@ Dispatch one `@mention` per chunk — ALL in the same response:
@agent Chunk 2 of TOTAL_CHUNKS: [next chunk]
```
Wait for all agents to return. Parse each response as JSON. Accumulate nodes/edges/hyperedges across all results and write to `.graphify_semantic_new.json`.
Wait for all agents to return. Parse each response as JSON. Accumulate nodes/edges/hyperedges across all results and write to `graphify-out/.graphify_semantic_new.json`.
The extraction prompt each agent receives (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE):
@@ -310,25 +312,25 @@ If more than half the chunks failed or are missing, stop and tell the user to re
Save new results to cache:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.cache import save_semantic_cache
from pathlib import Path
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text()) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
print(f'Cached {saved} files')
"
```
Merge cached + new results into `.graphify_semantic.json`:
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
cached = json.loads(Path('.graphify_cached.json').read_text()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text()) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text()) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
all_nodes = cached['nodes'] + new.get('nodes', [])
all_edges = cached['edges'] + new.get('edges', [])
@@ -347,21 +349,21 @@ merged = {
'input_tokens': new.get('input_tokens', 0),
'output_tokens': new.get('output_tokens', 0),
}
Path('.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
"
```
Clean up temp files: `rm -f .graphify_cached.json .graphify_uncached.txt .graphify_semantic_new.json`
Clean up temp files: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json`
#### Part C - Merge AST + semantic into final extraction
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from pathlib import Path
ast = json.loads(Path('.graphify_ast.json').read_text())
sem = json.loads(Path('.graphify_semantic.json').read_text())
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text())
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text())
# Merge: AST nodes first, semantic nodes deduplicated by id
seen = {n['id'] for n in ast['nodes']}
@@ -380,7 +382,7 @@ merged = {
'input_tokens': sem.get('input_tokens', 0),
'output_tokens': sem.get('output_tokens', 0),
}
Path('.graphify_extract.json').write_text(json.dumps(merged, indent=2))
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2))
total = len(merged_nodes)
edges = len(merged_edges)
print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
@@ -391,7 +393,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
```bash
mkdir -p graphify-out
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
@@ -400,8 +402,8 @@ from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
detection = json.loads(Path('.graphify_detect.json').read_text())
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
G = build_from_json(extraction)
communities = cluster(G)
@@ -424,7 +426,7 @@ analysis = {
'surprises': surprises,
'questions': questions,
}
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
if G.number_of_nodes() == 0:
print('ERROR: Graph is empty - extraction produced no nodes.')
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
@@ -439,12 +441,12 @@ Replace INPUT_PATH with the actual path.
### Step 5 - Label communities
Read `.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
Then regenerate the report and save the labels for the visualizer:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import score_all
@@ -452,9 +454,9 @@ from graphify.analyze import god_nodes, surprising_connections, suggest_question
from graphify.report import generate
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
detection = json.loads(Path('.graphify_detect.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -469,7 +471,7 @@ questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
print('Report updated with community labels')
"
```
@@ -484,15 +486,15 @@ Replace INPUT_PATH with the actual path.
If `--obsidian` was given:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_obsidian, to_canvas
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -515,40 +517,92 @@ print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries
Generate the HTML graph (always, unless `--no-viz`):
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_html
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
labels = {int(k): v for k, v in labels_raw.items()}
if G.number_of_nodes() > 5000:
print(f'Graph has {G.number_of_nodes()} nodes - too large for HTML viz. Use Obsidian vault instead.')
NODE_LIMIT = 5000
if G.number_of_nodes() > NODE_LIMIT:
from collections import Counter
print(f'Graph has {G.number_of_nodes()} nodes (above {NODE_LIMIT} limit). Building aggregated community view...')
node_to_community = {nid: cid for cid, members in communities.items() for nid in members}
import networkx as nx_meta
meta = nx_meta.Graph()
for cid, members in communities.items():
meta.add_node(str(cid), label=labels.get(cid, f'Community {cid}'))
edge_counts = Counter()
for u, v in G.edges():
cu, cv = node_to_community.get(u), node_to_community.get(v)
if cu is not None and cv is not None and cu != cv:
edge_counts[(min(cu, cv), max(cu, cv))] += 1
for (cu, cv), w in edge_counts.items():
meta.add_edge(str(cu), str(cv), weight=w, relation=f'{w} cross-community edges', confidence='AGGREGATED')
if meta.number_of_nodes() > 1:
meta_communities = {cid: [str(cid)] for cid in communities}
member_counts = {cid: len(members) for cid, members in communities.items()}
to_html(meta, meta_communities, 'graphify-out/graph.html', community_labels=labels or None, member_counts=member_counts)
print(f'graph.html written (aggregated: {meta.number_of_nodes()} community nodes, {meta.number_of_edges()} cross-community edges)')
print('Tip: run with --obsidian for full node-level detail.')
else:
print('Single community — aggregated view not useful. Skipping graph.html.')
else:
to_html(G, communities, 'graphify-out/graph.html', community_labels=labels or None)
print('graph.html written - open in any browser, no server needed')
"
```
### Step 6b - Wiki (only if --wiki flag)
**Only run this step if `--wiki` was explicitly given in the original command.**
Run this before Step 9 (cleanup) so `graphify-out/.graphify_labels.json` is still available.
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.build import build_from_json
from graphify.wiki import to_wiki
from graphify.analyze import god_nodes
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
labels = {int(k): v for k, v in labels_raw.items()}
gods = god_nodes(G)
n = to_wiki(G, communities, 'graphify-out/wiki', community_labels=labels or None, cohesion=cohesion, god_nodes_data=gods)
print(f'Wiki: {n} articles written to graphify-out/wiki/')
print(' graphify-out/wiki/index.md -> agent entry point')
"
```
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
**If `--neo4j`** - generate a Cypher file for manual import:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_cypher
from pathlib import Path
G = build_from_json(json.loads(Path('.graphify_extract.json').read_text()))
G = build_from_json(json.loads(Path('graphify-out/.graphify_extract.json').read_text()))
to_cypher(G, 'graphify-out/cypher.txt')
print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt')
"
@@ -557,15 +611,15 @@ print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt'
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster
from graphify.export import push_to_neo4j
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -579,15 +633,15 @@ Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default
### Step 7b - SVG export (only if --svg flag)
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_svg
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -601,14 +655,14 @@ print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
### Step 7c - GraphML export (only if --graphml flag)
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.build import build_from_json
from graphify.export import to_graphml
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -640,15 +694,15 @@ To configure in Claude Desktop, add to `claude_desktop_config.json`:
### Step 8 - Token reduction benchmark (only if total_words > 5000)
If `total_words` from `.graphify_detect.json` is greater than 5,000, run:
If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.benchmark import run_benchmark, print_benchmark
from pathlib import Path
detection = json.loads(Path('.graphify_detect.json').read_text())
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
result = run_benchmark('graphify-out/graph.json', corpus_words=detection['total_words'])
print_benchmark(result)
"
@@ -661,18 +715,18 @@ Print the output directly in chat. If `total_words <= 5000`, skip silently - the
### Step 9 - Save manifest, update cost tracker, clean up, and report
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
from datetime import datetime, timezone
from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('.graphify_detect.json').read_text())
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
save_manifest(detect['files'])
# Update cumulative cost tracker
extract = json.loads(Path('.graphify_extract.json').read_text())
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
input_tok = extract.get('input_tokens', 0)
output_tok = extract.get('output_tokens', 0)
@@ -695,7 +749,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_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .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_labels.json graphify-out/.graphify_chunk_*.json
rm -f graphify-out/.needs_update 2>/dev/null || true
```
@@ -735,7 +789,7 @@ The graph is the map. Your job after the pipeline is to be the guide.
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.detect import detect_incremental, save_manifest
from pathlib import Path
@@ -743,7 +797,7 @@ from pathlib import Path
result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('.graphify_incremental.json').write_text(json.dumps(result))
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result))
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
@@ -754,11 +808,11 @@ print(f'{new_total} new/changed file(s) to re-extract.')
If new files exist, first check whether all changed files are code files:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
result = json.loads(open('.graphify_incremental.json').read()) if Path('.graphify_incremental.json').exists() else {}
result = json.loads(open('graphify-out/.graphify_incremental.json').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {}
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts'}
new_files = result.get('new_files', {})
all_changed = [f for files in new_files.values() for f in files]
@@ -774,7 +828,7 @@ If `code_only` is False (any changed file is a doc/paper/image): run the full St
Then:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_json
@@ -787,7 +841,7 @@ existing_data = json.loads(Path('graphify-out/graph.json').read_text())
G_existing = json_graph.node_link_graph(existing_data, edges='links')
# Load new extraction
new_extraction = json.loads(Path('.graphify_extract.json').read_text())
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
G_new = build_from_json(new_extraction)
# Merge: new nodes/edges into existing graph
@@ -801,7 +855,7 @@ Then run Steps 4–8 on the merged graph as normal.
After Step 4, show the graph diff:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.analyze import graph_diff
from graphify.build import build_from_json
@@ -810,8 +864,8 @@ import networkx as nx
from pathlib import Path
# Load old graph (before update) from backup written before merge
old_data = json.loads(Path('.graphify_old.json').read_text()) if Path('.graphify_old.json').exists() else None
new_extract = json.loads(Path('.graphify_extract.json').read_text())
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text()) if Path('graphify-out/.graphify_old.json').exists() else None
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
G_new = build_from_json(new_extract)
if old_data:
@@ -825,8 +879,8 @@ if old_data:
"
```
Before the merge step, save the old graph: `cp graphify-out/graph.json .graphify_old.json`
Clean up after: `rm -f .graphify_old.json`
Before the merge step, save the old graph: `cp graphify-out/graph.json graphify-out/.graphify_old.json`
Clean up after: `rm -f graphify-out/.graphify_old.json`
---
@@ -835,7 +889,7 @@ Clean up after: `rm -f .graphify_old.json`
Skip Steps 1–3. Load the existing graph from `graphify-out/graph.json` and re-run clustering:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections
@@ -868,7 +922,7 @@ analysis = {
'gods': gods,
'surprises': surprises,
}
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
print(f'Re-clustered: {len(communities)} communities')
"
```
@@ -888,7 +942,7 @@ Two traversal modes - choose based on the question:
First check the graph exists:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
@@ -906,7 +960,7 @@ Load `graphify-out/graph.json`, then:
5. If the graph lacks enough information, say so - do not hallucinate edges.
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys, json
from networkx.readwrite import json_graph
import networkx as nx
@@ -997,7 +1051,7 @@ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`,
After writing the answer, save it back into the graph so it improves future queries:
```bash
$(cat .graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the question, `ANSWER` with your full answer text, `SOURCE_NODES` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
@@ -1010,7 +1064,7 @@ Find the shortest path between two named concepts in the graph.
First check the graph exists:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
@@ -1020,7 +1074,7 @@ if not Path('graphify-out/graph.json').exists():
If it fails, stop and tell the user to run `/graphify <path>` first.
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
@@ -1072,7 +1126,7 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
After writing the explanation, save it back:
```bash
$(cat .graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
```
---
@@ -1083,7 +1137,7 @@ Give a plain-language explanation of a single node - everything connected to it.
First check the graph exists:
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
@@ -1093,7 +1147,7 @@ if not Path('graphify-out/graph.json').exists():
If it fails, stop and tell the user to run `/graphify <path>` first.
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
@@ -1138,7 +1192,7 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
After writing the explanation, save it back:
```bash
$(cat .graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
```
---
@@ -1148,7 +1202,7 @@ $(cat .graphify_python) -m graphify save-result --question "Explain NODE_NAME" -
Fetch a URL and add it to the corpus, then update the graph.
```bash
$(cat .graphify_python) -c "
$(cat graphify-out/.graphify_python) -c "
import sys
from graphify.ingest import ingest
from pathlib import Path
+24 -2
View File
@@ -550,8 +550,30 @@ G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
labels = {int(k): v for k, v in labels_raw.items()}
if G.number_of_nodes() > 5000:
print(f'Graph has {G.number_of_nodes()} nodes - too large for HTML viz. Use Obsidian vault instead.')
NODE_LIMIT = 5000
if G.number_of_nodes() > NODE_LIMIT:
from collections import Counter
print(f'Graph has {G.number_of_nodes()} nodes (above {NODE_LIMIT} limit). Building aggregated community view...')
node_to_community = {nid: cid for cid, members in communities.items() for nid in members}
import networkx as nx_meta
meta = nx_meta.Graph()
for cid, members in communities.items():
meta.add_node(str(cid), label=labels.get(cid, f'Community {cid}'))
edge_counts = Counter()
for u, v in G.edges():
cu, cv = node_to_community.get(u), node_to_community.get(v)
if cu is not None and cv is not None and cu != cv:
edge_counts[(min(cu, cv), max(cu, cv))] += 1
for (cu, cv), w in edge_counts.items():
meta.add_edge(str(cu), str(cv), weight=w, relation=f'{w} cross-community edges', confidence='AGGREGATED')
if meta.number_of_nodes() > 1:
meta_communities = {cid: [str(cid)] for cid in communities}
member_counts = {cid: len(members) for cid, members in communities.items()}
to_html(meta, meta_communities, 'graphify-out/graph.html', community_labels=labels or None, member_counts=member_counts)
print(f'graph.html written (aggregated: {meta.number_of_nodes()} community nodes, {meta.number_of_edges()} cross-community edges)')
print('Tip: run with --obsidian for full node-level detail.')
else:
print('Single community — aggregated view not useful. Skipping graph.html.')
else:
to_html(G, communities, 'graphify-out/graph.html', community_labels=labels or None)
print('graph.html written - open in any browser, no server needed')
+15
View File
@@ -132,6 +132,21 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
return False
def check_update(watch_path: Path) -> bool:
"""Check for pending semantic update flag and notify the user if set.
Cron-safe: always returns True so cron jobs do not alarm.
Non-code file changes (docs, papers, images) require LLM-backed
re-extraction via `/graphify --update` — this function only signals
that the update is needed.
"""
flag = Path(watch_path) / "graphify-out" / "needs_update"
if flag.exists():
print(f"[graphify check-update] Pending non-code changes in {watch_path}.")
print("[graphify check-update] Run `/graphify --update` to apply semantic re-extraction.")
return True
def _notify_only(watch_path: Path) -> None:
"""Write a flag file and print a notification (fallback for non-code-only corpora)."""
flag = watch_path / "graphify-out" / "needs_update"
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.4.27"
version = "0.4.31"
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" }
-87
View File
@@ -1,87 +0,0 @@
{
"httpx": {
"model": "kimi-k2.6",
"chunk_size": 2,
"total_nodes": 71,
"total_edges": 57,
"unique_rel_types": 6,
"relation_types": {
"references": 33,
"semantically_similar_to": 7,
"conceptually_related_to": 7,
"rationale_for": 7,
"calls": 2,
"implements": 1
},
"input_tokens": 7243,
"output_tokens": 41410,
"cost_usd": 0.1203,
"elapsed_seconds": 1151.9,
"chunks_run": 3,
"chunks_failed": 0
},
"click": {
"model": "kimi-k2.6",
"chunk_size": 2,
"total_nodes": 62,
"total_edges": 48,
"unique_rel_types": 7,
"relation_types": {
"references": 13,
"calls": 11,
"shares_data_with": 8,
"conceptually_related_to": 7,
"rationale_for": 7,
"implements": 1,
"cites": 1
},
"input_tokens": 13776,
"output_tokens": 35520,
"cost_usd": 0.1077,
"elapsed_seconds": 1022.8,
"chunks_run": 3,
"chunks_failed": 0
},
"rich": {
"model": "kimi-k2.6",
"chunk_size": 2,
"total_nodes": 53,
"total_edges": 52,
"unique_rel_types": 6,
"relation_types": {
"implements": 18,
"calls": 15,
"conceptually_related_to": 7,
"references": 6,
"semantically_similar_to": 3,
"rationale_for": 3
},
"input_tokens": 12474,
"output_tokens": 28220,
"cost_usd": 0.0865,
"elapsed_seconds": 781.2,
"chunks_run": 3,
"chunks_failed": 0
},
"nanoGPT": {
"model": "kimi-k2.6",
"chunk_size": 2,
"total_nodes": 28,
"total_edges": 30,
"unique_rel_types": 6,
"relation_types": {
"references": 16,
"semantically_similar_to": 4,
"shares_data_with": 3,
"rationale_for": 3,
"calls": 2,
"conceptually_related_to": 2
},
"input_tokens": 4344,
"output_tokens": 29463,
"cost_usd": 0.0851,
"elapsed_seconds": 915.9,
"chunks_run": 3,
"chunks_failed": 0
}
}
@@ -1,72 +0,0 @@
{
"chunk_4": {
"nanoGPT": {
"node_count": 27,
"edge_count": 31,
"unique_rel_types": 5,
"relation_types": {
"references": 22,
"conceptually_related_to": 3,
"semantically_similar_to": 3,
"calls": 1,
"rationale_for": 2
},
"input_tokens": 2183,
"output_tokens": 14699,
"elapsed_seconds": 418.73,
"cost_usd": 0.0425
},
"httpx": {
"node_count": 20,
"edge_count": 15,
"unique_rel_types": 4,
"relation_types": {
"calls": 7,
"rationale_for": 3,
"conceptually_related_to": 4,
"implements": 1
},
"input_tokens": 3208,
"output_tokens": 15222,
"elapsed_seconds": 405.59,
"cost_usd": 0.0445
}
},
"chunk_8": {
"nanoGPT": {
"node_count": 20,
"edge_count": 21,
"unique_rel_types": 6,
"relation_types": {
"rationale_for": 4,
"references": 8,
"semantically_similar_to": 4,
"calls": 2,
"shares_data_with": 1,
"conceptually_related_to": 2
},
"input_tokens": 3568,
"output_tokens": 15451,
"elapsed_seconds": 327.97,
"cost_usd": 0.0454
},
"httpx": {
"node_count": 52,
"edge_count": 35,
"unique_rel_types": 7,
"relation_types": {
"calls": 6,
"rationale_for": 8,
"references": 2,
"conceptually_related_to": 4,
"cites": 7,
"implements": 2,
"semantically_similar_to": 6
},
"input_tokens": 12303,
"output_tokens": 22718,
"elapsed_seconds": 593.69,
"cost_usd": 0.071
}
}
}
-391
View File
@@ -1,391 +0,0 @@
"""Direct LLM backend for semantic extraction.
Bypasses the Claude Code Agent tool and calls any OpenAI-compatible API directly.
Supports Kimi (Moonshot AI), OpenAI, and Anthropic (via openai-compat proxy).
Usage:
from graphify.llm import extract_files_direct
result = extract_files_direct(
files=[Path("docs/design.md"), Path("src/auth.py")],
backend="kimi",
api_key="sk-...",
)
# result: {"nodes": [...], "edges": [...], "hyperedges": [...],
# "input_tokens": N, "output_tokens": N}
"""
from __future__ import annotations
import json
import time
from pathlib import Path
# ── Backend configs ────────────────────────────────────────────────────────────
BACKENDS: dict[str, dict] = {
"kimi": {
"base_url": "https://api.moonshot.ai/v1",
"default_model": "kimi-k2.5", # 256K context, vision + reasoning
"context_window": 256_000,
# Kimi k2.5 pricing (approximate USD — verify at platform.moonshot.ai):
"input_cost_per_1k": 0.0006,
"output_cost_per_1k": 0.0028,
},
"openai": {
"base_url": "https://api.openai.com/v1",
"default_model": "gpt-4o",
"context_window": 128_000,
"input_cost_per_1k": 0.0025,
"output_cost_per_1k": 0.01,
},
"claude": {
# Claude via official Anthropic SDK (different interface, handled separately)
"base_url": None,
"default_model": "claude-sonnet-4-6",
"context_window": 200_000,
"input_cost_per_1k": 0.003,
"output_cost_per_1k": 0.015,
},
}
# ── Extraction prompt ──────────────────────────────────────────────────────────
_FEW_SHOT_EXAMPLE = """
Example input:
=== FILE: auth/login.py ===
from db import UserDB
def login(username, password):
user = UserDB.find(username)
if user and user.check_password(password):
return generate_token(user)
Example output:
{"nodes":[{"id":"login_login","label":"login","file_type":"code","source_file":"auth/login.py","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null},{"id":"login_userdb","label":"UserDB","file_type":"code","source_file":"auth/login.py","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"login_login","target":"login_userdb","relation":"calls","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"auth/login.py","source_location":null,"weight":1.0}],"hyperedges":[],"input_tokens":0,"output_tokens":0}
Now extract from the files below using the same schema:
"""
_SYSTEM_PROMPT = """You are a graphify extraction agent. Your task: read the file contents and extract a knowledge graph as JSON.
Output ONLY valid JSON — no explanation, no markdown fences, no preamble, no trailing text after the closing brace.
Rules:
- EXTRACTED: relationship explicit in source (import, call, citation, "see §3.2")
- INFERRED: reasonable inference (shared data structure, implied dependency)
- AMBIGUOUS: uncertain - flag for review, do not omit
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.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
Chart: metric, trend/insight, data source.
Tweet/post: claim as node, author, concepts mentioned.
Diagram: components and connections.
Research figure: what it demonstrates, method, result.
Handwritten/whiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS.
Semantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Only add these when the similarity is genuinely non-obvious and cross-cutting.
Hyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Use sparingly — maximum 3 hyperedges per chunk.
If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author, contributor onto every node from that file.
confidence_score is REQUIRED on every edge:
- EXTRACTED edges: confidence_score must be 1.0
- INFERRED edges: score 0.4-0.9 based on how certain you are. Strong structural inference: 0.8-0.9. Reasonable but not certain: 0.6-0.7. Weak: 0.4-0.5.
- AMBIGUOUS edges: score 0.1-0.3
Output exactly this JSON (no other text):
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|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}"""
def _build_user_message(files: list[Path], root: Path | None = None) -> str:
"""Read files and build the user message for extraction."""
parts = []
for f in files:
try:
rel = f.relative_to(root) if root else f
except ValueError:
rel = f
try:
# Skip binary files (PDFs, images handled separately via vision)
if f.suffix.lower() in {".pdf", ".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"}:
parts.append(f"=== FILE: {rel} ===\n[Binary file — skipped in text extraction]")
continue
content = f.read_text(encoding="utf-8", errors="replace")
# Truncate very large files — LLM has context limits even at 128K
if len(content) > 80_000:
content = content[:80_000] + f"\n... [truncated at 80K chars]"
parts.append(f"=== FILE: {rel} ===\n{content}")
except OSError as exc:
parts.append(f"=== FILE: {rel} ===\n[Could not read: {exc}]")
return "\n\n".join(parts)
def _parse_response(text: str) -> dict:
"""Extract JSON from LLM response, tolerating markdown fences."""
text = text.strip()
# Strip ```json fences if present
if text.startswith("```"):
lines = text.splitlines()
# Remove first and last fence lines
inner = lines[1:-1] if lines[-1].strip().startswith("```") else lines[1:]
text = "\n".join(inner).strip()
return json.loads(text)
# ── OpenAI-compatible backends (Kimi, OpenAI) ─────────────────────────────────
def _extract_openai_compat(
files: list[Path],
backend_cfg: dict,
api_key: str,
model: str,
root: Path | None,
) -> dict:
try:
from openai import OpenAI
except ImportError:
raise ImportError("openai package required: pip install openai")
timeout = 2400 if "k2.6" in model else 120
client = OpenAI(api_key=api_key, base_url=backend_cfg["base_url"], timeout=timeout)
user_msg = _build_user_message(files, root)
t0 = time.time()
# kimi-k2.x reasoning models only accept temperature=1
temperature = 1 if "k2" in model else 0.1
# Prepend few-shot example to user message for reasoning models
full_user_msg = (_FEW_SHOT_EXAMPLE + user_msg) if "k2" in model else user_msg
# K2.6 does not support response_format=json_object — it handles JSON via prompt
use_json_format = "k2.6" not in model
kwargs = dict(
model=model,
messages=[
{"role": "system", "content": _SYSTEM_PROMPT},
{"role": "user", "content": full_user_msg},
],
temperature=temperature,
max_tokens=32768 if "k2.6" in model else 16384,
)
if use_json_format:
kwargs["response_format"] = {"type": "json_object"}
response = client.chat.completions.create(**kwargs)
elapsed = time.time() - t0
msg = response.choices[0].message
raw = msg.content or ""
# Reasoning models (kimi-k2.5) may put the answer in reasoning_content
# and leave content empty — fall back to it
if not raw.strip():
raw = getattr(msg, "reasoning_content", "") or ""
# Some providers wrap JSON in a finish_reason=stop with content in tool_calls
if not raw.strip() and response.choices[0].finish_reason:
import pprint
raise ValueError(
f"Empty response from model.\n"
f"finish_reason={response.choices[0].finish_reason!r}\n"
f"message fields: {[k for k in vars(msg) if getattr(msg, k)]}"
)
usage = response.usage
try:
result = _parse_response(raw)
except (json.JSONDecodeError, ValueError) as exc:
raise ValueError(f"Backend returned invalid JSON: {exc}\nRaw response (first 500 chars):\n{raw[:500]}")
result["input_tokens"] = usage.prompt_tokens if usage else 0
result["output_tokens"] = usage.completion_tokens if usage else 0
result["elapsed_seconds"] = round(elapsed, 2)
result["model"] = model
result["backend"] = backend_cfg.get("base_url", "unknown")
return result
# ── Claude via claude CLI (no API key needed inside Claude Code) ───────────────
def _extract_claude(
files: list[Path],
api_key: str | None,
model: str,
root: Path | None,
) -> dict:
"""Extract using claude CLI subprocess — works inside Claude Code without an API key."""
import subprocess
import tempfile
user_msg = _build_user_message(files, root)
prompt = _SYSTEM_PROMPT + "\n\n" + user_msg
t0 = time.time()
# Pass prompt via stdin to avoid OS arg length limits
proc = subprocess.run(
["claude", "-p", "-", "--model", model, "--output-format", "text"],
input=prompt,
capture_output=True, text=True, timeout=300,
encoding="utf-8", errors="replace",
)
raw = proc.stdout.strip()
if proc.returncode != 0 and not raw:
raise RuntimeError(f"claude CLI failed (exit {proc.returncode}): {proc.stderr[:300]}")
elapsed = time.time() - t0
try:
result = _parse_response(raw)
except (json.JSONDecodeError, ValueError) as exc:
raise ValueError(f"Backend returned invalid JSON: {exc}\nRaw response (first 500 chars):\n{raw[:500]}")
# Estimate tokens (claude CLI doesn't return usage counts)
result["input_tokens"] = len(prompt) // 4
result["output_tokens"] = len(raw) // 4
result["elapsed_seconds"] = round(elapsed, 2)
result["model"] = model
result["backend"] = "claude-cli"
return result
# ── Public API ─────────────────────────────────────────────────────────────────
def extract_files_direct(
files: list[Path],
backend: str,
api_key: str,
model: str | None = None,
root: Path | None = None,
) -> dict:
"""Extract knowledge graph from files using a direct LLM API call.
Args:
files: list of file paths to extract from (one API call per batch)
backend: "kimi", "openai", or "claude"
api_key: API key for the backend
model: override the default model for this backend
root: project root for relative path display
Returns:
dict with nodes, edges, hyperedges, input_tokens, output_tokens,
elapsed_seconds, model, backend
"""
if backend not in BACKENDS:
raise ValueError(f"Unknown backend {backend!r}. Choose from: {list(BACKENDS)}")
cfg = BACKENDS[backend]
chosen_model = model or cfg["default_model"]
if backend == "claude":
return _extract_claude(files, api_key, chosen_model, root)
else:
return _extract_openai_compat(files, cfg, api_key, chosen_model, root)
def estimate_cost(backend: str, input_tokens: int, output_tokens: int) -> float:
"""Estimate USD cost for a completed extraction call."""
cfg = BACKENDS.get(backend, {})
input_cost = (input_tokens / 1000) * cfg.get("input_cost_per_1k", 0)
output_cost = (output_tokens / 1000) * cfg.get("output_cost_per_1k", 0)
return round(input_cost + output_cost, 6)
def _chunk_files(files: list[Path], chunk_size: int) -> list[list[Path]]:
return [files[i:i + chunk_size] for i in range(0, len(files), chunk_size)]
_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff", ".svg"}
def _split_into_chunks(files: list[Path], chunk_size: int = 22) -> list[list[Path]]:
"""Mirror graphify skill chunking: 20-25 files per chunk, images get their own chunk."""
images = [f for f in files if f.suffix.lower() in _IMAGE_EXTENSIONS]
non_images = [f for f in files if f.suffix.lower() not in _IMAGE_EXTENSIONS]
chunks = _chunk_files(non_images, chunk_size)
# Each image is its own chunk (vision needs isolated context)
chunks += [[img] for img in images]
return chunks
def extract_corpus_parallel(
files: list[Path],
backend: str,
api_key: str,
model: str | None = None,
root: Path | None = None,
chunk_size: int = 22,
max_workers: int = 5,
on_chunk_done: "callable | None" = None,
) -> dict:
"""Extract a full corpus in parallel — mirrors graphify's multi-subagent dispatch.
Splits files into chunks of 20-25 (images solo), fires all chunks simultaneously
via ThreadPoolExecutor (max_workers parallel API calls), then merges results.
Args:
files: all files to extract from
backend: "kimi", "openai", or "claude"
api_key: API key for the backend
model: override default model
root: project root for relative path display
chunk_size: non-image files per API call (default 22, matching graphify skill)
max_workers: max parallel API calls (default 5)
on_chunk_done: optional callback(chunk_idx, total, result) for progress reporting
Returns:
merged dict with nodes, edges, hyperedges, input_tokens, output_tokens
"""
from concurrent.futures import ThreadPoolExecutor, as_completed
chunks = _split_into_chunks(files, chunk_size)
total = len(chunks)
all_nodes: list[dict] = []
all_edges: list[dict] = []
all_hyperedges: list[dict] = []
total_input = 0
total_output = 0
failed = 0
def _call(idx_chunk: tuple[int, list[Path]]) -> tuple[int, dict | Exception]:
idx, chunk = idx_chunk
try:
result = extract_files_direct(chunk, backend, api_key, model, root)
return idx, result
except Exception as exc:
return idx, exc
with ThreadPoolExecutor(max_workers=max_workers) as pool:
futures = {pool.submit(_call, (i, chunk)): i for i, chunk in enumerate(chunks)}
for future in as_completed(futures):
idx, result = future.result()
if isinstance(result, Exception):
print(f" [chunk {idx+1}/{total}] FAILED: {result}", flush=True)
failed += 1
else:
# Deduplicate nodes by id
seen = {n["id"] for n in all_nodes}
for n in result.get("nodes", []):
if n["id"] not in seen:
all_nodes.append(n)
seen.add(n["id"])
all_edges.extend(result.get("edges", []))
all_hyperedges.extend(result.get("hyperedges", []))
total_input += result.get("input_tokens", 0)
total_output += result.get("output_tokens", 0)
if on_chunk_done:
on_chunk_done(idx, total, result)
if failed > total // 2:
raise RuntimeError(f"More than half the chunks failed ({failed}/{total}). Aborting.")
return {
"nodes": all_nodes,
"edges": all_edges,
"hyperedges": all_hyperedges,
"input_tokens": total_input,
"output_tokens": total_output,
"chunks_total": total,
"chunks_failed": failed,
}
-125
View File
@@ -1,125 +0,0 @@
#!/usr/bin/env python3
"""Run Kimi K2.6 extraction across the same corpora/files used in the K2.5 benchmark."""
from __future__ import annotations
import json, sys, time, random
from collections import Counter
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from llm import extract_files_direct, estimate_cost
KIMI_KEY = "sk-5rsh69xqeq2JRREJzelnTcnkxpn2hMcZdRpBb0iVgabnJ7br"
MODEL = "kimi-k2.6"
CHUNK = 2 # files per call, same as previous benchmark
CORPORA = {
"httpx": Path("/home/safi/graphify_eval/codebase/httpx"),
"click": Path("/home/safi/graphify_eval/codebase/click"),
"rich": Path("/home/safi/graphify_eval/codebase/rich"),
"nanoGPT": Path("/home/safi/graphify_eval/mixed/nanoGPT"),
}
_SKIP = {".git","graphify-out","venv",".venv","build","dist","__pycache__",".pytest_cache","node_modules","egg-info"}
_EXT = {".py",".ts",".js",".go",".rs",".java",".c",".cpp",".rb",".cs",
".md",".txt",".rst",".php",".swift",".kt",".scala",".lua",".zig"}
def pick(path: Path, n: int = 60, seed: int = 42) -> list[Path]:
candidates = [p for p in sorted(path.rglob("*"))
if p.is_file()
and p.suffix.lower() in _EXT
and not any(x in _SKIP or x.endswith(".egg-info") for x in p.parts)]
random.seed(seed)
random.shuffle(candidates)
return candidates[:n]
def chunk(lst, size):
return [lst[i:i+size] for i in range(0, len(lst), size)]
def analyze(result):
nodes = result.get("nodes", [])
edges = result.get("edges", [])
return {
"node_count": len(nodes),
"edge_count": len(edges),
"relation_types": dict(Counter(e.get("relation","") for e in edges)),
"node_labels": [n.get("label", n.get("id","")) for n in nodes],
"input_tokens": result.get("input_tokens", 0),
"output_tokens": result.get("output_tokens", 0),
"elapsed_seconds":result.get("elapsed_seconds", 0),
}
results = {}
for corpus, path in CORPORA.items():
print(f"\n{'='*60}")
print(f" {corpus} ({MODEL})")
print(f"{'='*60}")
files = pick(path)
chunks = chunk(files, CHUNK)[:3] # 3 chunks per corpus = 6 files
print(f" {len(files)} files sampled → {len(chunks)} chunks of {CHUNK}")
all_nodes, all_edges, rel_types = [], [], Counter()
total_in, total_out, total_cost, total_time = 0, 0, 0.0, 0.0
failed = 0
for i, ch in enumerate(chunks):
print(f" chunk {i+1}/{len(chunks)}: {[f.name for f in ch]} ...", end=" ", flush=True)
try:
r = extract_files_direct(ch, backend="kimi", api_key=KIMI_KEY, model=MODEL, root=path)
m = analyze(r)
all_nodes.extend(m["node_labels"])
all_edges.append(m["edge_count"])
rel_types.update(m["relation_types"])
total_in += m["input_tokens"]
total_out += m["output_tokens"]
cost = estimate_cost("kimi", m["input_tokens"], m["output_tokens"])
total_cost += cost
total_time += m["elapsed_seconds"]
print(f"nodes={m['node_count']} edges={m['edge_count']} rel_types={len(m['relation_types'])} cost=${cost:.4f} t={m['elapsed_seconds']:.1f}s")
except Exception as exc:
print(f"FAILED: {exc}")
failed += 1
results[corpus] = {
"model": MODEL,
"chunk_size": CHUNK,
"total_nodes": len(all_nodes),
"total_edges": sum(all_edges),
"unique_rel_types":len(rel_types),
"relation_types": dict(rel_types.most_common()),
"input_tokens": total_in,
"output_tokens": total_out,
"cost_usd": round(total_cost, 4),
"elapsed_seconds": round(total_time, 1),
"chunks_run": len(chunks) - failed,
"chunks_failed": failed,
}
print(f"\n TOTAL: nodes={results[corpus]['total_nodes']} edges={results[corpus]['total_edges']} "
f"rel_types={results[corpus]['unique_rel_types']} cost=${results[corpus]['cost_usd']:.4f}")
out = Path("scripts/benchmark_kimi_k2.6.json")
out.write_text(json.dumps(results, indent=2))
print(f"\n\nResults saved to {out}")
# Print comparison table vs K2.5 results
k25_ref = {
"httpx": {"total_nodes": 877+502+370, "total_edges": 907+543+358, "unique_rel_types": 48, "cost_usd": 0.72+0.47+0.40},
"click": {"total_nodes": 653+540+310, "total_edges": 637+470+231, "unique_rel_types": 44, "cost_usd": 0.67+0.50+0.36},
"rich": {"total_nodes": 447+397+311, "total_edges": 446+397+294, "unique_rel_types": 35, "cost_usd": 0.62+0.53+0.44},
"nanoGPT": {"total_nodes": 183+126+100+103, "total_edges": 222+148+107+101, "unique_rel_types": 36, "cost_usd": 0.25+0.16+0.11+0.09},
}
print(f"\n{'='*70}")
print(f" Kimi K2.5 vs K2.6 — same corpora, chunk={CHUNK}")
print(f"{'─'*70}")
print(f" {'Corpus':<10} {'K2.5 nodes':>12} {'K2.6 nodes':>12} {'K2.5 rel':>10} {'K2.6 rel':>10} {'K2.5 $':>8} {'K2.6 $':>8}")
print(f"{'─'*70}")
for corpus in CORPORA:
r = results[corpus]
ref = k25_ref[corpus]
print(f" {corpus:<10} {ref['total_nodes']:>12} {r['total_nodes']:>12} "
f"{ref['unique_rel_types']:>10} {r['unique_rel_types']:>10} "
f"${ref['cost_usd']:>7.2f} ${r['cost_usd']:>7.4f}")
print(f"{'='*70}")
-120
View File
@@ -1,120 +0,0 @@
#!/usr/bin/env python3
"""
Kimi K2.6 large-context benchmark — 2 corpora, chunk=4 and chunk=8.
K2.5 reference (from previous benchmark):
httpx chunk=4: nodes=502, edges=543, rel_types=34
httpx chunk=8: nodes=370, edges=358, rel_types=37
nanoGPT chunk=4: nodes=100, edges=107, rel_types=24
nanoGPT chunk=8: nodes=103, edges=101, rel_types=26
Claude Sonnet reference (chunk=4 and chunk=8):
httpx chunk=4: nodes=417, rel_types=8
httpx chunk=8: nodes=290, rel_types=7
nanoGPT chunk=4: nodes=108, rel_types=8
nanoGPT chunk=8: nodes=83, rel_types=8
"""
from __future__ import annotations
import json, sys, time, random
from collections import Counter
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from llm import extract_files_direct, estimate_cost
KIMI_KEY = "sk-5rsh69xqeq2JRREJzelnTcnkxpn2hMcZdRpBb0iVgabnJ7br"
MODEL = "kimi-k2.6"
CORPORA = {
"nanoGPT": Path("/home/safi/graphify_eval/mixed/nanoGPT"),
"httpx": Path("/home/safi/graphify_eval/codebase/httpx"),
}
CHUNK_SIZES = [4, 8]
_SKIP = {".git","graphify-out","venv",".venv","build","dist","__pycache__",
".pytest_cache","node_modules","egg-info"}
_EXT = {".py",".ts",".js",".go",".rs",".java",".c",".cpp",".rb",".cs",
".md",".txt",".rst",".php",".swift",".kt",".scala",".lua",".zig"}
def pick(path: Path, n: int = 60, seed: int = 42) -> list[Path]:
candidates = [p for p in sorted(path.rglob("*"))
if p.is_file()
and p.suffix.lower() in _EXT
and not any(x in _SKIP or x.endswith(".egg-info") for x in p.parts)]
random.seed(seed)
random.shuffle(candidates)
return candidates[:n]
def analyze(result):
nodes = result.get("nodes", [])
edges = result.get("edges", [])
return {
"node_count": len(nodes),
"edge_count": len(edges),
"unique_rel_types":len(set(e.get("relation","") for e in edges)),
"relation_types": dict(Counter(e.get("relation","") for e in edges)),
"input_tokens": result.get("input_tokens", 0),
"output_tokens": result.get("output_tokens", 0),
"elapsed_seconds": result.get("elapsed_seconds", 0),
}
all_results = {}
for chunk_size in CHUNK_SIZES:
print(f"\n{'#'*65}")
print(f" CHUNK = {chunk_size} files")
print(f"{'#'*65}")
chunk_results = {}
for corpus, path in CORPORA.items():
files = pick(path)
batch = files[:chunk_size]
print(f"\n [{corpus}] sending {len(batch)} files...", end=" ", flush=True)
try:
r = extract_files_direct(batch, backend="kimi", api_key=KIMI_KEY,
model=MODEL, root=path)
m = analyze(r)
cost = estimate_cost("kimi", m["input_tokens"], m["output_tokens"])
print(f"nodes={m['node_count']} edges={m['edge_count']} "
f"rel_types={m['unique_rel_types']} "
f"tokens={m['input_tokens']:,}in/{m['output_tokens']:,}out "
f"cost=${cost:.4f} t={m['elapsed_seconds']:.1f}s")
chunk_results[corpus] = {**m, "cost_usd": round(cost, 4)}
except Exception as exc:
print(f"FAILED: {exc}")
chunk_results[corpus] = {"error": str(exc)}
all_results[f"chunk_{chunk_size}"] = chunk_results
out = Path("scripts/benchmark_kimi_k2.6_largechunk.json")
out.write_text(json.dumps(all_results, indent=2))
print(f"\nResults saved to {out}")
# Reference data
REF = {
"K2.5": {
4: {"httpx": (502, 34), "nanoGPT": (100, 24)},
8: {"httpx": (370, 37), "nanoGPT": (103, 26)},
},
"Sonnet": {
4: {"httpx": (417, 8), "nanoGPT": (108, 8)},
8: {"httpx": (290, 7), "nanoGPT": (83, 8)},
},
}
print(f"\n{'='*75}")
print(f" Relation-type diversity — K2.6 vs K2.5 vs Claude Sonnet 4.6")
print(f"{'─'*75}")
print(f" {'Corpus+Chunk':<18} {'Sonnet nodes':>13} {'Sonnet rel':>11} {'K2.5 nodes':>11} {'K2.5 rel':>9} {'K2.6 nodes':>11} {'K2.6 rel':>9}")
print(f"{'─'*75}")
for chunk_size in CHUNK_SIZES:
for corpus in CORPORA:
k26 = all_results.get(f"chunk_{chunk_size}", {}).get(corpus, {})
k25n, k25r = REF["K2.5"][chunk_size][corpus]
snn, snr = REF["Sonnet"][chunk_size][corpus]
k26n = k26.get("node_count", "ERR")
k26r = k26.get("unique_rel_types", "ERR")
label = f"{corpus} @{chunk_size}"
print(f" {label:<18} {snn:>13} {snr:>11} {k25n:>11} {k25r:>9} {k26n!s:>11} {k26r!s:>9}")
print(f"{'='*75}")
+21
View File
@@ -29,6 +29,27 @@ def test_ambiguous_edge_preserved():
data = G.edges["n_layernorm", "n_concept_attn"]
assert data["confidence"] == "AMBIGUOUS"
def test_legacy_node_source_canonicalized():
"""Legacy 'source' key on nodes is renamed to 'source_file' before graph build."""
ext = {"nodes": [{"id": "n1", "label": "A", "file_type": "code", "source": "a.py"}],
"edges": [], "input_tokens": 0, "output_tokens": 0}
G = build_from_json(ext)
assert "source_file" in G.nodes["n1"]
assert G.nodes["n1"]["source_file"] == "a.py"
assert "source" not in G.nodes["n1"]
def test_legacy_edge_from_to_canonicalized():
"""Legacy 'from'/'to' keys on edges are accepted alongside 'source'/'target'."""
ext = {"nodes": [{"id": "n1", "label": "A", "file_type": "code", "source_file": "a.py"},
{"id": "n2", "label": "B", "file_type": "code", "source_file": "b.py"}],
"edges": [{"from": "n1", "to": "n2", "relation": "calls",
"confidence": "EXTRACTED", "source_file": "a.py", "weight": 1.0}],
"input_tokens": 0, "output_tokens": 0}
G = build_from_json(ext)
assert G.number_of_edges() == 1
def test_build_merges_multiple_extractions():
ext1 = {"nodes": [{"id": "n1", "label": "A", "file_type": "code", "source_file": "a.py"}],
"edges": [], "input_tokens": 0, "output_tokens": 0}
+27 -1
View File
@@ -3,7 +3,7 @@ import tempfile
from pathlib import Path
from graphify.build import build_from_json
from graphify.cluster import cluster
from graphify.export import to_json, to_cypher, to_graphml, to_html
from graphify.export import to_json, to_cypher, to_graphml, to_html, to_canvas
FIXTURES = Path(__file__).parent / "fixtures"
@@ -125,3 +125,29 @@ def test_to_html_contains_nodes_and_edges():
content = out.read_text()
assert "RAW_NODES" in content
assert "RAW_EDGES" in content
def test_to_html_member_counts_accepted():
"""to_html accepts member_counts without raising."""
G = make_graph()
communities = cluster(G)
member_counts = {cid: len(members) for cid, members in communities.items()}
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.html"
to_html(G, communities, str(out), member_counts=member_counts)
assert out.exists()
def test_to_canvas_file_paths_relative_to_vault():
"""Node file paths in canvas must be vault-root-relative (just fname.md), not hardcoded."""
G = make_graph()
communities = cluster(G)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.canvas"
to_canvas(G, communities, str(out))
data = json.loads(out.read_text())
file_nodes = [n for n in data["nodes"] if n.get("type") == "file"]
assert file_nodes, "canvas should contain file nodes"
for node in file_nodes:
assert "/" not in node["file"], f"file path should not contain '/': {node['file']}"
assert node["file"].endswith(".md")
+6
View File
@@ -117,3 +117,9 @@ def test_status_shows_both_hooks(tmp_path):
assert "post-commit" in result
assert "post-checkout" in result
assert result.count("installed") >= 2
def test_hook_skips_head_on_exe():
"""Hook script must skip shebang extraction for .exe binaries (Windows)."""
from graphify.hooks import _PYTHON_DETECT
assert "*.exe) _SHEBANG=" in _PYTHON_DETECT or '*.exe)' in _PYTHON_DETECT
+6 -5
View File
@@ -194,9 +194,9 @@ def test_opencode_agents_install_writes_plugin(tmp_path):
def test_opencode_agents_install_registers_plugin_in_config(tmp_path):
"""opencode install registers the plugin in opencode.json."""
"""opencode install registers the plugin in .opencode/opencode.json."""
_agents_install(tmp_path, "opencode")
config_file = tmp_path / "opencode.json"
config_file = tmp_path / ".opencode" / "opencode.json"
assert config_file.exists()
import json as _json
config = _json.loads(config_file.read_text())
@@ -204,9 +204,10 @@ def test_opencode_agents_install_registers_plugin_in_config(tmp_path):
def test_opencode_agents_install_merges_existing_config(tmp_path):
"""opencode install preserves existing opencode.json keys."""
"""opencode install preserves existing .opencode/opencode.json keys."""
import json as _json
config_file = tmp_path / "opencode.json"
config_file = tmp_path / ".opencode" / "opencode.json"
config_file.parent.mkdir(parents=True, exist_ok=True)
config_file.write_text(_json.dumps({"model": "claude-opus-4-5", "plugin": []}))
_agents_install(tmp_path, "opencode")
config = _json.loads(config_file.read_text())
@@ -221,7 +222,7 @@ def test_opencode_agents_uninstall_removes_plugin(tmp_path):
_agents_uninstall(tmp_path, platform="opencode")
plugin = tmp_path / ".opencode" / "plugins" / "graphify.js"
assert not plugin.exists()
config_file = tmp_path / "opencode.json"
config_file = tmp_path / ".opencode" / "opencode.json"
if config_file.exists():
config = _json.loads(config_file.read_text())
assert not any("graphify.js" in p for p in config.get("plugin", []))
+28
View File
@@ -52,6 +52,34 @@ def test_watched_extensions_excludes_noise():
# --- watch() import error without watchdog ---
def test_check_update_no_flag_returns_true(tmp_path):
"""check_update returns True and is silent when needs_update flag is absent."""
from graphify.watch import check_update
assert check_update(tmp_path) is True
def test_check_update_with_flag_returns_true_and_prints(tmp_path, capsys):
"""check_update returns True and prints notification when flag exists."""
from graphify.watch import check_update
flag = tmp_path / "graphify-out" / "needs_update"
flag.parent.mkdir(parents=True, exist_ok=True)
flag.write_text("1")
result = check_update(tmp_path)
assert result is True
out = capsys.readouterr().out
assert "graphify --update" in out
def test_check_update_does_not_clear_flag(tmp_path):
"""check_update never removes the needs_update flag (clearing is LLM's job)."""
from graphify.watch import check_update
flag = tmp_path / "graphify-out" / "needs_update"
flag.parent.mkdir(parents=True, exist_ok=True)
flag.write_text("1")
check_update(tmp_path)
assert flag.exists()
def test_watch_raises_without_watchdog(tmp_path, monkeypatch):
import builtins
real_import = builtins.__import__