Compare commits

...
144 Commits
Author SHA1 Message Date
SafiandClaude Sonnet 4.6 2246e461a9 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 7ab62fd14a 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 9866cbc4af 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 2736e05714 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 5c77d9cc4a 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 9c04b059be docs: add Verilog/SystemVerilog to language count and list 2026-04-14 09:36:57 +01:00
SafiandClaude Sonnet 4.6 79a9200f09 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 41544c7076 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 c657eb2049 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 9fd6810e4e 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 e441454c55 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 962f28c603 docs: add Hermes platform, Dart to language list, 22→23 languages 2026-04-13 08:46:20 +01:00
SafiandClaude Sonnet 4.6 7c81c1b889 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 04e2960135 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 c713cf89fd 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 6b2d38358b 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 2499a1c377 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 0a4e6915c1 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 efce74dada update README: 22 languages, add .vue and .svelte to file types table 2026-04-12 13:02:45 +01:00
SafiandClaude Sonnet 4.6 4205ae86cb 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 013313f8d6 add LinkedIn badge to README 2026-04-11 21:15:32 +01:00
Safi b4d4ac8e9b add 0.4.2 CHANGELOG entry 2026-04-11 21:10:45 +01:00
SafiandClaude Sonnet 4.6 62aac4f868 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 3c503400cb 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 625ca0e2f3 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 271ee0aff6 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 0e453083de 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 209224d08c 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 fa388c8556 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 3ce9bdabf4 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 68bb2bd3dc 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 699e9960ce 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 2c21bc0488 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 a2872cafac 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 f758911b10 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 79acb7e46a 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 210243fa58 fix hook reinstall, CRLF labels, skill-windows missing commands (0.3.28) 2026-04-10 10:07:11 +01:00
Safi f7ee752eb1 switch downloads badge to pepy.tech to avoid shields.io rate limit 2026-04-10 09:49:50 +01:00
Safi af3a3d2157 update README Gemini CLI description to mention skill file copy 2026-04-10 01:29:05 +01:00
Safi 55964bc0b1 fix gemini install missing skill file copy (0.3.27) 2026-04-10 01:28:19 +01:00
Safi a0a196e1af update README to list all platforms including Aider, Copilot CLI, Cursor, Gemini in CLI section 2026-04-10 01:09:35 +01:00
Safi 863100cb06 fix MCP server path validation security issue (0.3.26) 2026-04-10 01:08:15 +01:00
SafiandClaude Sonnet 4.6 1cbcee539f 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 cf39034744 Remove Trendshift badge (API not available) 2026-04-09 22:46:47 +01:00
Safi e440539305 Add Trendshift badge to README 2026-04-09 22:45:52 +01:00
Safi ee43236c16 Fix codex/opencode install idempotency — always run hook step (#153) 2026-04-09 17:59:16 +01:00
Safi 54c6d04b75 Switch star history to star-history.com for faster updates 2026-04-09 17:46:34 +01:00
Safi 687fbc810a Update README: add Cursor and Gemini CLI to all platform sections 2026-04-09 17:44:59 +01:00
SafiandClaude Sonnet 4.6 dcc402e140 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 0b8067c9d1 Add Cursor to description, README intro, and PyPI keywords 2026-04-09 17:25:36 +01:00
SafiandClaude Sonnet 4.6 f770712704 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 a104a0d9fc Add monthly PyPI downloads badge to README 2026-04-09 14:46:13 +01:00
SafiandClaude Sonnet 4.6 6f9fc65af4 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 b101a99d2f 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 b7fd5acc38 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 38255e733f 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 e1864d79c8 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 3501605242 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 096a76f314 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 f140d4786d 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 4d8cffef47 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 29c639d97d 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 11dff7e9b3 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 ec4f6845aa add Korean README and fix trae.com link across all READMEs 2026-04-09 08:00:07 +01:00
Safi 1a50f2d12b add Penpax link to README 2026-04-09 01:14:08 +01:00
SafiandClaude Sonnet 4.6 8dbf953016 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 dd8235e0b5 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 23d88c55b0 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 30a66ec1f4 fix: switch star history chart to starchart.cc (no auth required) 2026-04-08 20:06:06 +01:00
Safi 0dc125d09a release: 0.3.15 — Trae platform, security hardening, pipx hooks, PowerShell fix 2026-04-08 20:00:05 +01:00
Safi 6a3b4bb39b fix: shebang allowlist validation in all skill files 2026-04-08 19:57:33 +01:00
Safi 1cc54b3bbf fix: XSS in legend innerHTML and shebang allowlist in hooks 2026-04-08 19:53:10 +01:00
Safi b64c231467 fix: skill-droid.md missing from package-data, louvain kwargs version-safe 2026-04-08 19:47:07 +01:00
ljinshuanandlijinshuan f4c3c551e1 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 74e192db00 docs: add Japanese README 2026-04-08 19:40:33 +01:00
gdesai23 312ba0dd1e docs: add graph.json + LLM workflow example to README 2026-04-08 19:40:29 +01:00
azizur100389andClaude Opus 4.6 8a0dd45711 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 785c9f4dd7 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
Safi 2d64c0cd10 fix: Codex PreToolUse hook + --update ghost node pruning (#86, #51) 2026-04-08 19:29:33 +01:00
Safi bd24ddb1d6 fix: hook JSON format, Go pkg scoping, xcassets PDF, cross-file guard, skill file paths (#83, #85, #52, #81) 2026-04-08 19:20:48 +01:00
Safi ffd8906c6c fix: ensure Cypher node label always starts with a letter (#84) 2026-04-08 19:02:05 +01:00
Safi 92b70ce5f4 fix: sanitize_label double-encoding and --wiki missing from skill (#66, #55) 2026-04-08 09:40:21 +01:00
Safi 3d53287ff6 Fix Louvain fallback hang on large sparse graphs (#48) 2026-04-07 22:36:45 +01:00
Safi 96ea51c098 Bump version to 0.3.10 2026-04-07 21:20:11 +01:00
Safi fec0f9fca9 Fix Windows Unicode crash and add skill version staleness check (#47, #46) 2026-04-07 21:18:50 +01:00
Safi 1383fb0739 Update README: add graphify query CLI, 19 language count, Factory Droid in repo About 2026-04-07 20:25:47 +01:00
SafiandClaude Sonnet 4.6 a78d25d4fc Add ObjC support, C# inheritance, CLI query, symlink support, bug fixes (v0.3.7-0.3.9)
- Add Objective-C extractor (.m/.mm) with @interface, @implementation, @protocol, imports, calls
- Add C# inheritance extraction via base_list nodes (inherits edges)
- Add --obsidian-dir flag to skill.md and skill-windows.md
- Add graphify query CLI command with --dfs, --budget, --graph flags
- Add follow_symlinks parameter to detect() and collect_files() with cycle detection
- Fix semantic cache relative path resolution (was saving only 4/17 files)
- Fix validate.py missing rationale file_type causing 75 warnings per run
- Add tree-sitter-objc dependency
- Update README with .m/.mm extensions, --obsidian-dir usage, Codex $ skill trigger
- 367 tests passing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 20:20:49 +01:00
Safi 3d5da6039a Add Elixir language support (.ex/.exs)
Extracts defmodule, def/defp, alias/import/require/use, and call graph.
Follows same custom-walk pattern as Zig and PowerShell extractors.
2026-04-07 12:54:12 +01:00
Safi f6dd049cb0 Add .docx and .xlsx support via optional [office] extra
python-docx converts .docx to markdown (headings, lists, tables).
openpyxl converts .xlsx sheets to markdown tables. Both are
pre-converted to .md sidecars in graphify-out/converted/ before
semantic extraction - no skill changes needed. Graceful fallback
if [office] not installed: file is skipped with an install hint.
2026-04-07 12:38:03 +01:00
Safi a06313a0f9 Fix UnicodeDecodeError on Windows GBK locale: add encoding=utf-8 to all read_text/write_text calls 2026-04-07 11:54:54 +01:00
Safi db2d297296 Add Windows support: skill-windows.md with PowerShell-compatible commands
graphify install now auto-detects Windows and installs the Windows skill
variant. skill-windows.md replaces bash-specific commands (which, head, tr,
rm -f, mkdir -p) with PowerShell equivalents. Bumps to v0.3.3.
2026-04-07 11:30:08 +01:00
Safi abd55cca9a Add GitHub Sponsors badge to README 2026-04-07 10:50:59 +01:00
Safi e5e93c8180 Add GitHub Sponsors funding config 2026-04-07 10:46:36 +01:00
Safi 1a109afdce Add star history chart to README 2026-04-07 10:33:31 +01:00
Safi d7230a24c3 bump version to 0.3.2 2026-04-07 09:59:01 +01:00
Safi 9d998cc810 Add Zig and PowerShell language support 2026-04-07 09:56:53 +01:00
Safi f2423bc114 Add .graphifyignore support for excluding files and directories 2026-04-07 09:41:01 +01:00
Safi b079c6713a Add Factory Droid platform support 2026-04-07 09:34:28 +01:00
Safi 8c1d5e8114 Update SECURITY.md: supported versions, SSRF and YAML injection mitigations 2026-04-06 22:38:02 +01:00
Safi 808cd98395 Fix YAML injection in webpage title and query frontmatter 2026-04-06 22:35:19 +01:00
Safi e7bd4f38ee bump version to 0.3.1 2026-04-06 22:24:21 +01:00
Safi c529e2217f Fix 8 bugs: SSRF in tweet fetch, Cypher injection, XSS in community labels, graph_diff edge ordering, cache key collision, hook uninstall correctness, watch mode set, rebuild word count 2026-04-06 22:23:55 +01:00
Safi 4e844ea907 Update README: git hook failure behavior 2026-04-06 22:23:55 +01:00
Safi 148e247662 Fix 6 bugs: hook exit code, token budget, file node detection, duplicate function, atomic cache writes, deleted file tracking 2026-04-06 22:23:55 +01:00
Safi 9eda1558c2 feat: Lua language support 2026-04-06 21:59:38 +01:00
Safi 79b8d8d9b2 docs: add Simplified Chinese README
Add a Chinese README translation and link it from the main README for easier language discovery.
2026-04-06 21:59:38 +01:00
Safi 477465ae0d feat: Swift language support
* feat: add Swift language support

Add tree-sitter-swift extractor for classes, structs, protocols,
functions, imports, and call graph edges. Includes 8 passing tests.

* feat: full Swift AST support — enums, extensions, actors, conformance

- Enums: extract enum types, methods, and cases (case_of edges)
- Extensions: methods attach to the original type (no duplicate nodes)
- Actors: recognized via unified class_declaration node type
- Conformance/inheritance: inherits edges from : Protocol syntax
- deinit/subscript: name resolution for nameless declarations
- 12 new tests (110 total, all passing)
2026-04-06 21:59:38 +01:00
Safi 404674a24a security: SSRF private IP blocking and Neo4j Cypher injection fix
Two targeted security hardening changes:

1. SSRF: validate_url() now resolves hostnames and blocks private/reserved
   IP ranges (127.x, 10.x, 169.254.x, etc.) and cloud metadata endpoints.
   Prevents SSRF attacks in cloud environments where a URL like
   http://169.254.169.254/latest/meta-data/ could leak instance credentials.

2. Neo4j Cypher injection: Node labels (file_type) are now sanitized to
   alphanumeric + underscore before interpolation into Cypher queries.
   Previously, attacker-controlled file_type metadata could inject
   arbitrary Cypher in team/shared graph scenarios.

Both changes are zero-impact on normal UX - no new config, no new flags,
no behavioral changes for legitimate use.
2026-04-06 21:59:38 +01:00
Safi 934957cbfd update worked example READMEs for v3 multi-platform 2026-04-06 16:20:13 +01:00
Safi e11d04f8c2 explain always-on vs explicit trigger in README 2026-04-06 16:15:51 +01:00
Safi 1a54f16b80 feat: always-on hooks and README updates for all platforms 2026-04-06 16:06:31 +01:00
Safi aed4a981a1 v3: MIT license, multi-platform packaging and CI 2026-04-06 16:06:31 +01:00
Safi 3694822040 document node deduplication strategy in build.py 2026-04-06 16:06:31 +01:00
Safi 5461feb7e8 refactor extract.py: LanguageConfig + _extract_generic replaces 10 copy-pasted extractors (2527 → 1588 lines) 2026-04-06 16:06:31 +01:00
Safi 6570488658 fix build() dropping hyperedges when merging multiple extractions 2026-04-06 16:06:31 +01:00
Safi 38d967fc63 feat: multi-platform skill files and install routing (Codex, OpenCode, OpenClaw) 2026-04-06 16:06:31 +01:00
Safi 07de9d5c22 fix: use correct Python interpreter for pipx installs 2026-04-06 16:06:31 +01:00
Safi c1bf6c90dc fix graspologic optional, fall back to networkx louvain, add privacy section 2026-04-06 16:06:31 +01:00
Safi 4ba8198c7c v2.1: PyPI release and CI for v2 branch 2026-04-06 16:06:31 +01:00
Safi c46a4ebb68 README: fix CI badge to v2, update curl URL, add how it works, graphify claude install section 2026-04-06 16:06:31 +01:00
Safi 0ee77c0b6a bump version to 0.2.0 2026-04-06 16:06:31 +01:00
Safi 317d73f8f7 v2: confidence scores, hyperedges, rationale extraction, git hooks, Claude Code hooks
- confidence_score required on every edge (INFERRED: 0.4-0.9, EXTRACTED: 1.0, AMBIGUOUS: 0.1-0.3)
- semantically_similar_to edges for non-obvious cross-file conceptual links
- hyperedges for 3+ node group relationships - fixed cache and merge pipeline that was silently dropping them
- check_semantic_cache returns 4-tuple including cached_hyperedges
- extract.py: mine the "why" - module/class/function docstrings and rationale comments (# NOTE: # IMPORTANT: # HACK: # WHY: # RATIONALE: # TODO: # FIXME:) as rationale_for nodes
- skill.md: rationale_for in relation schema, doc files extract design rationale
- obsidian output opt-in (--obsidian flag) - default output is graph.html + graph.json + GRAPH_REPORT.md only
- hooks.py: post-checkout hook added alongside post-commit - graph rebuilds on branch switch
- claude install: writes .claude/settings.json PreToolUse hook on Glob/Grep - Claude checks graph before searching raw files
- README updated with all v2 features
2026-04-06 16:06:31 +01:00
Safi 3f8169c807 README: highlight multimodal capability upfront 2026-04-06 16:06:31 +01:00
Safi 3a117c93e8 v2: hypergraph support - hyperedges in graph.json, shaded regions in HTML, report section 2026-04-06 16:06:31 +01:00
Safi 6fa4c7e662 v2: semantic similarity edges, scored higher in surprising connections 2026-04-06 16:06:31 +01:00
Safi dafe6c9f03 v2: confidence scores on INFERRED edges, avg shown in report 2026-04-06 16:06:31 +01:00
Safi 7e3da961a9 v2: fast --update for code-only changes, parallel AST+semantic, graphify claude install 2026-04-06 16:06:31 +01:00
Safi 63d80200c5 README: clarify any folder works, clean up usage section 2026-04-06 16:06:31 +01:00
Safi 66f1f40de8 add git commit hook - auto-rebuilds graph after every commit 2026-04-06 16:06:31 +01:00
Safi e2fd4f944e watch: auto-rebuild graph on code changes without LLM, notify on doc/image changes 2026-04-06 16:06:31 +01:00
Safi 21e443e201 Add reproducible worked example with 7 input files and README 2026-04-06 16:06:31 +01:00
Safi d213c03adf Add --wiki export: agent-crawlable knowledge wiki from graph 2026-04-06 16:06:31 +01:00
Safi 92ab83ea38 Use graph.json for follow-up questions; bump to 0.1.6 2026-04-06 16:06:31 +01:00
Safi cb4ec5d39d fix: HTML always generated by default in Step 6, not flag-gated 2026-04-06 16:06:31 +01:00
Safi 010583674e release: 0.1.5 2026-04-06 16:06:31 +01:00
Safi d8b1e82079 fix: 5 skill gaps - graphml usage, manifest timing, graph existence checks, no-viz clarity
- Add --graphml to Usage table (was implemented but undocumented there)
- Remove early manifest save from --update merge step (Step 9 owns it; saving early meant failed pipelines left manifest ahead of graph)
- query/path/explain now check graph.json exists before running, with clear "run /graphify first" message
- --no-viz: clarify it skips both Obsidian vault and HTML (was contradictory)
2026-04-06 16:06:31 +01:00
Safi ef8c2fef50 perf: larger chunks + code-only fast path + timing estimates
- Semantic extraction chunks: 12-15 → 20-25 files (fewer subagent round trips)
- Code-only corpora skip semantic dispatch entirely (AST covers it)
- Print estimated time before extraction so the wait feels intentional
2026-04-06 16:06:31 +01:00
Safi 0f4de8e47f test: add end-to-end pipeline integration test
Covers detect → extract → build → cluster → analyze → report → export
using existing fixtures. AST-only (no LLM calls), catches regressions
in how modules connect, not just individual module behaviour.
2026-04-06 16:06:31 +01:00
Safi 5efcf114ee fix critical install bug, add --graphml to pipeline, update changelog 2026-04-06 16:06:31 +01:00
Safi d4b24d8609 feat: vis.js HTML graph, token reduction benchmark, repo cleanup
- Replace pyvis with custom vis.js renderer: node size by degree,
  click-to-inspect panel with clickable neighbors, search box,
  community filter, physics clustering by community
- HTML graph generated by default on every run (no --html flag needed)
- Token reduction benchmark auto-runs after every /graphify on corpora >5k words
- Fix 292 edge warnings: silently skip stdlib/external edges in build.py
- Fix build() to merge extractions before building (cross-extraction edges were dropped)
- Add 5 HTML renderer tests (223 total)
- Remove unnecessary files: lib/, tests/eval_attention.py, misplaced eval reports
- Add graphify-out/ and .graphify_*.json to .gitignore
- Bump version to 0.1.4, remove pyvis dependency
- README: token reduction as top-level selling point, vis.js in tech stack,
  graph.html in output listing, correct test count and install command
2026-04-06 16:06:31 +01:00
Safi 5db8f7ce39 docs: update surprising connections description, test count
style: replace all em dashes with hyphens

fix: explain hidden .graphify/ folder in skill output and README

fix: rename .graphify/ to graphify-out/ so output is visible by default
2026-04-06 16:06:31 +01:00
Safi 693d2ba991 feat: composite surprise score — cross-type, cross-repo, community distance, peripheral→hub 2026-04-06 16:06:31 +01:00
Safi 7e82212304 feat: GraphML export (--graphml flag) for Gephi and yEd 2026-04-06 16:06:31 +01:00
Safi 64e07abd98 docs: CI, architecture guide, worked examples, README fixes
- Add GitHub Actions CI workflow (Python 3.10 and 3.12)
- Add CI badge to README
- Add ARCHITECTURE.md: pipeline overview, module table, schema, how to
  add a language extractor, security summary
- Move eval reports from tests/ to worked/httpx/ and worked/mixed-corpus/
- Fix README: test count 163→212, language table (13 languages via
  tree-sitter), extract.py description, worked examples links

benchmark: 8.8x token reduction on nanoGPT + minGPT + micrograd

- Run AST extraction on 29 Python files across 3 Karpathy repos
- 177 nodes, 246 edges, 17 communities (Leiden)
- 8.8x avg token reduction vs naive full-corpus context stuffing
- Notable: micrograd cleanly splits into engine/nn communities;
  nanoGPT model vs training loop correctly separated
- Honest: stdlib import noise flagged, config isolates documented

benchmark: 71.5x token reduction on mixed corpus (code+papers+images)

Full run: nanoGPT+minGPT+micrograd + 5 research papers + 4 images
285 nodes, 340 edges, 53 communities
Average BFS query: 1,726 tokens vs 123,488 naive (71.5x)
Code-only (AST) sub-benchmark: 8.8x on 13k-word corpus
2026-04-06 16:06:31 +01:00
112 changed files with 33486 additions and 3124 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
github: safishamsi
+36
View File
@@ -0,0 +1,36 @@
name: CI
on:
push:
branches: ["v1", "v2", "v3", "v4", "main"]
pull_request:
branches: ["v1", "v2", "v3", "v4", "main"]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.12"]
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install -e ".[mcp,pdf,watch]"
pip install pytest
- name: Run tests
run: |
python -m pytest tests/ -q --tb=short
- name: Verify install works end-to-end
run: |
graphify --help
graphify install
+9
View File
@@ -13,3 +13,12 @@ build/
*.so
*.egg
.graphify/
graphify-out/
.graphify_*.json
.graphify_python
.claude/
skills/
docs/superpowers/
.vscode/
openspec/
uv.lock
+8
View File
@@ -0,0 +1,8 @@
## graphify
This project has a graphify knowledge graph at graphify-out/.
Rules:
- Before answering architecture or codebase questions, read graphify-out/GRAPH_REPORT.md for god nodes and community structure
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
+84
View File
@@ -0,0 +1,84 @@
# Architecture
graphify is a Claude Code skill backed by a Python library. The skill orchestrates the library; the library can be used standalone.
## Pipeline
```
detect() → extract() → build_graph() → cluster() → analyze() → report() → export()
```
Each stage is a single function in its own module. They communicate through plain Python dicts and NetworkX graphs - no shared state, no side effects outside `graphify-out/`.
## Module responsibilities
| Module | Function | Input → Output |
|--------|----------|----------------|
| `detect.py` | `collect_files(root)` | directory → `[Path]` filtered list |
| `extract.py` | `extract(path)` | file path → `{nodes, edges}` dict |
| `build.py` | `build_graph(extractions)` | list of extraction dicts → `nx.Graph` |
| `cluster.py` | `cluster(G)` | graph → graph with `community` attr on each node |
| `analyze.py` | `analyze(G)` | graph → analysis dict (god nodes, surprises, questions) |
| `report.py` | `render_report(G, analysis)` | graph + analysis → GRAPH_REPORT.md string |
| `export.py` | `export(G, out_dir, ...)` | graph → Obsidian vault, graph.json, graph.html, graph.svg |
| `ingest.py` | `ingest(url, ...)` | URL → file saved to corpus dir |
| `cache.py` | `check_semantic_cache / save_semantic_cache` | files → (cached, uncached) split |
| `security.py` | validation helpers | URL / path / label → validated or raises |
| `validate.py` | `validate_extraction(data)` | extraction dict → raises on schema errors |
| `serve.py` | `start_server(graph_path)` | graph file path → MCP stdio server |
| `watch.py` | `watch(root, flag_path)` | directory → writes flag file on change |
| `benchmark.py` | `run_benchmark(graph_path)` | graph file → corpus vs subgraph token comparison |
## Extraction output schema
Every extractor returns:
```json
{
"nodes": [
{"id": "unique_string", "label": "human name", "source_file": "path", "source_location": "L42"}
],
"edges": [
{"source": "id_a", "target": "id_b", "relation": "calls|imports|uses|...", "confidence": "EXTRACTED|INFERRED|AMBIGUOUS"}
]
}
```
`validate.py` enforces this schema before `build_graph()` consumes it.
## Confidence labels
| Label | Meaning |
|-------|---------|
| `EXTRACTED` | Relationship is explicitly stated in the source (e.g., an import statement, a direct call) |
| `INFERRED` | Relationship is a reasonable deduction (e.g., call-graph second pass, co-occurrence in context) |
| `AMBIGUOUS` | Relationship is uncertain; flagged for human review in GRAPH_REPORT.md |
## Adding a new language extractor
1. Add a `extract_<lang>(path: Path) -> dict` function in `extract.py` following the existing pattern (tree-sitter parse → walk nodes → collect `nodes` and `edges` → call-graph second pass for INFERRED `calls` edges).
2. Register the file suffix in `extract()` dispatch and `collect_files()`.
3. Add the suffix to `CODE_EXTENSIONS` in `detect.py` and `_WATCHED_EXTENSIONS` in `watch.py`.
4. Add the tree-sitter package to `pyproject.toml` dependencies.
5. Add a fixture file to `tests/fixtures/` and tests to `tests/test_languages.py`.
## Security
All external input passes through `graphify/security.py` before use:
- URLs → `validate_url()` (http/https only) + `_NoFileRedirectHandler` (blocks file:// redirects)
- Fetched content → `safe_fetch()` / `safe_fetch_text()` (size cap, timeout)
- Graph file paths → `validate_graph_path()` (must resolve inside `graphify-out/`)
- Node labels → `sanitize_label()` (strips control chars, caps 256 chars, HTML-escapes)
See `SECURITY.md` for the full threat model.
## Testing
One test file per module under `tests/`. Run with:
```bash
pytest tests/ -q
```
All tests are pure unit tests - no network calls, no file system side effects outside `tmp_path`.
+376
View File
@@ -0,0 +1,376 @@
# Changelog
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
## 0.4.16 (2026-04-16)
- Fix: graphify watch crashed on all platforms with NameError because import sys was missing from watch.py (#386, #394)
- Fix: .mjs files were detected but produced 0 nodes — added .mjs to the AST extractor dispatch table (#387)
- Fix: llm.py excluded from the published wheel (local benchmarking file, not part of the public API) (#391)
## 0.4.15 (2026-04-15)
- Feat: VS Code Copilot Chat support — `graphify vscode install` installs a Python-only skill (works on Windows PowerShell) and writes `.github/copilot-instructions.md` for always-on graph context (#206)
- Fix: OpenCode plugin path used backslashes on Windows causing duplicate entries in `opencode.json` — now uses forward slashes via `.as_posix()` (#378)
- Fix: Gemini CLI on Windows now installs skill to `~/.agents/skills/` (higher priority) instead of `~/.gemini/skills/` (#368)
- Fix: `.mjs` and `.ejs` files now recognised by the AST extractor as JavaScript (#365, #372)
- Fix: `god_nodes()` field renamed from `edges` to `degree` for clarity — updated in report, wiki, serve, and all tests (#375)
- Fix: macOS `graphify watch` now uses `PollingObserver` by default to avoid missed events with FSEvents (#373)
## 0.4.14 (2026-04-15)
- Fix: cross-file call edges now emitted for all languages (Swift, Go, Rust, Java, C#, Kotlin, Scala, Ruby, PHP, and others) — previously only Python had cross-file resolution; unresolved call sites are now saved per file and resolved against a global label map in a post-pass (#348)
- Fix: PHP extractor now handles `scoped_call_expression` (static method calls like `Helper::format()`) and `class_constant_access_expression` (enum/constant references like `Status::ACTIVE`) — both were silently dropped before (#230, #232)
- Fix: `--wiki` flag now runs `to_wiki()` as Step 6b in the skill pipeline before the cleanup step — community labels are available and the wiki is written to `graphify-out/wiki/` (#229, #354)
- Fix: `graphify install --platform opencode` now also installs the `.opencode/plugins/graphify.js` plugin, matching what `graphify opencode install` does (#356)
- Fix: `extract()` accepts explicit `cache_root` parameter so subdirectory runs no longer write cache to `<subdir>/graphify-out/cache/` (#350)
- Fix: `os.replace` in cache writer falls back to `shutil.copy2` on `PermissionError` (Windows WinError 5) (#287)
- Fix: `graphify update` exits with code 1 on rebuild failure instead of silently returning (#287)
- Fix: `CLAUDE.md`, Cursor, and Antigravity templates now use `graphify update .` instead of hardcoded `python3 -c` invocation (#287)
- Fix: `skill-kiro.md` added to `pyproject.toml` package-data — `graphify kiro install` was failing on fresh pip installs (#352)
- Fix: `betweenness_centrality` in `suggest_questions` uses `k=100` approximate sampling for graphs over 1000 nodes; `edge_betweenness_centrality` returns early for graphs over 5000 nodes (#341)
## 0.4.13 (2026-04-14)
- Add: Verilog/SystemVerilog support — `.v` and `.sv` files extracted via tree-sitter-verilog (modules, functions, tasks, package imports, module instantiations with `instantiates` edges) (#325)
- Fix: hyperedge polygons render correctly on HiDPI/Retina displays — `afterDrawing` callback ctx is now used directly (already in network coordinate space), removing the double-applied transform and incorrect `canvas.width/2` DPR anchor (#334)
- Fix: AGENTS.md and GEMINI.md rebuild rule now uses `graphify update .` instead of hardcoded `python3 -c "..."` — correct Python is resolved through the graphify binary, no more interpreter mismatches in Nix/pipx/uv environments (#324)
- Fix: `graphify query` and `graphify explain` no longer crash with `AttributeError` when a node has `label: null` — all `.get("label", "")` calls guarded with `or ""` to handle explicit null values (#323)
## 0.4.12 (2026-04-13)
- Add: Kiro IDE/CLI support — `graphify kiro install` writes `.kiro/skills/graphify/SKILL.md` (invoked via `/graphify`) and `.kiro/steering/graphify.md` (`inclusion: always` — always-on context before every conversation) (#319, #321)
- Fix: cache `file_hash()` now uses the path relative to project root instead of the resolved absolute path — cache entries are now portable across machines, CI runners, and different checkout directories (#311)
## 0.4.11 (2026-04-13)
- Fix: `graphify query` no longer crashes with `ValueError` on MultiGraph graphs — `G.edges[u, v]` replaced with `G[u][v]` + MultiGraph guard (#305)
- Fix: `graphify query` no longer crashes with `AttributeError: 'NoneType' has no attribute 'lower'` when a node has a null `source_file` (#307)
- Fix: MCP server launched from a different directory now correctly derives the `graphify-out` base from the absolute path provided, instead of CWD (#309)
- Fix: `.graphifyignore` patterns from a parent directory now fire correctly when graphify is run on a subfolder — patterns are matched against paths relative to both the scan root and the `.graphifyignore`'s anchor directory (#303)
## 0.4.10 (2026-04-13)
- Fix: `graphify install --platform cursor` no longer crashes — passes `Path(".")` to `_cursor_install` (#281)
- Fix: `_agents_uninstall` now only removes the OpenCode plugin when uninstalling the `opencode` platform — other platforms were incorrectly having their OpenCode plugin stripped (#276)
- Fix: misleading comment in query `--graph` path handler removed (#278)
- Fix: `skill-codex.md` — `wait` → `wait_agent` (correct Codex tool name) (#273)
- Add: `svg = ["matplotlib"]` optional extra in pyproject.toml; `matplotlib` added to `[all]` extra (#288)
- Fix: `graspologic` dependency now has `python_version < '3.13'` env marker in `leiden` and `all` extras — prevents install failures on Python 3.13+ (#290)
- Add: Dart/Flutter support — `.dart` files extracted via regex (classes, mixins, functions, imports); added to `CODE_EXTENSIONS` (#292)
- Add: `norm_label` field written at build time in `to_json()` for diacritic-insensitive search; `_score_nodes` and `_find_node` in `serve.py` use `norm_label` with Unicode NFKD normalization fallback (#293)
- Add: Hermes Agent platform support — `graphify hermes install` writes skill to `~/.hermes/skills/graphify/SKILL.md` and AGENTS.md (#251)
- Add: PHP extractor now captures static property access (`Foo::$bar`) as `uses_static_prop` edges (#234)
- Add: PHP extractor now captures `config()` helper calls as `uses_config` edges pointing to the first config key segment (#236)
- Add: PHP extractor now captures service container bindings (`bind`, `singleton`, `scoped`, `instance`) as `bound_to` edges (#238)
- Add: PHP extractor now captures `$listen` / `$subscribe` event listener arrays as `listened_by` edges (#240)
- Add: `prune_dangling_edges()` utility in `export.py` — removes edges whose source/target is not in the node set (#294)
- Fix: Antigravity install injects YAML frontmatter into skill file for native tool discovery; rules now include MCP navigation hint; prints MCP config snippet (#268)
- Fix: Windows hook tests now use platform-aware assertions instead of POSIX executable bit checks (#279)
- Add: CLI commands `path`, `explain`, `add`, `watch`, `update`, `cluster-only` now work as bare terminal commands (not just AI skill invocations) — documented in `--help` output (#277)
## 0.4.8 (2026-04-12)
- Fix: platform skill files (aider, codex, opencode, claw, droid, copilot, windows) no longer contain Claude-specific language — references to "Claude" as the AI model replaced with platform-agnostic wording (#272)
## 0.4.7 (2026-04-12)
- Fix: `watch` semantic edge preservation was always empty — `graph.json` uses `links` key but code read `edges` (#269)
- Fix: `graphify claw install` now writes to `.openclaw/` (correct OpenClaw directory) instead of `.claw/` (#208)
- Add: Blade template support — `@include`, `<livewire:>` components, and `wire:click` bindings extracted from `.blade.php` files (#242)
- Docs: WSL/Linux MCP setup note — package name is `graphifyy`, use `.venv/bin/python3` in `.mcp.json` (#250)
## 0.4.6 (2026-04-12)
- Add: Google Antigravity support — `graphify antigravity install` writes `.agent/rules/graphify.md` (always-on rules) and `.agent/workflows/graphify.md` (`/graphify` slash command) (#203, #199, #53)
## 0.4.5 (2026-04-12)
- Fix: MCP server no longer crashes with `ValidationError` on blank lines sent between JSON messages by some clients (#201)
## 0.4.4 (2026-04-12)
- Fix: `watch` now preserves INFERRED/AMBIGUOUS edges (code↔doc rationale links) across rebuilds — previously all cross-type edges were dropped (#261)
- Fix: Codex hook no longer emits `permissionDecision:allow` which codex-cli 0.120.0 rejects (#249)
- Fix: Common lockfiles (`package-lock.json`, `yarn.lock`, `Cargo.lock`, etc.) are now skipped during detection, preventing token drain on large JS/Rust/Python projects (#266)
## 0.4.3 (2026-04-12)
- Fix: JS/TS relative imports now resolve to full-path node IDs — previously all `imports_from` edges were silently dropped on large TypeScript codebases (#256)
- Fix: Python relative imports (`from .foo import bar`) now resolve correctly to full-path node IDs (#256)
- Fix: `watch --rebuild_code` now merges fresh AST with existing semantic nodes from docs/papers instead of overwriting them (#253)
- Fix: Windows hooks now fall back to `python` if `python3` is not found; exits cleanly if neither has graphify installed (#244)
- Fix: `surprising_connections` / `suggest_questions` no longer crash with `KeyError` on stale `_src`/`_tgt` edge hints after node merges (#226)
- Add: `.vue` and `.svelte` files now recognized as code and included in extraction (#254)
## 0.4.2 (2026-04-11)
- Fix: same-basename files in different directories produced colliding node IDs — now uses full path (#211)
- Fix: edges using `from`/`to` keys instead of `source`/`target` were silently dropped (#216)
- Fix: empty graphs (no edges) crashed `to_html` with `ZeroDivisionError` (#217)
- Fix: post-commit hook skipped `.tsx`, `.jsx`, and other valid code extensions due to stale allowlist (#222)
- Fix: NetworkX ≤3.1 serialises edges as `links` — now accepted alongside `edges` (#212)
- Fix: version warning fired during `install`/`uninstall` and duplicated on shared paths (#220)
- Fix: all file IO now uses `encoding="utf-8"` — prevents crashes on Windows with CJK or emoji labels; hook writes use `newline="\n"` to prevent CRLF shebang breakage (#204)
- Fix: Obsidian export — node labels ending in `.md` produced `.md.md` filenames; `GRAPH_REPORT.md` now links to community hub files so vault stays in one connected component (#221)
## 0.4.1 (2026-04-10)
- Fix: `collect_files()` in `extract.py` now respects `.graphifyignore` — previously ignored patterns, causing thousands of unwanted files (e.g. `node_modules/`) to be scanned (#188)
- Fix: skill.md Step B2 now explicitly requires `subagent_type="general-purpose"` — using `Explore` type silently dropped extraction results since it is read-only and cannot write chunk files (#195)
- Fix: Step B3 now warns when chunk files are missing from disk instead of silently skipping them
## 0.4.0 (2026-04-10)
- Branch: v4 — video and audio corpus support
- Add: drop `.mp4`, `.mp3`, `.wav`, `.mov`, `.webm`, `.m4a`, `.ogg`, `.mkv`, `.avi`, `.m4v` files into any corpus and graphify transcribes them locally with faster-whisper before extraction
- Add: YouTube and URL download via yt-dlp — `/graphify add https://youtube.com/...` downloads audio-only and feeds it through the same Whisper pipeline
- Add: domain-aware Whisper prompts — the coding agent reads god nodes from the corpus and writes a one-sentence domain hint for Whisper itself, no separate API call
- Add: `graphify-out/transcripts/` cache — transcripts cached by filename; YouTube URLs cached by hash so re-runs skip already-transcribed files
- Requires: `pip install 'graphifyy[video]'` for faster-whisper and yt-dlp
## 0.3.29 (2026-04-10)
- Add: video and audio corpus support — drop `.mp4`, `.mp3`, `.wav`, `.mov`, `.webm`, `.m4a`, `.ogg`, `.mkv`, `.avi`, `.m4v` files into any corpus and graphify transcribes them with faster-whisper before extraction
- Add: YouTube and URL video download — pass a YouTube link (or any video URL) to `/graphify add <url>` and yt-dlp downloads audio-only, which is then transcribed and added to the corpus automatically
- Add: domain-aware Whisper prompts — god nodes from non-video files are used to build a one-sentence domain hint for Whisper via a cheap Haiku call, improving transcript accuracy on technical content
- Add: `graphify-out/transcripts/` cache — transcripts are cached by filename so re-runs skip already-transcribed files; URLs cached by hash
- Requires: `pip install 'graphifyy[video]'` for faster-whisper + yt-dlp
## 0.3.28 (2026-04-10)
- Fix: hook installers (Claude Code, Codex, Gemini CLI) now always remove and reinstall the hook on re-run — users upgrading from old versions no longer get stuck with a broken hook format (#182)
- Fix: rationale node labels no longer contain bare `\r` characters on Windows/WSL CRLF files — breaks Obsidian export was silently producing invalid filenames (#176)
- Fix: `skill-windows.md` now includes `--wiki`, `--obsidian-dir`, and `--directed` which were missing vs the main skill (#177)
## 0.3.27 (2026-04-10)
- Fix: graphify install --platform gemini now also copies the skill file to ~/.gemini/skills/graphify/SKILL.md so the /graphify trigger works in Gemini CLI (#174)
## 0.3.26 (2026-04-10)
- Fix: MCP server no longer uses a circular path validation when loading a graph outside cwd — now validates the path exists and ends in `.json` instead of checking containment within its own parent directory (security fix)
## 0.3.25 (2026-04-09)
- Fix: `graphify install --platform gemini` now routes to `gemini_install()` instead of erroring — `gemini` was missing from `_PLATFORM_CONFIG` (#171)
- Fix: `graphify install --platform cursor` now routes to `_cursor_install()` the same way (#171)
- Fix: `serve.py` `validate_graph_path` now passes `base=Path(graph_path).resolve().parent` so MCP server works when graph is outside cwd (#170)
- Fix: MCP `call_tool()` handler now wraps dispatch in try/except — exceptions in tool handlers return graceful error strings instead of crashing the stdio loop (#163)
- Fix: `_load_graphifyignore` now walks parent directories up to the `.git` boundary, matching `.gitignore` discovery behavior — subdirectory scans now inherit root ignore patterns (#168)
- Add: Aider platform support — `graphify install --platform aider` copies skill to `~/.aider/graphify/SKILL.md`; `graphify aider install/uninstall` writes AGENTS.md rules (#74)
- Add: GitHub Copilot CLI platform support — `graphify install --platform copilot` copies skill to `~/.copilot/skills/graphify/SKILL.md`; `graphify copilot install/uninstall` for skill management (#134)
- Add: `--directed` flag — `build_from_json()` and `build()` now accept `directed=True` to produce a `DiGraph` preserving edge direction (source→target); `cluster()` converts to undirected internally for Leiden; `graph_diff` edge key handles directed graphs correctly (#125)
- Add: Frontmatter-aware cache for Markdown files — `.md` files hash only the body below YAML frontmatter, so metadata-only changes (reviewed, status, tags) no longer invalidate the cache (#131)
## 0.3.24 (2026-04-09)
- Fix: `graphify codex install` (and opencode) no longer exits early when `AGENTS.md` already has the graphify section — partial installs with a missing `.codex/hooks.json` can now recover on re-run (#153)
## 0.3.23 (2026-04-09)
- Add: Gemini CLI support — `graphify gemini install` writes a `GEMINI.md` section and a `BeforeTool` hook in `.gemini/settings.json` that fires before file-read tool calls (#105)
- Add: sponsor nudge at pipeline completion — all skill files now print a one-line sponsor link after a fresh build, not on `--update` runs
## 0.3.22 (2026-04-09)
- Add: Cursor support — `graphify cursor install` writes `.cursor/rules/graphify.mdc` with `alwaysApply: true` so the graph context is always included; `graphify cursor uninstall` removes it (#137)
- Fix: `_rebuild_code()` KeyError — `detected[FileType.CODE]` corrected to `detected['files']['code']` matching `detect()`'s actual return shape; was silently breaking git hooks on every commit (#148)
- Fix: `to_json()` crash on NetworkX 3.2.x — `node_link_data(G, edges="links")` now falls back to `node_link_data(G)` on older NetworkX, same shim already used for `node_link_graph` (#149)
- Fix: README clarifies `graphifyy` is the only official PyPI package — other `graphify*` packages are not affiliated (#129)
## 0.3.21 (2026-04-09)
- Fix: Codex PreToolUse hook now places `systemMessage` at the top level of the output JSON instead of inside `hookSpecificOutput` — matches the strict schema enforced by codex-cli 0.118.0+ which uses `additionalProperties: false` (#138)
- Fix: git hooks now use `#!/bin/sh` instead of `#!/bin/bash` — Git for Windows ships `sh.exe` not `bash`, so hooks were silently skipped on Windows (#140)
## 0.3.20 (2026-04-09)
- Fix: XSS in interactive HTML graph — node labels, file types, community names, source files, and edge relations now HTML-escaped before `innerHTML` injection; neighbor link `onclick` uses `JSON.stringify` instead of raw string interpolation
- Add: OpenCode `tool.execute.before` plugin — `graphify opencode install` now writes `.opencode/plugins/graphify.js` and registers it in `opencode.json`, firing the graph reminder before bash calls (equivalent to Claude Code's PreToolUse hook) (#71)
- Fix: AST-resolved call edges now carry `confidence=EXTRACTED, weight=1.0` instead of INFERRED/0.8 — tree-sitter call resolution is deterministic, not probabilistic (#127)
- Fix: `tree-sitter>=0.23.0` now pinned in dependencies and `_check_tree_sitter_version()` guard added — stale environments now get a clear `RuntimeError` with upgrade instructions instead of a cryptic `TypeError` deep in the AST pipeline (#89)
## 0.3.19 (2026-04-09)
- Fix: install step now tries plain `pip install` before falling back to `--break-system-packages` — Homebrew and PEP 668 managed environments no longer risk environment corruption (#126)
## 0.3.18 (2026-04-09)
- Fix: `--watch` mode now respects `.graphifyignore` — `_rebuild_code` was calling `collect_files()` directly instead of `detect()`, bypassing ignore patterns (#120)
- Fix: Codex PreToolUse hook now uses `systemMessage` instead of `additionalContext` — Codex does not support `additionalContext` and was returning an error (#121)
- Fix: Trae link corrected from `trae.com` to `trae.ai` in README, README.zh-CN.md, README.ja-JP.md, README.ko-KR.md (#122)
- Docs: Korean README added (README.ko-KR.md) (#112)
- Refactor: `save_query_result` inline Python blocks in all 6 skill files replaced with `graphify save-result` CLI command — shorter, maintainable, less tokens for LLM (#114)
- Add: `graphify save-result` CLI subcommand — saves Q&A results to memory dir without inline Python
- Fix: HTML graph click detection now uses hover-tracking (`hoveredNodeId`) — more reliable than vis.js click params on small/dense nodes (#82)
- Fix: `mkdir -p graphify-out` now runs before writing `.graphify_python` in `skill.md` — prevents write failure on first run; `.graphify_python` no longer deleted in Step 9 cleanup across all skill files so follow-up commands keep their interpreter (#93)
- Fix: `skill-trae.md` added to `pyproject.toml` package-data — Trae users no longer hit `ModuleNotFoundError` after `pip install` (#102)
- Fix: `analyze.py` and `watch.py` now import extension sets from `detect.py` instead of local copies — Swift, Lua, Zig, PowerShell, Elixir, JSX, Julia, Objective-C files no longer misclassified as documents (#109)
- Refactor: dead `build_graph()` function removed from `cluster.py` (#109)
## 0.3.17 (2026-04-08)
- Add: Julia (.jl) support — modules, structs, abstract types, functions, short functions, using/import, call edges, inherits edges via tree-sitter-julia (#98)
- Fix: Semantic extraction chunks now group files by directory so related artifacts land in the same chunk, reducing missed cross-chunk relationships (#65)
- Fix: `tree-sitter>=0.21` now pinned in dependencies — prevents silent empty AST output when older tree-sitter is installed with newer language bindings (#52)
- Add: Progress output every 100 files during AST extraction so large projects don't appear to hang (#52)
## 0.3.16 (2026-04-08)
- Fix: `graphify query`, `serve`, and `benchmark` now work on NetworkX < 3.4 — version-safe shim for `node_link_graph()` at all call sites (#95)
- Fix: `.jsx` files now detected and extracted via the JS extractor — added to `CODE_EXTENSIONS` and `_DISPATCH` (#94)
- Fix: `.graphify_python` no longer deleted in Step 9 cleanup across all 6 skill files — pipx users no longer hit `ModuleNotFoundError` on follow-up commands (#92)
## 0.3.15 (2026-04-08)
- Feat: Trae and Trae CN platform support (`graphify install --platform trae` / `trae-cn`)
- Fix: `skill-droid.md` was missing from PyPI package data — Factory Droid users couldn't install the skill
- Fix: XSS in HTML legend — community labels now HTML-escaped before `innerHTML` injection
- Fix: Shebang allowlist validation in `hooks.py` and all 6 skill files — prevents metacharacter injection from malicious binaries
- Fix: `louvain_communities()` kwargs now inspected at runtime for cross-version NetworkX compatibility
- Fix: pipx installs now detected correctly in git hooks (reads shebang from graphify binary)
- Fix: graspologic ANSI escape codes no longer corrupt PowerShell 5.1 scroll buffer
- Docs: Japanese README added
- Docs: `graph.json` + LLM workflow example added to README
- Docs: Codex PreToolUse hook now documented in platform table
## 0.3.14 (2026-04-08)
- Fix: `graphify codex install` now also writes a PreToolUse hook to `.codex/hooks.json` so the graph reminder fires before every Bash tool call (#86)
- Fix: `--update` now prunes ghost nodes from deleted files before merging new extraction (#51)
## 0.3.13 (2026-04-08)
- Fix: PreToolUse hook now outputs `additionalContext` JSON so Claude actually sees the graph reminder before Glob/Grep calls (#83)
- Fix: Go AST method receivers and type declarations now use package directory scope, eliminating disconnected duplicate type nodes across files in the same package (#85)
- Fix: PDFs inside Xcode asset catalogs (`.imageset`, `.xcassets`) are no longer misclassified as academic papers (#52)
- Fix: `_resolve_cross_file_imports` is now guarded with `if py_paths` and wrapped in try/except so a Python parser crash can't abort extraction for non-Python files (#52)
- Fix: Skill intermediate files (`.graphify_*.json`) now live in `graphify-out/` instead of project root, preventing git pollution (#81)
## 0.3.12 (2026-04-07)
- Fix: `sanitize_label` was double-encoding HTML entities in the interactive graph (`&amp;lt;` instead of `&lt;`) — removed `html.escape()` from `sanitize_label`; callers that inject directly into HTML now call `html.escape()` themselves (#66)
- Fix: `--wiki` flag missing from `skill.md` usage table (#55)
## 0.3.11 (2026-04-07)
- Fix: Louvain fallback hangs indefinitely on large sparse graphs — added `max_level=10, threshold=1e-4` to prevent infinite loops while preserving community quality (#48)
## 0.3.10 (2026-04-07)
- Fix: Windows UnicodeEncodeError during `graphify install` — replaced arrow character with `->` in all print statements (#47)
- Add: skill version staleness check — warns when installed skill is older than the current package, across all platforms (#46)
## 0.3.9 (2026-04-07)
- Add: `follow_symlinks` parameter to `detect()` and `collect_files()` — opt-in symlink following with circular symlink cycle detection (#33)
- Fix: `watch.py` now uses `collect_files()` instead of manual rglob loop for consistency
- Docs: Codex uses `$graphify .` not `/graphify .` (#36)
- Test: 5 new symlink tests (367 total)
## 0.3.8 (2026-04-07)
- Add: C# inheritance and interface implementation extraction — `base_list` now emits `inherits` edges for both simple (`identifier`) and generic (`generic_name`) base types (#45)
- Add: `graphify query "<question>"` CLI command — BFS/DFS traversal of `graph.json` without needing Claude Code skill (`--dfs`, `--budget N`, `--graph <path>` flags)
- Test: 2 new C# inheritance tests (362 total)
## 0.3.7 (2026-04-07)
- Add: Objective-C support (`.m`, `.mm`) — `@interface`, `@implementation`, `@protocol`, method declarations, `#import` directives, message-expression call edges
- Add: `--obsidian-dir <path>` flag — write Obsidian vault to a custom directory instead of `graphify-out/obsidian`
- Fix: semantic cache was only saving 4/17 files — relative paths from subagents now resolved against corpus root before existence check
- Fix: 75 validation warnings per run for `file_type: "rationale"` — added `"rationale"` to `VALID_FILE_TYPES`
- Test: 6 Objective-C tests; `.m`/`.mm` added to `test_collect_files_from_dir` supported set (360 total)
## 0.3.0 (2026-04-06)
- Add: multi-platform support — Codex (`skill-codex.md`), OpenCode (`skill-opencode.md`), OpenClaw (`skill-claw.md`)
- Add: `graphify install --platform <codex|opencode|claw>` routes skill to correct config directory
- Add: `graphify codex install` / `opencode install` / `claw install` — writes AGENTS.md for always-on graph-first behaviour
- Add: `graphify claude uninstall` / `codex uninstall` / `opencode uninstall` / `claw uninstall`
- Add: MIT license
- Fix: `build()` was silently dropping hyperedges when merging multiple extractions
- Refactor: `extract.py` 2527 → 1588 lines — replaced 12 copy-pasted language extractors with `LanguageConfig` dataclass + `_extract_generic()`
- Docs: clustering is graph-topology-based (no embeddings) — explained in README
- Docs: all missing flags documented (`--cluster-only`, `--no-viz`, `--neo4j-push`, `query --dfs`, `query --budget`, `add --author`, `add --contributor`)
## 0.2.2 (2026-04-06)
- Add: `graphify claude install` — writes graphify section to local CLAUDE.md + PreToolUse hook in `.claude/settings.json`
- Add: `graphify claude uninstall` — removes section and hook
- Add: `graphify hook install` — installs post-commit and post-checkout git hooks (platform-agnostic)
- Add: `graphify hook uninstall` / `hook status`
- Add: `graphify benchmark` CLI command
- Fix: node deduplication documented at all three layers
## 0.1.8 (2026-04-05)
- Fix: follow-up questions now check for wiki first (graphify-out/wiki/index.md) before falling back to graph.json
- Fix: --update now auto-regenerates wiki if graphify-out/wiki/ exists
- Fix: community articles show truncation notice ("... and N more nodes") when > 25 nodes
- UX: pipeline completion message now lists all available flags and commands so users know what graphify can do
## 0.1.7 (2026-04-05)
- Add: `--wiki` flag — generates Wikipedia-style agent-crawlable wiki from the graph (index.md + community articles + god node articles)
- Add: `graphify/wiki.py` module with `to_wiki()` — cross-community wikilinks, cohesion scores, audit trail, navigation footer
- Add: 14 wiki tests (245 total)
- Fix: follow-up question example code now correctly splits node labels by `_` to extract verb prefixes (previous version used `def`/`fn` prefix matching which always returned zero results)
## 0.1.6 (2026-04-05)
- Fix: follow-up questions after pipeline now answered from graph.json, not by re-exploring the directory (was 25 tool calls / 1m30s; now instant)
- Skill: added "Answering Follow-up Questions" section with graph query patterns
## 0.1.5 (2026-04-05)
- Perf: semantic extraction chunks 12-15 → 20-25 files (fewer subagent round trips)
- Perf: code-only corpora skip semantic dispatch entirely (AST handles it)
- Perf: print timing estimate before extraction so the wait feels intentional
- Fix: 5 skill gaps - --graphml in Usage table, --update manifest timing, query/path/explain graph existence check, --no-viz clarity
- Refactor: dead imports removed (shutil, sys, inline os); _node_community_map() helper replaces 8 copy-pasted dict comprehensions; to_html() split into _html_styles() + _html_script(); serve.py call_tool() if/elif chain replaced with dispatch table
- Test: end-to-end pipeline integration test (detect → extract → build → cluster → analyze → report → export)
## 0.1.4 (2026-04-05)
- Replace pyvis with custom vis.js HTML renderer - node size by degree, click-to-inspect panel with clickable neighbors, search box, community filter, physics clustering
- HTML graph generated by default on every run (no flag needed)
- Token reduction benchmark auto-runs after every pipeline on corpora over 5,000 words
- Fix: 292 edge warnings per run eliminated - stdlib/external edges now silently skipped
- Fix: `build()` cross-extraction edges were silently dropped - now merged before assembly
- Fix: `pip install graphify` → `pip install graphifyy` in skill Step 1 (critical install bug)
- Add: `--graphml` flag implemented in skill pipeline (was documented but not wired up)
- Remove: pyvis dependency, dead lib/ folder, misplaced eval reports from tests/
- Add: 5 HTML renderer tests (223 total)
## 0.1.3 (2026-04-04)
- Fix: `pyproject.toml` structure - `requires-python` and `dependencies` were incorrectly placed under `[project.urls]`
- Add: GitHub repository and issues URLs to PyPI page
- Add: `keywords` for PyPI search discoverability
- Docs: README clarifies Claude Code requirement, temporary PyPI name, worked examples footnote
## 0.1.1 (2026-04-04)
- Add: CI badge to README (GitHub Actions, Python 3.10 + 3.12)
- Add: ARCHITECTURE.md - pipeline overview, module table, extraction schema, how to add a language
- Add: SECURITY.md - threat model, mitigations, vulnerability reporting
- Add: `worked/` directory with eval reports (karpathy-repos 71.5x benchmark, httpx, mixed-corpus)
- Fix: pytest not found in CI - added explicit `pip install pytest` step
- Fix: README test count (163 → 212), language table, worked examples links
- Docs: README reframed as Claude Code skill; Karpathy problem → graphify answer framing
## 0.1.0 (2026-04-03)
Initial release.
- 13-language AST extraction via tree-sitter (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP)
- Leiden community detection via graspologic with oversized community splitting
- SHA256 semantic cache - warm re-runs skip unchanged files
- MCP stdio server - `query_graph`, `get_node`, `get_neighbors`, `shortest_path`, `god_nodes`
- Memory feedback loop - Q&A results saved to `graphify-out/memory/`, extracted on `--update`
- Obsidian vault export with wikilinks, community tags, Canvas layout
- Security module - URL validation, safe fetch with size cap, path guards, label sanitisation
- `graphify install` CLI - copies skill to `~/.claude/skills/` and registers in `CLAUDE.md`
- Parallel subagent extraction for docs, papers, and images
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Safi Shamsi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+238
View File
@@ -0,0 +1,238 @@
# graphify
[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja-JP.md) | [한국어](README.ko-KR.md)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
[![Sponsor](https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors)](https://github.com/sponsors/safishamsi)
**AIコーディングアシスタント向けのスキル。** Claude Code、Codex、OpenCode、OpenClaw、Factory Droid で `/graphify` と入力するだけで、ファイルを読み込んでナレッジグラフを構築し、あなたが気づいていなかった構造を返します。コードベースをより速く理解し、アーキテクチャ上の意思決定の「なぜ」を見つけ出します。
完全にマルチモーダル対応。コード、PDF、Markdown、スクリーンショット、図、ホワイトボード写真、他言語の画像まで――graphify は Claude Vision を使ってそれらすべてから概念と関係性を抽出し、1 つのグラフに接続します。tree-sitter AST により 19 言語をサポート(Python、JS、TS、Go、Rust、Java、C、C++、Ruby、C#、Kotlin、Scala、PHP、Swift、Lua、Zig、PowerShell、Elixir、Objective-C)。
> Andrej Karpathy は論文、ツイート、スクリーンショット、メモを放り込む `/raw` フォルダを持っています。graphify はまさにその問題への答えです――生ファイルを読むのに比べて1クエリあたりのトークン数が 71.5 倍少なく、セッションをまたいで永続化され、見つけたものと推測したものを正直に区別します。
```
/graphify . # どのフォルダでも動作 - コードベース、メモ、論文、なんでも
```
```
graphify-out/
├── graph.html インタラクティブなグラフ - ノードをクリック、検索、コミュニティでフィルタ
├── GRAPH_REPORT.md ゴッドノード、意外なつながり、推奨される質問
├── graph.json 永続化されたグラフ - 数週間後でも再読み込みなしでクエリ可能
└── cache/ SHA256 キャッシュ - 再実行時は変更されたファイルのみ処理
```
グラフに含めたくないフォルダを除外するには `.graphifyignore` ファイルを追加します:
```
# .graphifyignore
vendor/
node_modules/
dist/
*.generated.py
```
構文は `.gitignore` と同じです。パターンは graphify を実行したフォルダからの相対パスに対してマッチします。
## 仕組み
graphify は 2 パスで動作します。まず、決定論的な AST パスがコードファイルから構造(クラス、関数、インポート、コールグラフ、docstring、根拠コメント)を LLM なしで抽出します。次に、Claude サブエージェントがドキュメント、論文、画像に対して並列に実行され、概念、関係性、設計の根拠を抽出します。結果は NetworkX グラフにマージされ、Leiden コミュニティ検出でクラスタリングされ、インタラクティブ HTML、クエリ可能な JSON、平易な言葉の監査レポートとしてエクスポートされます。
**クラスタリングはグラフトポロジベース――埋め込みは使いません。** Leiden はエッジ密度によってコミュニティを見つけます。Claude が抽出する意味的類似性エッジ(`semantically_similar_to`、INFERRED とマーク)は既にグラフに含まれているため、コミュニティ検出に直接影響します。グラフ構造そのものが類似性シグナルであり――別途の埋め込みステップやベクターデータベースは不要です。
すべての関係は `EXTRACTED`(ソースから直接見つかった)、`INFERRED`(合理的な推論、信頼度スコア付き)、`AMBIGUOUS`(レビュー対象としてフラグ付け)のいずれかでタグ付けされます。何が見つかったもので何が推測されたものか、常に分かります。
## インストール
**必要なもの:** Python 3.10+ および以下のいずれか: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [OpenClaw](https://openclaw.ai), または [Factory Droid](https://factory.ai)
```bash
pip install graphifyy && graphify install
```
> PyPI パッケージは `graphify` の名前が再取得されるまでの間、一時的に `graphifyy` となっています。CLI とスキルコマンドは依然として `graphify` です。
### プラットフォームサポート
| プラットフォーム | インストールコマンド |
|----------|----------------|
| Claude Code (Linux/Mac) | `graphify install` |
| Claude Code (Windows) | `graphify install`(自動検出)または `graphify install --platform windows` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| OpenClaw | `graphify install --platform claw` |
| Factory Droid | `graphify install --platform droid` |
Codex ユーザーは並列抽出のために `~/.codex/config.toml` の `[features]` の下に `multi_agent = true` も必要です。Factory Droid は並列サブエージェントディスパッチに `Task` ツールを使用します。OpenClaw は逐次抽出を使用します(並列エージェントサポートはこのプラットフォームではまだ初期段階です)。
次に、AI コーディングアシスタントを開いて入力します:
```
/graphify .
```
注意:Codex はスキル呼び出しに `/` ではなく `$` を使用するため、代わりに `$graphify .` と入力してください。
### アシスタントに常にグラフを使わせる(推奨)
グラフを構築した後、プロジェクトで一度だけ以下を実行します:
| プラットフォーム | コマンド |
|----------|---------|
| Claude Code | `graphify claude install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| OpenClaw | `graphify claw install` |
| Factory Droid | `graphify droid install` |
**Claude Code** は 2 つのことを行います:Claude にアーキテクチャの質問に答える前に `graphify-out/GRAPH_REPORT.md` を読むように指示する `CLAUDE.md` セクションを書き込み、すべての Glob と Grep 呼び出しの前に発火する **PreToolUse フック**(`settings.json`)をインストールします。ナレッジグラフが存在する場合、Claude は次のメッセージを見ます:_"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ ――これにより Claude はすべてのファイルを grep するのではなく、グラフを介してナビゲートします。
**Codex、OpenCode、OpenClaw、Factory Droid** は同じルールをプロジェクトルートの `AGENTS.md` に書き込みます。これらのプラットフォームは PreToolUse フックをサポートしていないため、AGENTS.md が常時有効のメカニズムとなります。
アンインストールは対応するアンインストールコマンドで行います(例:`graphify claude uninstall`)。
**常時有効 vs 明示的トリガー――何が違うのか?**
常時有効のフックは `GRAPH_REPORT.md` を表面化します――これはゴッドノード、コミュニティ、意外なつながりを 1 ページにまとめた要約です。アシスタントはファイル検索の前にこれを読み、キーワードマッチではなく構造に基づいてナビゲートします。これで日常的な質問のほとんどをカバーできます。
`/graphify query`、`/graphify path`、`/graphify explain` はさらに深く踏み込みます:生の `graph.json` をホップごとに辿り、ノード間の正確なパスをトレースし、エッジレベルの詳細(関係タイプ、信頼度スコア、ソース位置)を表面化します。一般的なオリエンテーションではなく、特定の質問をグラフから答えさせたいときに使います。
こう考えてください:常時有効のフックはアシスタントに地図を与え、`/graphify` コマンドはその地図を正確にナビゲートさせます。
<details>
<summary>手動インストール(curl)</summary>
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
```
`~/.claude/CLAUDE.md` に追加します:
```
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
```
</details>
## 使い方
```
/graphify # カレントディレクトリで実行
/graphify ./raw # 特定のフォルダで実行
/graphify ./raw --mode deep # より積極的な INFERRED エッジ抽出
/graphify ./raw --update # 変更されたファイルのみ再抽出し、既存グラフにマージ
/graphify ./raw --cluster-only # 既存グラフのクラスタリングを再実行(再抽出なし)
/graphify ./raw --no-viz # HTML をスキップ、レポート + JSON のみ生成
/graphify ./raw --obsidian # Obsidian ボールトも生成(オプトイン)
/graphify ./raw --obsidian --obsidian-dir ~/vaults/myproject # ボールトを特定のディレクトリに書き込み
/graphify add https://arxiv.org/abs/1706.03762 # 論文を取得、保存、グラフを更新
/graphify add https://x.com/karpathy/status/... # ツイートを取得
/graphify add https://... --author "Name" # 元の著者をタグ付け
/graphify add https://... --contributor "Name" # コーパスに追加した人をタグ付け
/graphify query "アテンションとオプティマイザを結ぶものは?"
/graphify query "アテンションとオプティマイザを結ぶものは?" --dfs # 特定のパスをトレース
/graphify query "アテンションとオプティマイザを結ぶものは?" --budget 1500 # N トークンで上限設定
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
/graphify ./raw --watch # ファイル変更時にグラフを自動同期(コード:即時、ドキュメント:通知)
/graphify ./raw --wiki # エージェントがクロール可能な wiki を構築(index.md + コミュニティごとの記事)
/graphify ./raw --svg # graph.svg をエクスポート
/graphify ./raw --graphml # graph.graphml をエクスポート(Gephi、yEd)
/graphify ./raw --neo4j # Neo4j 用の cypher.txt を生成
/graphify ./raw --neo4j-push bolt://localhost:7687 # 実行中の Neo4j インスタンスに直接プッシュ
/graphify ./raw --mcp # MCP stdio サーバーを起動
# git フック - プラットフォーム非依存、コミット時とブランチ切り替え時にグラフを再構築
graphify hook install
graphify hook uninstall
graphify hook status
# 常時有効のアシスタント指示 - プラットフォーム固有
graphify claude install # CLAUDE.md + PreToolUse フック(Claude Code)
graphify claude uninstall
graphify codex install # AGENTS.md(Codex)
graphify opencode install # AGENTS.md(OpenCode)
graphify claw install # AGENTS.md(OpenClaw)
graphify droid install # AGENTS.md(Factory Droid)
# ターミナルから直接グラフをクエリ(AI アシスタント不要)
graphify query "アテンションとオプティマイザを結ぶものは?"
graphify query "認証フローを表示" --dfs
graphify query "CfgNode とは?" --budget 500
graphify query "..." --graph path/to/graph.json
```
あらゆるファイルタイプの組み合わせで動作します:
| タイプ | 拡張子 | 抽出方法 |
|------|-----------|------------|
| コード | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm` | tree-sitter による AST + コールグラフ + docstring/コメントの根拠 |
| ドキュメント | `.md .txt .rst` | Claude による概念 + 関係性 + 設計根拠 |
| Office | `.docx .xlsx` | Markdown に変換した後 Claude で抽出(`pip install graphifyy[office]` が必要) |
| 論文 | `.pdf` | 引用マイニング + 概念抽出 |
| 画像 | `.png .jpg .webp .gif` | Claude Vision - スクリーンショット、図、任意の言語 |
## 得られるもの
**ゴッドノード** - 最高次数の概念(すべてが接続するもの)
**意外なつながり** - 複合スコアでランク付け。コード-論文のエッジはコード-コードよりも高くランクされます。各結果には平易な英語の理由が含まれます。
**推奨される質問** - グラフがユニークに答えられる 4〜5 の質問
**「なぜ」** - docstring、インラインコメント(`# NOTE:`、`# IMPORTANT:`、`# HACK:`、`# WHY:`)、ドキュメントからの設計根拠が `rationale_for` ノードとして抽出されます。コードが何をするかだけでなく――なぜそのように書かれたか。
**信頼度スコア** - すべての INFERRED エッジには `confidence_score`(0.0〜1.0)があります。何が推測されたかだけでなく、モデルがどれだけ確信していたかもわかります。EXTRACTED エッジは常に 1.0 です。
**意味的類似性エッジ** - 構造的接続のないクロスファイル概念リンク。互いを呼び出さずに同じ問題を解いている 2 つの関数、同じアルゴリズムを記述しているコード内のクラスと論文内の概念など。
**ハイパーエッジ** - ペアワイズエッジでは表現できない 3+ ノードを接続するグループ関係。共有プロトコルを実装するすべてのクラス、認証フロー内のすべての関数、論文セクションから 1 つのアイデアを形成するすべての概念など。
**トークンベンチマーク** - 実行ごとに自動的に出力されます。混合コーパス(Karpathy リポジトリ + 論文 + 画像)で、生ファイルを読むのに比べて 1 クエリあたり **71.5 倍** 少ないトークン。最初の実行で抽出とグラフ構築を行います(これにはトークンがかかります)。以降のクエリはすべて生ファイルではなくコンパクトなグラフを読みます――ここで節約が複利的に効いてきます。SHA256 キャッシュにより、再実行時は変更されたファイルのみ再処理されます。
**自動同期** (`--watch`) - バックグラウンドターミナルで実行し、コードベースが変更されるとグラフが自動的に更新されます。コードファイルの保存は即座の再構築をトリガーします(AST のみ、LLM なし)。ドキュメント/画像の変更は、LLM の再パスのために `--update` を実行するよう通知します。
**Git フック** (`graphify hook install`) - post-commit と post-checkout フックをインストールします。コミットごと、ブランチ切り替えごとにグラフが自動的に再構築されます。再構築が失敗した場合、フックは非ゼロコードで終了するため、git がエラーを表面化し、静かに続行することはありません。バックグラウンドプロセスは不要です。
**Wiki** (`--wiki`) - コミュニティごとおよびゴッドノードごとの Wikipedia スタイルの Markdown 記事と、`index.md` エントリポイント。任意のエージェントを `index.md` に向ければ、JSON をパースする代わりにファイルを読むことでナレッジベースをナビゲートできます。
## 実例
| コーパス | ファイル数 | 削減率 | 出力 |
|--------|-------|-----------|--------|
| Karpathy リポジトリ + 論文5本 + 画像4枚 | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
| graphify ソース + Transformer 論文 | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
| httpx(合成 Python ライブラリ) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
トークン削減はコーパスサイズに応じてスケールします。6 ファイルはいずれにせよコンテキストウィンドウに収まるため、そこでのグラフの価値は圧縮ではなく構造的明瞭さです。52 ファイル(コード + 論文 + 画像)では 71 倍以上が得られます。各 `worked/` フォルダには生の入力ファイルと実際の出力(`GRAPH_REPORT.md`、`graph.json`)があり、自分で実行して数字を検証できます。
## プライバシー
graphify はドキュメント、論文、画像の意味的抽出のために、ファイル内容を AI コーディングアシスタントの基盤モデル API に送信します――Anthropic(Claude Code)、OpenAI(Codex)、またはプラットフォームが使用するプロバイダーです。コードファイルは tree-sitter AST を介してローカルで処理されます――コードに関してはファイル内容がマシンから出ることはありません。テレメトリ、利用追跡、分析は一切ありません。ネットワーク呼び出しは抽出中のプラットフォームのモデル API への呼び出しのみで、あなた自身の API キーを使用します。
## 技術スタック
NetworkX + Leiden(graspologic) + tree-sitter + vis.js。意味的抽出は Claude(Claude Code)、GPT-4(Codex)、またはプラットフォームが実行するモデルを介して行われます。Neo4j は不要、サーバーも不要、完全にローカルで実行されます。
## スター履歴
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
<details>
<summary>コントリビューション</summary>
**実例** は最も信頼を築くコントリビューションです。実際のコーパスで `/graphify` を実行し、出力を `worked/{slug}/` に保存し、グラフが正しく捉えたもの・間違えたものを評価する正直な `review.md` を書き、PR を提出してください。
**抽出バグ** - 入力ファイル、キャッシュエントリ(`graphify-out/cache/`)、何が見逃された/捏造されたかを添えて issue を開いてください。
モジュールの責任と言語の追加方法については [ARCHITECTURE.md](ARCHITECTURE.md) を参照してください。
</details>
+282
View File
@@ -0,0 +1,282 @@
# graphify
[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja-JP.md) | [한국어](README.ko-KR.md)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
[![Sponsor](https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors)](https://github.com/sponsors/safishamsi)
**AI 코딩 어시스턴트를 위한 스킬.** Claude Code, Codex, OpenCode, OpenClaw, Factory Droid, 또는 Trae에서 `/graphify`를 입력하면 파일을 읽고 지식 그래프를 구축하여, 미처 몰랐던 구조를 보여줍니다. 코드베이스를 더 빠르게 이해하고, 아키텍처 결정의 "이유"를 찾아보세요.
완전한 멀티모달 지원. 코드, PDF, 마크다운, 스크린샷, 다이어그램, 화이트보드 사진, 심지어 다른 언어로 된 이미지까지 — graphify는 Claude Vision을 사용하여 이 모든 것에서 개념과 관계를 추출하고 하나의 그래프로 연결합니다. tree-sitter AST를 통해 20개 언어를 지원합니다(Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia).
> Andrej Karpathy는 논문, 트윗, 스크린샷, 메모를 모아두는 `/raw` 폴더를 관리합니다. graphify는 바로 그 문제에 대한 답입니다 — 원본 파일을 직접 읽는 것 대비 쿼리당 토큰 소비가 71.5배 적고, 세션 간에 영속적이며, 발견한 것과 추측한 것을 정직하게 구분합니다.
```
/graphify . # 어떤 폴더든 동작 - 코드베이스, 노트, 논문, 무엇이든
```
```
graphify-out/
├── graph.html 인터랙티브 그래프 - 노드 클릭, 검색, 커뮤니티별 필터
├── GRAPH_REPORT.md 갓 노드, 의외의 연결, 추천 질문
├── graph.json 영속 그래프 - 몇 주 후에도 재읽기 없이 쿼리 가능
└── cache/ SHA256 캐시 - 재실행 시 변경된 파일만 처리
```
그래프에 포함하지 않을 폴더를 제외하려면 `.graphifyignore` 파일을 추가하세요:
```
# .graphifyignore
vendor/
node_modules/
dist/
*.generated.py
```
`.gitignore`와 동일한 문법입니다. 패턴은 graphify를 실행한 폴더 기준의 상대 경로에 대해 매칭됩니다.
## 동작 원리
graphify는 두 번의 패스로 실행됩니다. 첫 번째는 결정론적 AST 패스로, 코드 파일에서 구조(클래스, 함수, 임포트, 콜 그래프, docstring, 근거 주석)를 LLM 없이 추출합니다. 두 번째는 Claude 서브에이전트가 문서, 논문, 이미지에 대해 병렬로 실행되어 개념, 관계, 설계 근거를 추출합니다. 결과는 NetworkX 그래프로 병합되고, Leiden 커뮤니티 탐지로 클러스터링되며, 인터랙티브 HTML, 쿼리 가능한 JSON, 그리고 일반 언어 감사 보고서로 내보내집니다.
**클러스터링은 그래프 토폴로지 기반 — 임베딩을 사용하지 않습니다.** Leiden은 엣지 밀도를 기반으로 커뮤니티를 찾습니다. Claude가 추출하는 의미적 유사성 엣지(`semantically_similar_to`, INFERRED로 표시)는 이미 그래프에 포함되어 있으므로 커뮤니티 탐지에 직접 영향을 줍니다. 그래프 구조 자체가 유사성 신호이며 — 별도의 임베딩 단계나 벡터 데이터베이스가 필요하지 않습니다.
모든 관계는 `EXTRACTED`(소스에서 직접 발견), `INFERRED`(합리적 추론, 신뢰도 점수 포함), `AMBIGUOUS`(리뷰 필요 표시) 중 하나로 태깅됩니다. 무엇이 발견된 것이고 무엇이 추측된 것인지 항상 알 수 있습니다.
## 설치
**필수 요구사항:** Python 3.10+ 및 다음 중 하나: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), 또는 [Trae](https://trae.ai)
```bash
pip install graphifyy && graphify install
```
> PyPI 패키지는 `graphify` 이름을 되찾는 동안 임시로 `graphifyy`로 명명되어 있습니다. CLI와 스킬 명령은 여전히 `graphify`입니다.
### 플랫폼 지원
| 플랫폼 | 설치 명령 |
|--------|-----------|
| Claude Code (Linux/Mac) | `graphify install` |
| Claude Code (Windows) | `graphify install` (자동 감지) 또는 `graphify install --platform windows` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| OpenClaw | `graphify install --platform claw` |
| Factory Droid | `graphify install --platform droid` |
| Trae | `graphify install --platform trae` |
| Trae CN | `graphify install --platform trae-cn` |
Codex 사용자는 병렬 추출을 위해 `~/.codex/config.toml`의 `[features]` 아래에 `multi_agent = true`도 필요합니다. Factory Droid는 병렬 서브에이전트 디스패치에 `Task` 도구를 사용합니다. OpenClaw는 순차 추출을 사용합니다(해당 플랫폼의 병렬 에이전트 지원은 아직 초기 단계입니다). Trae는 병렬 서브에이전트 디스패치에 Agent 도구를 사용하며 PreToolUse 훅을 **지원하지 않습니다** — AGENTS.md가 상시 작동 메커니즘입니다.
그런 다음 AI 코딩 어시스턴트를 열고 입력하세요:
```
/graphify .
```
참고: Codex는 스킬 호출에 `/` 대신 `$`를 사용하므로 `$graphify .`라고 입력하세요.
### 어시스턴트가 항상 그래프를 사용하도록 설정 (권장)
그래프를 빌드한 후, 프로젝트에서 한 번만 실행하세요:
| 플랫폼 | 명령 |
|--------|------|
| Claude Code | `graphify claude install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| OpenClaw | `graphify claw install` |
| Factory Droid | `graphify droid install` |
| Trae | `graphify trae install` |
| Trae CN | `graphify trae-cn install` |
**Claude Code**는 두 가지를 수행합니다: 아키텍처 질문에 답하기 전에 `graphify-out/GRAPH_REPORT.md`를 읽도록 Claude에게 지시하는 `CLAUDE.md` 섹션을 작성하고, 모든 Glob 및 Grep 호출 전에 실행되는 **PreToolUse 훅**(`settings.json`)을 설치합니다. 지식 그래프가 존재하면 Claude는 다음 메시지를 보게 됩니다: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ — 이를 통해 Claude는 모든 파일을 grep하는 대신 그래프를 통해 탐색합니다.
**Codex**는 `AGENTS.md`에 작성하고 Bash 도구 호출 전에 실행되는 **PreToolUse 훅**을 `.codex/hooks.json`에 설치합니다 — Claude Code와 동일한 상시 작동 메커니즘입니다.
**OpenCode, OpenClaw, Factory Droid, Trae**는 프로젝트 루트의 `AGENTS.md`에 동일한 규칙을 작성합니다. 이 플랫폼들은 PreToolUse 훅을 지원하지 않으므로 AGENTS.md가 상시 작동 메커니즘입니다.
제거는 대응하는 uninstall 명령으로 수행합니다(예: `graphify claude uninstall`).
**상시 작동 vs 명시적 트리거 — 차이점은?**
상시 작동 훅은 `GRAPH_REPORT.md`를 노출합니다 — 갓 노드, 커뮤니티, 의외의 연결을 한 페이지로 요약한 것입니다. 어시스턴트는 파일 검색 전에 이것을 읽으므로 키워드 매칭이 아닌 구조 기반으로 탐색합니다. 이것만으로 대부분의 일상적인 질문을 처리할 수 있습니다.
`/graphify query`, `/graphify path`, `/graphify explain`은 더 깊이 들어갑니다: 원시 `graph.json`을 홉 단위로 순회하고, 노드 간의 정확한 경로를 추적하며, 엣지 수준의 세부 정보(관계 유형, 신뢰도 점수, 소스 위치)를 보여줍니다. 일반적인 오리엔테이션이 아닌 그래프에서 특정 질문에 답하고 싶을 때 사용하세요.
이렇게 생각하면 됩니다: 상시 작동 훅은 어시스턴트에게 지도를 주고, `/graphify` 명령은 그 지도를 정확하게 탐색하게 합니다.
## `graph.json`을 LLM과 함께 사용하기
`graph.json`은 프롬프트에 한 번에 전부 붙여넣기 위한 것이 아닙니다. 유용한 워크플로우는 다음과 같습니다:
1. `graphify-out/GRAPH_REPORT.md`로 높은 수준의 개요를 파악합니다.
2. `graphify query`를 사용하여 답하려는 특정 질문에 대한 더 작은 서브그래프를 가져옵니다.
3. 전체 원시 코퍼스 대신 그 집중된 결과를 어시스턴트에게 제공합니다.
예를 들어, 프로젝트에서 graphify를 실행한 후:
```bash
graphify query "show the auth flow" --graph graphify-out/graph.json
graphify query "what connects DigestAuth to Response?" --graph graphify-out/graph.json
```
출력에는 노드 레이블, 엣지 유형, 신뢰도 태그, 소스 파일, 소스 위치가 포함됩니다. 이는 LLM을 위한 좋은 중간 컨텍스트 블록이 됩니다:
```text
이 그래프 쿼리 결과를 사용하여 질문에 답하세요. 추측보다 그래프 구조를 우선하고,
가능한 경우 소스 파일을 인용하세요.
```
어시스턴트가 도구 호출이나 MCP를 지원하는 경우, 텍스트를 붙여넣는 대신 그래프를 직접 사용하세요. graphify는 `graph.json`을 MCP 서버로 노출할 수 있습니다:
```bash
python -m graphify.serve graphify-out/graph.json
```
이를 통해 어시스턴트가 `query_graph`, `get_node`, `get_neighbors`, `shortest_path` 같은 반복 쿼리에 구조화된 그래프 접근을 할 수 있습니다.
<details>
<summary>수동 설치 (curl)</summary>
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
```
`~/.claude/CLAUDE.md`에 추가:
```
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
```
</details>
## 사용법
```
/graphify # 현재 디렉토리에서 실행
/graphify ./raw # 특정 폴더에서 실행
/graphify ./raw --mode deep # 더 적극적인 INFERRED 엣지 추출
/graphify ./raw --update # 변경된 파일만 재추출하여 기존 그래프에 병합
/graphify ./raw --cluster-only # 기존 그래프의 클러스터링만 재실행, 재추출 없음
/graphify ./raw --no-viz # HTML 건너뛰기, 보고서 + JSON만 생성
/graphify ./raw --obsidian # Obsidian 볼트도 생성 (옵트인)
/graphify ./raw --obsidian --obsidian-dir ~/vaults/myproject # 볼트를 특정 디렉토리에 생성
/graphify add https://arxiv.org/abs/1706.03762 # 논문 가져오기, 저장, 그래프 업데이트
/graphify add https://x.com/karpathy/status/... # 트윗 가져오기
/graphify add https://... --author "Name" # 원저자 태그
/graphify add https://... --contributor "Name" # 코퍼스에 추가한 사람 태그
/graphify query "어텐션과 옵티마이저를 연결하는 것은?"
/graphify query "어텐션과 옵티마이저를 연결하는 것은?" --dfs # 특정 경로 추적
/graphify query "어텐션과 옵티마이저를 연결하는 것은?" --budget 1500 # N 토큰으로 제한
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
/graphify ./raw --watch # 파일 변경 시 그래프 자동 동기화 (코드: 즉시, 문서: 알림)
/graphify ./raw --wiki # 에이전트가 크롤 가능한 위키 빌드 (index.md + 커뮤니티별 문서)
/graphify ./raw --svg # graph.svg 내보내기
/graphify ./raw --graphml # graph.graphml 내보내기 (Gephi, yEd)
/graphify ./raw --neo4j # Neo4j용 cypher.txt 생성
/graphify ./raw --neo4j-push bolt://localhost:7687 # 실행 중인 Neo4j 인스턴스에 직접 푸시
/graphify ./raw --mcp # MCP stdio 서버 시작
# git 훅 - 플랫폼 무관, 커밋 및 브랜치 전환 시 그래프 재빌드
graphify hook install
graphify hook uninstall
graphify hook status
# 상시 작동 어시스턴트 지시 - 플랫폼별
graphify claude install # CLAUDE.md + PreToolUse 훅 (Claude Code)
graphify claude uninstall
graphify codex install # AGENTS.md (Codex)
graphify opencode install # AGENTS.md (OpenCode)
graphify claw install # AGENTS.md (OpenClaw)
graphify droid install # AGENTS.md (Factory Droid)
graphify trae install # AGENTS.md (Trae)
graphify trae uninstall
graphify trae-cn install # AGENTS.md (Trae CN)
graphify trae-cn uninstall
# 터미널에서 직접 그래프 쿼리 (AI 어시스턴트 불필요)
graphify query "어텐션과 옵티마이저를 연결하는 것은?"
graphify query "인증 흐름 보기" --dfs
graphify query "CfgNode이 뭐지?" --budget 500
graphify query "..." --graph path/to/graph.json
```
다양한 파일 유형의 조합과 함께 동작합니다:
| 유형 | 확장자 | 추출 방식 |
|------|--------|-----------|
| 코드 | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl` | tree-sitter AST + 콜 그래프 + docstring/주석 근거 |
| 문서 | `.md .txt .rst` | Claude를 통한 개념 + 관계 + 설계 근거 |
| 오피스 | `.docx .xlsx` | 마크다운으로 변환 후 Claude를 통해 추출 (`pip install graphifyy[office]` 필요) |
| 논문 | `.pdf` | 인용 마이닝 + 개념 추출 |
| 이미지 | `.png .jpg .webp .gif` | Claude Vision - 스크린샷, 다이어그램, 모든 언어 |
## 결과물
**갓 노드** - 최고 차수의 개념 (모든 것이 연결되는 허브)
**의외의 연결** - 복합 점수로 순위 지정. 코드-논문 엣지는 코드-코드보다 높게 순위됩니다. 각 결과에는 쉬운 설명이 포함됩니다.
**추천 질문** - 그래프가 고유하게 답할 수 있는 4~5개의 질문
**"이유"** - docstring, 인라인 주석(`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), 문서의 설계 근거가 `rationale_for` 노드로 추출됩니다. 코드가 무엇을 하는지뿐만 아니라 — 왜 그렇게 작성되었는지.
**신뢰도 점수** - 모든 INFERRED 엣지에는 `confidence_score`(0.0~1.0)가 있습니다. 무엇이 추측되었는지뿐 아니라 모델이 얼마나 확신했는지도 알 수 있습니다. EXTRACTED 엣지는 항상 1.0입니다.
**의미적 유사성 엣지** - 구조적 연결 없는 파일 간 개념 링크. 서로를 호출하지 않으면서 같은 문제를 해결하는 두 함수, 코드의 클래스와 같은 알고리즘을 설명하는 논문의 개념 등.
**하이퍼엣지** - 쌍별 엣지로는 표현할 수 없는 3개 이상 노드의 그룹 관계. 공유 프로토콜을 구현하는 모든 클래스, 인증 흐름의 모든 함수, 논문 섹션에서 하나의 아이디어를 구성하는 모든 개념 등.
**토큰 벤치마크** - 매 실행 후 자동으로 출력됩니다. 혼합 코퍼스(Karpathy 리포지토리 + 논문 + 이미지)에서: 원본 파일 대비 쿼리당 **71.5배** 적은 토큰. 첫 실행은 추출과 그래프 빌드를 수행합니다(토큰이 소비됩니다). 이후 모든 쿼리는 원본 파일 대신 압축된 그래프를 읽습니다 — 여기서 절약이 복리로 누적됩니다. SHA256 캐시로 재실행 시 변경된 파일만 재처리합니다.
**자동 동기화** (`--watch`) - 백그라운드 터미널에서 실행하면 코드베이스가 변경될 때 그래프가 자동으로 업데이트됩니다. 코드 파일 저장 시 즉시 재빌드가 트리거됩니다(AST만, LLM 없음). 문서/이미지 변경 시에는 LLM 재처리를 위해 `--update` 실행을 알려줍니다.
**Git 훅** (`graphify hook install`) - post-commit 및 post-checkout 훅을 설치합니다. 모든 커밋과 브랜치 전환 후 그래프가 자동으로 재빌드됩니다. 재빌드가 실패하면 훅이 0이 아닌 코드로 종료하여 git이 에러를 표시하고 조용히 계속 진행하지 않습니다. 백그라운드 프로세스가 필요 없습니다.
**위키** (`--wiki`) - 커뮤니티 및 갓 노드별 위키피디아 스타일 마크다운 문서와 `index.md` 진입점. 어떤 에이전트든 `index.md`를 가리키면 JSON을 파싱하는 대신 파일을 읽어서 지식 베이스를 탐색할 수 있습니다.
## 실전 예제
| 코퍼스 | 파일 수 | 축소율 | 결과 |
|--------|---------|--------|------|
| Karpathy 리포지토리 + 논문 5편 + 이미지 4장 | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
| graphify 소스 + Transformer 논문 | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
| httpx (합성 Python 라이브러리) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
토큰 축소는 코퍼스 크기에 비례하여 확장됩니다. 6개 파일은 어차피 컨텍스트 윈도우에 들어가므로, 그래프의 가치는 압축이 아닌 구조적 명확성에 있습니다. 52개 파일(코드 + 논문 + 이미지)에서는 71배 이상을 달성합니다. 각 `worked/` 폴더에는 원본 입력 파일과 실제 출력(`GRAPH_REPORT.md`, `graph.json`)이 있어 직접 실행하여 수치를 검증할 수 있습니다.
## 개인정보 보호
graphify는 문서, 논문, 이미지의 의미적 추출을 위해 파일 내용을 AI 코딩 어시스턴트의 기반 모델 API로 전송합니다 — Anthropic(Claude Code), OpenAI(Codex), 또는 사용 중인 플랫폼의 제공자. 코드 파일은 tree-sitter AST를 통해 로컬에서 처리됩니다 — 코드의 경우 파일 내용이 사용자의 머신을 벗어나지 않습니다. 어떠한 텔레메트리, 사용 추적, 분석도 없습니다. 유일한 네트워크 호출은 추출 중 플랫폼 모델 API에 대한 것이며, 사용자 본인의 API 키를 사용합니다.
## 기술 스택
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. 의미적 추출은 Claude(Claude Code), GPT-4(Codex), 또는 플랫폼이 실행하는 모델을 통해 수행됩니다. Neo4j 불필요, 서버 불필요, 완전히 로컬에서 실행됩니다.
## 다음 계획
graphify는 그래프 레이어입니다. 그 위에 [Penpax](https://safishamsi.github.io/penpax.ai)를 개발하고 있습니다 — 회의, 브라우저 기록, 파일, 이메일, 코드를 하나의 지속적으로 업데이트되는 지식 그래프로 연결하는 온디바이스 디지털 트윈입니다. 클라우드 없음, 데이터 학습 없음. [대기 목록에 등록하세요.](https://safishamsi.github.io/penpax.ai)
## 스타 히스토리
[![Star History Chart](https://starchart.cc/safishamsi/graphify.svg)](https://starchart.cc/safishamsi/graphify)
<details>
<summary>기여하기</summary>
**실전 예제**는 가장 신뢰를 쌓는 기여 방식입니다. 실제 코퍼스에서 `/graphify`를 실행하고, 결과를 `worked/{slug}/`에 저장하고, 그래프가 맞게 파악한 것과 틀린 것을 평가하는 솔직한 `review.md`를 작성하여 PR을 제출하세요.
**추출 버그** - 입력 파일, 캐시 엔트리(`graphify-out/cache/`), 그리고 누락되거나 날조된 내용과 함께 이슈를 열어주세요.
모듈 책임과 언어 추가 방법은 [ARCHITECTURE.md](ARCHITECTURE.md)를 참조하세요.
</details>
+316 -133
View File
@@ -1,68 +1,202 @@
# graphify
any folder of files → persistent knowledge graph → Obsidian vault, graph.json, audit report
[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja-JP.md) | [한국어](README.ko-KR.md)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
[![Downloads](https://static.pepy.tech/badge/graphifyy/month)](https://pepy.tech/project/graphifyy)
[![Sponsor](https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors)](https://github.com/sponsors/safishamsi)
[![LinkedIn](https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin)](https://www.linkedin.com/in/safi-shamsi)
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, or Google Antigravity - it reads your files, builds a knowledge graph, and gives you back structure you didn't know was there. Understand a codebase faster. Find the "why" behind architectural decisions.
Fully multimodal. Drop in code, PDFs, markdown, screenshots, diagrams, whiteboard photos, images in other languages, or video and audio files - graphify extracts concepts and relationships from all of it and connects them into one graph. Videos are transcribed with Whisper using a domain-aware prompt derived from your corpus. 25 languages supported via tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
> Andrej Karpathy keeps a `/raw` folder where he drops papers, tweets, screenshots, and notes. graphify is the answer to that problem - 71.5x fewer tokens per query vs reading the raw files, persistent across sessions, honest about what it found vs guessed.
```
/graphify ./raw
/graphify . # works on any folder - your codebase, notes, papers, anything
```
```
.graphify/
├── obsidian/ open as Obsidian vault — visual graph, wikilinks, filter by community
├── GRAPH_REPORT.md what the graph found: god nodes, surprising connections, suggested questions
├── graph.json persistent graph — query it weeks later without re-reading anything
├── cache/ per-file SHA256 cache — re-runs only process changed files
└── memory/ Q&A results filed back in — what you ask grows the graph on next --update
graphify-out/
├── graph.html interactive graph - click nodes, search, filter by community
├── GRAPH_REPORT.md god nodes, surprising connections, suggested questions
├── graph.json persistent graph - query weeks later without re-reading
└── cache/ SHA256 cache - re-runs only process changed files
```
[placeholder: animated GIF showing the full pipeline — detect → extract → cluster → report → Obsidian vault]
Add a `.graphifyignore` file to exclude folders you don't want in the graph:
## Why this exists
```
# .graphifyignore
vendor/
node_modules/
dist/
*.generated.py
```
**The problem:** Andrej Karpathy described it well: he keeps a `/raw` folder where he drops papers, tweets, screenshots, and notes. The problem is that folder becomes opaque. You forget what's in it. You can't see what connects. Ask Claude "what links paper A to the code in repo B?" and it will hallucinate — it hasn't read both, and even if it has, it has no memory of that connection next session.
Same syntax as `.gitignore`. You can keep a single `.graphifyignore` at your repo root — patterns work correctly even when graphify is run on a subfolder.
**What LLMs get wrong:** Naive summarization fills in every gap confidently. You get a summary that sounds complete but you can't tell what was actually in the files vs invented by the model. And next session, it's all gone — no memory of what it extracted.
## How it works
**What graphify does differently:**
graphify runs in three passes. First, a deterministic AST pass extracts structure from code files (classes, functions, imports, call graphs, docstrings, rationale comments) with no LLM needed. Second, video and audio files are transcribed locally with faster-whisper using a domain-aware prompt derived from corpus god nodes — transcripts are cached so re-runs are instant. Third, Claude subagents run in parallel over docs, papers, images, and transcripts to extract concepts, relationships, and design rationale. The results are merged into a NetworkX graph, clustered with Leiden community detection, and exported as interactive HTML, queryable JSON, and a plain-language audit report.
- **Persistent graph** — relationships are stored in `.graphify/graph.json` and survive across sessions. Query weeks later without re-reading anything.
- **Honest audit trail** — every edge is tagged `EXTRACTED` (explicitly stated), `INFERRED` (call-graph or reasonable deduction), or `AMBIGUOUS` (flagged for review). You always know what was found vs invented.
- **Cross-document surprise** — Leiden community detection finds clusters, then surfaces cross-community connections: the things you would never think to ask about directly.
- **Feedback loop** — every query answer is saved to `.graphify/memory/`. On next `--update`, that Q&A becomes a node. The graph grows from what you ask, not just what you add.
**Clustering is graph-topology-based — no embeddings.** Leiden finds communities by edge density. The semantic similarity edges that Claude extracts (`semantically_similar_to`, marked INFERRED) are already in the graph, so they influence community detection directly. The graph structure is the similarity signal — no separate embedding step or vector database needed.
The result: a navigable map of your corpus that is honest about what it knows and what it guessed.
Every relationship is tagged `EXTRACTED` (found directly in source), `INFERRED` (reasonable inference, with a confidence score), or `AMBIGUOUS` (flagged for review). You always know what was found vs guessed.
## Install
**Requires:** Python 3.10+ and one of: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli), [VS Code Copilot Chat](https://code.visualstudio.com/docs/copilot/overview), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), [Trae](https://trae.ai), [Kiro](https://kiro.dev), Hermes, or [Google Antigravity](https://antigravity.google)
```bash
pip install graphify && graphify install
pip install graphifyy && graphify install
```
That's it. This copies the skill file into `~/.claude/skills/graphify/` and registers it in `~/.claude/CLAUDE.md` automatically. The Python package and all dependencies install on first `/graphify` run — you never touch pip manually again.
> **Official package:** The PyPI package is named `graphifyy` (install with `pip install graphifyy`). Other packages named `graphify*` on PyPI are not affiliated with this project. The only official repository is [safishamsi/graphify](https://github.com/safishamsi/graphify). The CLI and skill command are still `graphify`.
Then open Claude Code in any directory and type:
### Platform support
| Platform | Install command |
|----------|----------------|
| Claude Code (Linux/Mac) | `graphify install` |
| Claude Code (Windows) | `graphify install` (auto-detected) or `graphify install --platform windows` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| GitHub Copilot CLI | `graphify install --platform copilot` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify install --platform aider` |
| OpenClaw | `graphify install --platform claw` |
| Factory Droid | `graphify install --platform droid` |
| Trae | `graphify install --platform trae` |
| Trae CN | `graphify install --platform trae-cn` |
| Gemini CLI | `graphify install --platform gemini` |
| Hermes | `graphify install --platform hermes` |
| Kiro IDE/CLI | `graphify kiro install` |
| Cursor | `graphify cursor install` |
| Google Antigravity | `graphify antigravity install` |
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism. Codex supports PreToolUse hooks — `graphify codex install` installs one in `.codex/hooks.json` in addition to writing AGENTS.md.
Then open your AI coding assistant and type:
```
/graphify .
```
Note: Codex uses `$` instead of `/` for skill calling, so type `$graphify .` instead.
### Make your assistant always use the graph (recommended)
After building a graph, run this once in your project:
| Platform | Command |
|----------|---------|
| Claude Code | `graphify claude install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| GitHub Copilot CLI | `graphify copilot install` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify aider install` |
| OpenClaw | `graphify claw install` |
| Factory Droid | `graphify droid install` |
| Trae | `graphify trae install` |
| Trae CN | `graphify trae-cn install` |
| Cursor | `graphify cursor install` |
| Gemini CLI | `graphify gemini install` |
| Hermes | `graphify hermes install` |
| Kiro IDE/CLI | `graphify kiro install` |
| Google Antigravity | `graphify antigravity install` |
**Claude Code** does two things: writes a `CLAUDE.md` section telling Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs a **PreToolUse hook** (`settings.json`) that fires before every Glob and Grep call. If a knowledge graph exists, Claude sees: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ — so Claude navigates via the graph instead of grepping through every file.
**Codex** writes to `AGENTS.md` and also installs a **PreToolUse hook** in `.codex/hooks.json` that fires before every Bash tool call — same always-on mechanism as Claude Code.
**OpenCode** writes to `AGENTS.md` and also installs a **`tool.execute.before` plugin** (`.opencode/plugins/graphify.js` + `opencode.json` registration) that fires before bash tool calls and injects the graph reminder into tool output when the graph exists.
**Cursor** writes `.cursor/rules/graphify.mdc` with `alwaysApply: true` — Cursor includes it in every conversation automatically, no hook needed.
**Gemini CLI** copies the skill to `~/.gemini/skills/graphify/SKILL.md`, writes a `GEMINI.md` section, and installs a `BeforeTool` hook in `.gemini/settings.json` that fires before file-read tool calls — same always-on mechanism as Claude Code.
**Aider, OpenClaw, Factory Droid, Trae, and Hermes** write the same rules to `AGENTS.md` in your project root and copy the skill to the platform's global skill directory. These platforms don't support tool hooks, so AGENTS.md is the always-on mechanism.
**Kiro IDE/CLI** writes the skill to `.kiro/skills/graphify/SKILL.md` (invoked via `/graphify`) and a steering file to `.kiro/steering/graphify.md` with `inclusion: always` — Kiro injects this into every conversation automatically, no hook needed.
**Google Antigravity** writes `.agent/rules/graphify.md` (always-on rules) and `.agent/workflows/graphify.md` (registers `/graphify` as a slash command). No hook equivalent exists in Antigravity — rules are the always-on mechanism.
**GitHub Copilot CLI** copies the skill to `~/.copilot/skills/graphify/SKILL.md`. Run `graphify copilot install` to set it up.
**VS Code Copilot Chat** installs a Python-only skill (works on Windows PowerShell and macOS/Linux alike) and writes `.github/copilot-instructions.md` in your project root — VS Code reads this automatically every session, making graph context always-on without any hook mechanism. Run `graphify vscode install`. Note: this configures the chat panel in VS Code, not the Copilot CLI terminal tool.
Uninstall with the matching uninstall command (e.g. `graphify claude uninstall`).
**Always-on vs explicit trigger — what's the difference?**
The always-on hook surfaces `GRAPH_REPORT.md` — a one-page summary of god nodes, communities, and surprising connections. Your assistant reads this before searching files, so it navigates by structure instead of keyword matching. That covers most everyday questions.
`/graphify query`, `/graphify path`, and `/graphify explain` go deeper: they traverse the raw `graph.json` hop by hop, trace exact paths between nodes, and surface edge-level detail (relation type, confidence score, source location). Use them when you want a specific question answered from the graph rather than a general orientation.
Think of it this way: the always-on hook gives your assistant a map. The `/graphify` commands let it navigate the map precisely.
## Using `graph.json` with an LLM
`graph.json` is not meant to be pasted into a prompt all at once. The useful
workflow is:
1. Start with `graphify-out/GRAPH_REPORT.md` for the high-level overview.
2. Use `graphify query` to pull a smaller subgraph for the specific question
you want to answer.
3. Give that focused output to your assistant instead of dumping the full raw
corpus.
For example, after running graphify on a project:
```bash
graphify query "show the auth flow" --graph graphify-out/graph.json
graphify query "what connects DigestAuth to Response?" --graph graphify-out/graph.json
```
The output includes node labels, edge types, confidence tags, source files, and
source locations. That makes it a good intermediate context block for an LLM:
```text
Use this graph query output to answer the question. Prefer the graph structure
over guessing, and cite the source files when possible.
```
If your assistant supports tool calling or MCP, use the graph directly instead
of pasting text. graphify can expose `graph.json` as an MCP server:
```bash
python -m graphify.serve graphify-out/graph.json
```
That gives the assistant structured graph access for repeated queries such as
`query_graph`, `get_node`, `get_neighbors`, and `shortest_path`.
> **WSL / Linux note:** Ubuntu ships `python3`, not `python`. Install into a project venv to avoid PEP 668 conflicts, and use the full venv path in your `.mcp.json`:
> ```bash
> python3 -m venv .venv && .venv/bin/pip install "graphifyy[mcp]"
> ```
> ```json
> { "mcpServers": { "graphify": { "type": "stdio", "command": ".venv/bin/python3", "args": ["-m", "graphify.serve", "graphify-out/graph.json"] } } }
> ```
> Also note: the PyPI package is `graphifyy` (double-y) — `pip install graphify` installs an unrelated package.
<details>
<summary>Manual install (curl)</summary>
**Step 1 — copy the skill file**
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v1/skills/graphify/skill.md \
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v4/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
```
**Step 2 — register it in Claude Code**
Add this to `~/.claude/CLAUDE.md` (create the file if it doesn't exist):
Add to `~/.claude/CLAUDE.md`:
```
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) — any input to knowledge graph. Trigger: `/graphify`
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
```
@@ -70,147 +204,196 @@ When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"`
## Usage
```bash
```
/graphify # run on current directory
/graphify ./raw # run on a specific folder
/graphify ./raw --mode deep # more aggressive INFERRED edge extraction
/graphify ./raw --update # re-extract only changed files, merge into existing graph
/graphify ./raw --watch # notify when new files appear
/graphify ./raw --directed # build directed graph (preserves edge direction: source→target)
/graphify ./raw --cluster-only # rerun clustering on existing graph, no re-extraction
/graphify ./raw --no-viz # skip HTML, just produce report + JSON
/graphify ./raw --obsidian # also generate Obsidian vault (opt-in)
/graphify ./raw --obsidian --obsidian-dir ~/vaults/myproject # write vault to a specific directory
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper, save, update graph
/graphify add https://x.com/karpathy/status/... # fetch a tweet
/graphify add <url> --author "Karpathy" --contributor "safi"
/graphify add <video-url> # download audio, transcribe, add to graph
/graphify add https://... --author "Name" # tag the original author
/graphify add https://... --contributor "Name" # tag who added it to the corpus
/graphify query "what connects attention to the optimizer?" # BFS — broad context
/graphify query "how does the encoder reach the loss?" --dfs # DFS — trace a path
/graphify query "..." --budget 1500 # cap at N tokens
/graphify query "what connects attention to the optimizer?"
/graphify query "what connects attention to the optimizer?" --dfs # trace a specific path
/graphify query "what connects attention to the optimizer?" --budget 1500 # cap at N tokens
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
/graphify path "DigestAuth" "Response" # shortest path between two concepts
/graphify explain "SwinTransformer" # plain-language node explanation
/graphify ./raw --watch # auto-sync graph as files change (code: instant, docs: notifies you)
/graphify ./raw --wiki # build agent-crawlable wiki (index.md + article per community)
/graphify ./raw --svg # export graph.svg
/graphify ./raw --graphml # export graph.graphml (Gephi, yEd)
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
/graphify ./raw --neo4j-push bolt://localhost:7687 # push directly to a running Neo4j instance
/graphify ./raw --mcp # start MCP stdio server
/graphify ./raw --html # also export graph.html (browser, no Obsidian needed)
/graphify ./raw --svg # also export graph.svg (embeds in Notion, GitHub)
/graphify ./raw --neo4j # generate cypher.txt for Neo4j import
/graphify ./raw --mcp # start MCP stdio server for agent access
# git hooks - platform-agnostic, rebuild graph on commit and branch switch
graphify hook install
graphify hook uninstall
graphify hook status
# always-on assistant instructions - platform-specific
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
graphify claude uninstall
graphify codex install # AGENTS.md + PreToolUse hook in .codex/hooks.json (Codex)
graphify opencode install # AGENTS.md + tool.execute.before plugin (OpenCode)
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
graphify cursor uninstall
graphify gemini install # GEMINI.md + BeforeTool hook (Gemini CLI)
graphify gemini uninstall
graphify copilot install # skill file (GitHub Copilot CLI)
graphify copilot uninstall
graphify aider install # AGENTS.md (Aider)
graphify aider uninstall
graphify claw install # AGENTS.md (OpenClaw)
graphify droid install # AGENTS.md (Factory Droid)
graphify trae install # AGENTS.md (Trae)
graphify trae uninstall
graphify trae-cn install # AGENTS.md (Trae CN)
graphify trae-cn uninstall
graphify hermes install # AGENTS.md + ~/.hermes/skills/ (Hermes)
graphify hermes uninstall
graphify kiro install # .kiro/skills/ + .kiro/steering/graphify.md (Kiro IDE/CLI)
graphify kiro uninstall
graphify antigravity install # .agent/rules + .agent/workflows (Google Antigravity)
graphify antigravity uninstall
# query and navigate the graph directly from the terminal (no AI assistant needed)
graphify query "what connects attention to the optimizer?"
graphify query "show the auth flow" --dfs
graphify query "what is CfgNode?" --budget 500
graphify query "..." --graph path/to/graph.json
graphify path "DigestAuth" "Response" # shortest path between two nodes
graphify explain "SwinTransformer" # plain-language explanation of a node
# add content and update the graph from the terminal
graphify add https://arxiv.org/abs/1706.03762 # fetch paper, save to ./raw, update graph
graphify add https://... --author "Name" --contributor "Name"
# incremental update and maintenance
graphify watch ./src # auto-rebuild on code changes
graphify update ./src # re-extract code files, no LLM needed
graphify cluster-only ./my-project # rerun clustering on existing graph.json
```
Works with any mix of file types in the same folder:
Works with any mix of file types:
| Type | Extensions | How it's extracted |
|------|-----------|-------------------|
| Code | `.py .ts .tsx .js .go .rs` | AST (deterministic) + call-graph pass (INFERRED) |
| Code | `.java .cpp .c .rb .swift .kt` | Claude semantic extraction |
| Documents | `.md .txt .rst` | Concepts + relationships via Claude |
| Type | Extensions | Extraction |
|------|-----------|------------|
| Code | `.py .ts .js .jsx .tsx .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 |
| Docs | `.md .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 |
| Images | `.png .jpg .webp .gif .svg` | Claude vision — screenshots, charts, whiteboards, any language |
| Images | `.png .jpg .webp .gif` | Claude vision - screenshots, diagrams, any language |
| Video / Audio | `.mp4 .mov .mkv .webm .avi .m4v .mp3 .wav .m4a .ogg` | Transcribed locally with faster-whisper, transcript fed into Claude extraction (requires `pip install graphifyy[video]`) |
| YouTube / URLs | any video URL | Audio downloaded via yt-dlp, then same Whisper pipeline (requires `pip install graphifyy[video]`) |
## Video and audio corpus
Drop video or audio files into your corpus folder alongside your code and docs — graphify picks them up automatically:
```bash
pip install 'graphifyy[video]' # one-time setup
/graphify ./my-corpus # transcribes any video/audio files it finds
```
Add a YouTube video (or any public video URL) directly:
```bash
/graphify add <video-url>
```
yt-dlp downloads audio-only (fast, small), Whisper transcribes it locally, and the transcript is fed into the same extraction pipeline as your other docs. Transcripts are cached in `graphify-out/transcripts/` so re-runs skip already-transcribed files.
For better accuracy on technical content, use a larger model:
```bash
/graphify ./my-corpus --whisper-model medium
```
Audio never leaves your machine. All transcription runs locally.
## What you get
After running, Claude outputs three things directly in chat:
**God nodes** - highest-degree concepts (what everything connects through)
**God nodes** — highest-degree concepts (what everything connects through)
**Surprising connections** - ranked by composite score. Code-paper edges rank higher than code-code. Each result includes a plain-English why.
**Surprising connections** — cross-community edges; relationships between concepts in different clusters that you didn't know to look for
**Suggested questions** - 4-5 questions the graph is uniquely positioned to answer
**Suggested questions** — 4-5 questions the graph is uniquely positioned to answer, with the reason why (which bridge node makes it interesting, which community boundary it crosses)
**The "why"** - docstrings, inline comments (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), and design rationale from docs are extracted as `rationale_for` nodes. Not just what the code does - why it was written that way.
The full GRAPH_REPORT.md adds community summaries with cohesion scores and a list of ambiguous edges for review.
**Confidence scores** - every INFERRED edge has a `confidence_score` (0.0-1.0). You know not just what was guessed but how confident the model was. EXTRACTED edges are always 1.0.
## Key files explained
**Semantic similarity edges** - cross-file conceptual links with no structural connection. Two functions solving the same problem without calling each other, a class in code and a concept in a paper describing the same algorithm.
| File | Purpose |
|------|---------|
| `GRAPH_REPORT.md` | The audit report. God nodes, surprising connections, community cohesion scores, ambiguous edge list, suggested questions. |
| `graph.json` | Persistent graph in node-link format. Load it with NetworkX or push to Neo4j. Survives sessions. |
| `obsidian/` | Wikilink vault. Open in Obsidian → enable graph view → see communities as clusters. Filter by tag, search across everything. |
| `.graphify/cache/` | SHA256-based per-file cache. A re-run on an unchanged corpus takes seconds. |
| `.graphify/memory/` | Q&A feedback loop. Every `/graphify query` answer is saved here. Next `--update` extracts it into the graph. |
**Hyperedges** - group relationships connecting 3+ nodes that pairwise edges can't express. All classes implementing a shared protocol, all functions in an auth flow, all concepts from a paper section forming one idea.
## What this skill will NOT do
**Token benchmark** - printed automatically after every run. On a mixed corpus (Karpathy repos + papers + images): **71.5x** fewer tokens per query vs reading raw files. The first run extracts and builds the graph (this costs tokens). Every subsequent query reads the compact graph instead of raw files — that's where the savings compound. The SHA256 cache means re-runs only re-process changed files.
- **Won't invent edges** — `AMBIGUOUS` exists so uncertain relationships are flagged, not hidden. If the connection isn't clear, it's tagged, not fabricated.
- **Won't claim the graph is useful when it isn't** — a corpus over 2M words or 200 files gets a cost warning before proceeding.
- **Won't re-extract unchanged files** — SHA256 cache ensures warm re-runs skip everything that hasn't changed.
- **Won't visualize graphs over 5,000 nodes** — use `--no-viz` or query instead.
- **Won't download datasets or set up infrastructure** — graphify reads your files. What you put in the folder is what it works with.
- **Won't implement baselines or run experiments** — it reads and maps. Analysis is yours.
**Auto-sync** (`--watch`) - run in a background terminal and the graph updates itself as your codebase changes. Code file saves trigger an instant rebuild (AST only, no LLM). Doc/image changes notify you to run `--update` for the LLM re-pass.
## Design principles
**Git hooks** (`graphify hook install`) - installs post-commit and post-checkout hooks. Graph rebuilds automatically after every commit and every branch switch. If a rebuild fails, the hook exits with a non-zero code so git surfaces the error instead of silently continuing. No background process needed.
1. **Extraction quality is everything** — clustering is downstream of it. A bad graph clusters into bad communities. The AST + call-graph pass exists because deterministic beats probabilistic for code.
2. **Show the numbers** — cohesion is `0.91`, not "good". Token cost is always printed. You know what you spent.
3. **The best output is what you didn't know** — Surprising Connections is not optional. God nodes you probably already suspected. Cross-community edges are what you came for.
4. **The graph earns its complexity** — below a certain density, just use Claude directly. The graph adds value when you have more than you can hold in context across sessions.
5. **What you ask grows the graph** — query results are filed back in automatically. The corpus is not static.
6. **Honest uncertainty** — `EXTRACTED`, `INFERRED`, `AMBIGUOUS` are not cosmetic labels. They are the difference between trusting the graph and being misled by it.
## Contributing
**Adding worked examples**
Worked examples are the most trust-building part of this project. To add one:
1. Pick a real corpus (people should be able to verify the output)
2. Run the skill: `/graphify <path>`
3. Save the full output to `worked/{corpus_slug}/`
4. Write a `review.md` that honestly evaluates:
- What the graph got right
- What edges it correctly flagged AMBIGUOUS
- Any mistakes or missed connections
- Any surprising connections that were genuinely surprising
5. Submit a PR with all of the above
**Improving extraction**
If you find a file type or language where extraction is poor, open an issue with a minimal reproduction case. The best bug reports include: the input file, the extraction output (`.graphify/cache/` entry), and what was missed or invented.
**Adding domain knowledge**
If corpora in your domain consistently contain structures graphify doesn't extract well (e.g., legal documents, lab notebooks, musical scores), open a discussion with examples.
**Wiki** (`--wiki`) - Wikipedia-style markdown articles per community and god node, with an `index.md` entry point. Point any agent at `index.md` and it can navigate the knowledge base by reading files instead of parsing JSON.
## Worked examples
| Corpus | Type | Eval report |
|--------|------|-------------|
| httpx (Python HTTP client) | Codebase | `tests/EVAL_httpx.md` + `tests/GRAPH_REPORT_httpx.md` |
| Mixed corpus (code + paper + Arabic image) | Multi-type | `tests/EVAL_mixed_corpus.md` |
| Corpus | Files | Reduction | Output |
|--------|-------|-----------|--------|
| Karpathy repos + 5 papers + 4 images | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
| graphify source + Transformer paper | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
| httpx (synthetic Python library) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
Each includes the full graph output and an honest evaluation of what the skill got right and wrong.
Token reduction scales with corpus size. 6 files fits in a context window anyway, so graph value there is structural clarity, not compression. At 52 files (code + papers + images) you get 71x+. Each `worked/` folder has the raw input files and the actual output (`GRAPH_REPORT.md`, `graph.json`) so you can run it yourself and verify the numbers.
## Privacy
graphify sends file contents to your AI coding assistant's underlying model API for semantic extraction of docs, papers, and images — Anthropic (Claude Code), OpenAI (Codex), or whichever provider your platform uses. Code files are processed locally via tree-sitter AST — no file contents leave your machine for code. Video and audio files are transcribed locally with faster-whisper — audio never leaves your machine. No telemetry, usage tracking, or analytics of any kind. The only network calls are to your platform's model API during extraction, using your own API key.
## Tech stack
| Layer | Library | Why |
|-------|---------|-----|
| Graph | NetworkX | Pure Python, same internals as MS GraphRAG |
| Community detection | Leiden via graspologic | Better than K-means for sparse graphs |
| Code parsing | tree-sitter | Multi-language AST, deterministic, zero hallucination |
| Extraction | Claude (parallel subagents) | Reads anything, outputs structured graph data |
| Visualization | Obsidian vault | Native graph view, wikilinks, no server needed |
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantic extraction via Claude (Claude Code), GPT-4 (Codex), or whichever model your platform runs. Video transcription via faster-whisper + yt-dlp (optional, `pip install graphifyy[video]`). No Neo4j required, no server, runs entirely locally.
No Neo4j required. No dashboards. No server. Runs entirely locally.
## Built on graphify — Penpax
## Files
[**Penpax**](https://safishamsi.github.io/penpax.ai) is the enterprise layer on top of graphify. Where graphify turns a folder of files into a knowledge graph, Penpax applies the same graph to your entire working life — continuously.
```
graphify/
├── detect.py detect file types, auto-exclude venvs/caches/node_modules; scan .graphify/memory/
├── extract.py AST extraction (Python, TypeScript, JavaScript, Go, Rust) + call-graph pass
├── build.py assemble NetworkX graph from extraction JSON; schema-validates before assembly
├── cluster.py Leiden community detection, cohesion scoring
├── analyze.py god nodes, bridge nodes, surprising connections, suggested questions, graph diff
├── report.py render GRAPH_REPORT.md
├── export.py Obsidian vault, graph.json, graph.html, graph.svg, Neo4j Cypher, Canvas
├── ingest.py fetch URLs (arXiv, Twitter/X, PDF, any webpage); save Q&A to .graphify/memory/
├── cache.py SHA256-based per-file extraction cache; check_semantic_cache / save_semantic_cache
├── security.py URL validation (http/https only), safe fetch with size cap, path guards, label sanitisation
├── validate.py JSON schema checks on extraction output
├── serve.py MCP stdio server — query_graph, get_node, get_neighbors, shortest_path, god_nodes
└── watch.py fs watcher, writes flag file when new files appear
| | graphify | Penpax |
|---|---|---|
| Input | A folder of files | Browser history, meetings, emails, files, code — everything |
| Runs | On demand | Continuously in the background |
| Scope | A project | Your entire working life |
| Query | CLI / MCP / AI skill | Natural language, always on |
| Privacy | Local by default | Fully on-device, no cloud |
skills/graphify/
└── skill.md the Claude Code skill — the full pipeline the agent runs step by step
Built for lawyers, consultants, executives, doctors, researchers — anyone whose work lives across hundreds of conversations and documents they can never fully reconstruct.
SECURITY.md threat model, mitigations, vulnerability reporting
tests/ 163 tests, one file per module
pyproject.toml pip install graphify | pip install graphify[mcp,neo4j,pdf,watch]
```
**Free trial launching soon.** [Join the waitlist →](https://safishamsi.github.io/penpax.ai)
## What we are building next
graphify is the graph layer. Penpax is the always-on layer on top of it — an on-device digital twin that connects your meetings, browser history, files, emails, and code into one continuously updating knowledge graph. No cloud, no training on your data. [Join the waitlist.](https://safishamsi.github.io/penpax.ai)
## Star history
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
<details>
<summary>Contributing</summary>
**Worked examples** are the most trust-building contribution. Run `/graphify` on a real corpus, save output to `worked/{slug}/`, write an honest `review.md` evaluating what the graph got right and wrong, submit a PR.
**Extraction bugs** - open an issue with the input file, the cache entry (`graphify-out/cache/`), and what was missed or invented.
See [ARCHITECTURE.md](ARCHITECTURE.md) for module responsibilities and how to add a language.
</details>
+222
View File
@@ -0,0 +1,222 @@
# graphify
[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja-JP.md) | [한국어](README.ko-KR.md)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
**一个面向 AI 编码助手的技能。** 在 Claude Code、Codex、OpenCode、OpenClaw、Factory Droid 或 Trae 中输入 `/graphify`,它会读取你的文件、构建知识图谱,并把原本不明显的结构关系还给你。更快理解代码库,找到架构决策背后的"为什么"。
完全多模态。你可以直接丢进去代码、PDF、Markdown、截图、流程图、白板照片,甚至其他语言的图片 —— graphify 会用 Claude vision 从这些内容中提取概念和关系,并把它们连接到同一张图里。
> Andrej Karpathy 会维护一个 `/raw` 文件夹,把论文、推文、截图和笔记都丢进去。graphify 就是在解决这类问题 —— 相比直接读取原始文件,每次查询的 token 消耗可降低 **71.5 倍**,结果还能跨会话持久保存,并且会明确区分哪些内容是实际发现的,哪些只是合理推断。
```
/graphify . # 可用于任意目录:代码库、笔记、论文都可以
```
```
graphify-out/
├── graph.html 可交互图谱:可点节点、搜索、按社区过滤
├── GRAPH_REPORT.md God nodes、意外连接、建议提问
├── graph.json 持久化图谱:数周后仍可查询,无需重新读原始文件
└── cache/ SHA256 缓存:重复运行时只处理变更过的文件
```
## 工作原理
graphify 分两轮执行。第一轮是确定性的 AST 提取,对代码文件做结构分析(类、函数、导入、调用图、docstring、解释性注释),这一轮不需要 LLM。第二轮会并行调用 Claude 子代理处理文档、论文和图片,从中提取概念、关系和设计动机。最后把两边结果合并到一个 NetworkX 图里,用 Leiden 社区发现算法做聚类,并导出成可交互 HTML、可查询 JSON,以及一份人类可读的审计报告。
**聚类是基于图拓扑完成的,不依赖 embeddings。** Leiden 按边密度发现社区。Claude 抽取出的语义相似边(`semantically_similar_to`,标记为 `INFERRED`)本来就存在于图中,所以会直接影响社区划分。图结构本身就是相似性信号,不需要额外的 embedding 步骤,也不需要向量数据库。
每条关系都会被标记为 `EXTRACTED`(直接在源材料中找到)、`INFERRED`(合理推断,并附带置信度分数)或 `AMBIGUOUS`(有歧义,需要复核)。所以你始终知道哪些是实际发现的,哪些是模型猜出来的。
## 安装
**要求:** Python 3.10+,并且使用以下平台之一:[Claude Code](https://claude.ai/code)、[Codex](https://openai.com/codex)、[OpenCode](https://opencode.ai)、[OpenClaw](https://openclaw.ai)、[Factory Droid](https://factory.ai) 或 [Trae](https://trae.ai)
```bash
pip install graphifyy && graphify install
```
> PyPI 包当前暂时叫 `graphifyy`,因为 `graphify` 这个名字还在回收中。CLI 命令和 skill 命令仍然都是 `graphify`。
### 平台支持
| 平台 | 安装命令 |
|------|----------|
| Claude Code | `graphify install` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| OpenClaw | `graphify install --platform claw` |
| Factory Droid | `graphify install --platform droid` |
| Trae | `graphify install --platform trae` |
| Trae CN | `graphify install --platform trae-cn` |
Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `multi_agent = true`,这样才能并行提取。OpenClaw 目前的并行 agent 支持还比较早期,所以使用顺序提取。Trae 使用 Agent 工具进行并行子代理调度,**不支持** PreToolUse hook,因此 AGENTS.md 是其常驻机制。
然后打开你的 AI 编码助手,输入:
```
/graphify .
```
### 让助手始终优先使用图谱(推荐)
图构建完成后,在项目里运行一次:
| 平台 | 命令 |
|------|------|
| Claude Code | `graphify claude install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| OpenClaw | `graphify claw install` |
| Factory Droid | `graphify droid install` |
| Trae | `graphify trae install` |
| Trae CN | `graphify trae-cn install` |
**Claude Code** 会做两件事:
1. 在 `CLAUDE.md` 中写入一段规则,告诉 Claude 在回答架构问题前先读 `graphify-out/GRAPH_REPORT.md`
2. 安装一个 **PreToolUse hook**(写入 `settings.json`),在每次 `Glob` 和 `Grep` 前触发
如果知识图谱存在,Claude 会先看到:_"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ —— 这样 Claude 会优先按图谱导航,而不是一上来就 grep 整个项目。
**Codex、OpenCode、OpenClaw、Factory Droid、Trae** 会把同样的规则写进项目根目录的 `AGENTS.md`。这些平台没有 PreToolUse hook,所以 `AGENTS.md` 是它们的常驻机制。
卸载时使用对应平台的 uninstall 命令即可(例如 `graphify claude uninstall`)。
**常驻模式和显式触发有什么区别?**
常驻 hook 会优先暴露 `GRAPH_REPORT.md` —— 这是一页式总结,包含 god nodes、社区结构和意外连接。你的助手在搜索文件前会先读它,因此会按结构导航,而不是按关键字乱搜。这已经能覆盖大部分日常问题。
`/graphify query`、`/graphify path` 和 `/graphify explain` 会更深入:它们会逐跳遍历底层 `graph.json`,追踪节点之间的精确路径,并展示边级别细节(关系类型、置信度、源位置)。当你想从图谱里精确回答某个问题,而不仅仅是获得整体感知时,就该用这些命令。
可以这样理解:常驻 hook 是先给助手一张地图,`/graphify` 这几个命令则是让它沿着地图精确导航。
<details>
<summary>手动安装(curl)</summary>
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
```
把下面内容加到 `~/.claude/CLAUDE.md`:
```
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
```
</details>
## 用法
```
/graphify # 对当前目录运行
/graphify ./raw # 对指定目录运行
/graphify ./raw --mode deep # 更激进地抽取 INFERRED 边
/graphify ./raw --update # 只重新提取变更文件,并合并到已有图谱
/graphify ./raw --cluster-only # 只重新聚类已有图谱,不重新提取
/graphify ./raw --no-viz # 跳过 HTML,只生成 report + JSON
/graphify ./raw --obsidian # 额外生成 Obsidian vault(可选)
/graphify add https://arxiv.org/abs/1706.03762 # 拉取论文、保存并更新图谱
/graphify add https://x.com/karpathy/status/... # 拉取推文
/graphify add https://... --author "Name" # 标记原作者
/graphify add https://... --contributor "Name" # 标记是谁把它加入语料库的
/graphify query "what connects attention to the optimizer?"
/graphify query "what connects attention to the optimizer?" --dfs # 追踪一条具体路径
/graphify query "what connects attention to the optimizer?" --budget 1500 # 把预算限制在 N tokens
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
/graphify ./raw --watch # 文件变更时自动同步图谱(代码:立即更新;文档:提醒你)
/graphify ./raw --wiki # 构建可供 agent 抓取的 wiki(index.md + 每个 community 一篇文章)
/graphify ./raw --svg # 导出 graph.svg
/graphify ./raw --graphml # 导出 graph.graphml(Gephi、yEd)
/graphify ./raw --neo4j # 生成给 Neo4j 用的 cypher.txt
/graphify ./raw --neo4j-push bolt://localhost:7687 # 直接推送到运行中的 Neo4j
/graphify ./raw --mcp # 启动 MCP stdio server
# git hooks - 跨平台,在 commit 和切分支后重建图谱
graphify hook install
graphify hook uninstall
graphify hook status
# 常驻助手规则 - 按平台区分
graphify claude install # CLAUDE.md + PreToolUse hook(Claude Code)
graphify claude uninstall
graphify codex install # AGENTS.md(Codex)
graphify opencode install # AGENTS.md(OpenCode)
graphify claw install # AGENTS.md(OpenClaw)
graphify droid install # AGENTS.md(Factory Droid)
graphify trae install # AGENTS.md(Trae)
graphify trae uninstall
graphify trae-cn install # AGENTS.md(Trae CN)
graphify trae-cn uninstall
```
支持混合文件类型:
| 类型 | 扩展名 | 提取方式 |
|------|--------|----------|
| 代码 | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php` | tree-sitter AST + 调用图 + docstring / 注释中的 rationale |
| 文档 | `.md .txt .rst` | 通过 Claude 提取概念、关系和设计动机 |
| 论文 | `.pdf` | 引文挖掘 + 概念提取 |
| 图片 | `.png .jpg .webp .gif` | Claude vision —— 截图、图表、任意语言都可以 |
## 你会得到什么
**God nodes** —— 度最高的概念节点(整个系统最容易汇聚到的地方)
**意外连接** —— 按综合得分排序。代码-论文之间的边会比代码-代码边权重更高。每条结果都会附带一段人话解释。
**建议提问** —— 图谱特别擅长回答的 4 到 5 个问题。
**“为什么”** —— docstring、行内注释(`# NOTE:`、`# IMPORTANT:`、`# HACK:`、`# WHY:`)以及文档里的设计动机都会被抽取成 `rationale_for` 节点。不只是知道代码“做了什么”,还能知道“为什么要这么写”。
**置信度分数** —— 每条 `INFERRED` 边都有 `confidence_score`(0.0-1.0)。你不只知道哪些是猜出来的,还知道模型对这个猜测有多有把握。`EXTRACTED` 边恒为 1.0。
**语义相似边** —— 跨文件的概念连接,即使结构上没有直接依赖也能建立关联。比如两个函数做的是同一类问题但彼此没有调用,或者某个代码类和某篇论文里的算法概念本质相同。
**超边(Hyperedges)** —— 用来表达 3 个以上节点的群组关系,这是普通两两边表达不出来的。比如:一组类共同实现一个协议、认证链路里的一组函数、同一篇论文某一节里的多个概念共同组成一个想法。
**Token 基准** —— 每次运行后都会自动打印。对混合语料(Karpathy 的仓库 + 论文 + 图片),每次查询的 token 消耗可以比直接读原文件少 **71.5 倍**。第一次运行需要先提取并建图,这一步会花 token;后续查询直接读取压缩后的图谱,节省会越来越明显。SHA256 缓存保证重复运行时只重新处理变更文件。
**自动同步**(`--watch`)—— 在后台终端里跑着,代码库一变化,图谱就会跟着更新。代码文件保存会立刻触发重建(只走 AST,不用 LLM);文档/图片变更则会提醒你跑 `--update` 进行 LLM 再提取。
**Git hooks**(`graphify hook install`)—— 安装 `post-commit` 和 `post-checkout` hook。每次 commit 后、每次切分支后都会自动重建图谱,不需要额外开一个后台进程。
**Wiki**(`--wiki`)—— 为每个 community 和 god node 生成类似维基百科的 Markdown 文章,并提供 `index.md` 作为入口。任何 agent 只要读 `index.md`,就能通过普通文件导航整个知识库,而不必直接解析 JSON。
## Worked examples
| 语料 | 文件数 | 压缩比 | 输出 |
|------|--------|--------|------|
| Karpathy 的仓库 + 5 篇论文 + 4 张图片 | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
| graphify 源码 + Transformer 论文 | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
| httpx(合成 Python 库) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
Token 压缩效果会随着语料规模增大而更明显。6 个文件本来就塞得进上下文窗口,所以 graphify 在这种场景里的价值更多是结构清晰度,而不是 token 压缩。到了 52 个文件(代码 + 论文 + 图片)这种规模,就能做到 71x+。每个 `worked/` 目录里都带了原始输入和真实输出(`GRAPH_REPORT.md`、`graph.json`),你可以自己跑一遍核对数字。
## 隐私
graphify 会把文档、论文和图片的内容发送给你所用 AI 编码助手背后的模型 API 来做语义提取 —— 可能是 Anthropic(Claude Code)、OpenAI(Codex),或者你当前平台使用的其他提供方。代码文件则完全在本地通过 tree-sitter AST 处理,不会把代码内容发出去。项目本身没有任何遥测、使用跟踪或分析。唯一的网络请求就是语义提取阶段调用你平台自己的模型 API,使用的也是你自己的 API key。
## 技术栈
NetworkX + Leiden(graspologic)+ tree-sitter + vis.js。语义提取由 Claude(Claude Code)、GPT-4(Codex)或你当前平台所运行的模型完成。不需要 Neo4j,不需要 server,整体是纯本地运行。
<details>
<summary>贡献</summary>
**Worked examples** 是最能建立信任的贡献方式。对一个真实语料跑 `/graphify`,把输出保存到 `worked/{slug}/`,再写一份诚实的 `review.md`,评价图谱哪些地方做得对、哪些地方做得不对,然后提交 PR。
**提取 bug** —— 提 issue 时请附上输入文件、对应的缓存项(`graphify-out/cache/`)以及它漏提取或瞎编了什么。
模块职责和新增语言的方法见 [ARCHITECTURE.md](ARCHITECTURE.md)。
</details>
+10 -10
View File
@@ -4,8 +4,8 @@
| Version | Supported |
|---------|-----------|
| 0.1.x | Yes |
| < 0.1 | No |
| 0.3.x | Yes |
| < 0.3 | No |
## Reporting a Vulnerability
@@ -22,27 +22,27 @@ We will acknowledge receipt within 48 hours and aim to release a fix within 7 da
## Security Model
graphify is a **local development tool**. It runs as a Claude Code skill and optionally as a local MCP stdio server. It makes no network calls during graph analysis — only during `ingest` (explicit URL fetch by the user).
graphify is a **local development tool**. It runs as a Claude Code skill and optionally as a local MCP stdio server. It makes no network calls during graph analysis - only during `ingest` (explicit URL fetch by the user).
### Threat Surface
| Vector | Mitigation |
|--------|-----------|
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes. Redirect targets are re-validated by `_NoFileRedirectHandler` — a redirect to `file://` is blocked. |
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes, blocks private/loopback/link-local IPs, and blocks cloud metadata endpoints. Redirect targets are re-validated. All fetch paths including tweet oEmbed go through `safe_fetch()`. |
| Oversized downloads | `safe_fetch()` streams responses and aborts at 50 MB. `safe_fetch_text()` aborts at 10 MB. |
| Non-2xx HTTP responses | `safe_fetch()` raises `HTTPError` on non-2xx status codes — error pages are not silently treated as content. |
| Path traversal in MCP server | `security.validate_graph_path()` resolves paths and requires them to be inside `.graphify/`. Also requires the `.graphify/` directory to exist. |
| Non-2xx HTTP responses | `safe_fetch()` raises `HTTPError` on non-2xx status codes - error pages are not silently treated as content. |
| Path traversal in MCP server | `security.validate_graph_path()` resolves paths and requires them to be inside `graphify-out/`. Also requires the `graphify-out/` directory to exist. |
| XSS in graph HTML output | `security.sanitize_label()` strips control characters, caps at 256 chars, and HTML-escapes all node labels and edge titles before pyvis embeds them. |
| Prompt injection via node labels | `sanitize_label()` also applied to MCP text output — node labels from user-controlled source files cannot break the text format returned to agents. |
| YAML frontmatter injection | Newlines stripped from user-provided strings before embedding in YAML frontmatter (e.g. in `save_query_result()`). |
| Encoding crashes on source files | All tree-sitter byte slices decoded with `errors="replace"` — non-UTF-8 source files degrade gracefully instead of crashing extraction. |
| Prompt injection via node labels | `sanitize_label()` also applied to MCP text output - node labels from user-controlled source files cannot break the text format returned to agents. |
| YAML frontmatter injection | `_yaml_str()` escapes backslashes, double quotes, and newlines before embedding user-controlled strings (webpage titles, query questions) in YAML frontmatter. |
| Encoding crashes on source files | All tree-sitter byte slices decoded with `errors="replace"` - non-UTF-8 source files degrade gracefully instead of crashing extraction. |
| Symlink traversal | `os.walk(..., followlinks=False)` is explicit throughout `detect.py`. |
| Corrupted graph.json | `_load_graph()` in `serve.py` wraps `json.JSONDecodeError` and prints a clear recovery message instead of crashing. |
### What graphify does NOT do
- Does not run a network listener (MCP server communicates over stdio only)
- Does not execute code from source files (tree-sitter parses ASTs — no eval/exec)
- Does not execute code from source files (tree-sitter parses ASTs - no eval/exec)
- Does not use `shell=True` in any subprocess call
- Does not store credentials or API keys
+2 -1
View File
@@ -1,4 +1,4 @@
"""graphify — extract · build · cluster · analyze · report."""
"""graphify - extract · build · cluster · analyze · report."""
def __getattr__(name):
@@ -18,6 +18,7 @@ def __getattr__(name):
"to_html": ("graphify.export", "to_html"),
"to_svg": ("graphify.export", "to_svg"),
"to_canvas": ("graphify.export", "to_canvas"),
"to_wiki": ("graphify.wiki", "to_wiki"),
}
if name in _map:
import importlib
+1292 -29
View File
File diff suppressed because it is too large. Load diff
+159 -48
View File
@@ -3,6 +3,11 @@ from __future__ import annotations
import networkx as nx
def _node_community_map(communities: dict[int, list[str]]) -> dict[str, int]:
"""Invert communities dict: node_id -> community_id."""
return {n: cid for cid, nodes in communities.items() for n in nodes}
def _is_file_node(G: nx.Graph, node_id: str) -> bool:
"""
Return True if this node is a file-level hub node (e.g. 'client', 'models')
@@ -11,16 +16,20 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
These are synthetic nodes created by the AST extractor and should be excluded
from god nodes, surprising connections, and knowledge gap reporting.
"""
label = G.nodes[node_id].get("label", "")
attrs = G.nodes[node_id]
label = attrs.get("label", "")
if not label:
return False
# File-level hub: label is a filename with a code extension
if label.split(".")[-1] in ("py", "ts", "js", "go", "rs", "java", "rb", "cpp", "c", "h"):
return True
# File-level hub: label matches the actual source filename (not just any label ending in .py)
source_file = attrs.get("source_file", "")
if source_file:
from pathlib import Path as _Path
if label == _Path(source_file).name:
return True
# Method stub: AST extractor labels methods as '.method_name()'
if label.startswith(".") and label.endswith("()"):
return True
# Module-level function stub: labeled 'function_name()' — only has a contains edge
# Module-level function stub: labeled 'function_name()' - only has a contains edge
# These are real functions but structurally isolated by definition; not a gap worth flagging
if label.endswith("()") and G.degree(node_id) <= 1:
return True
@@ -28,7 +37,7 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
def god_nodes(G: nx.Graph, top_n: int = 10) -> list[dict]:
"""Return the top_n most-connected real entities — the core abstractions.
"""Return the top_n most-connected real entities - the core abstractions.
File-level hub nodes are excluded: they accumulate import/contains edges
mechanically and don't represent meaningful architectural abstractions.
@@ -42,7 +51,7 @@ def god_nodes(G: nx.Graph, top_n: int = 10) -> list[dict]:
result.append({
"id": node_id,
"label": G.nodes[node_id].get("label", node_id),
"edges": deg,
"degree": deg,
})
if len(result) >= top_n:
break
@@ -55,7 +64,7 @@ def surprising_connections(
top_n: int = 5,
) -> list[dict]:
"""
Find connections that are genuinely surprising — not obvious from file structure.
Find connections that are genuinely surprising - not obvious from file structure.
Strategy:
- Multi-file corpora: cross-file edges between real entities (not concept nodes).
@@ -100,21 +109,102 @@ def _is_concept_node(G: nx.Graph, node_id: str) -> bool:
return False
from graphify.detect import CODE_EXTENSIONS, DOC_EXTENSIONS, PAPER_EXTENSIONS, IMAGE_EXTENSIONS
def _file_category(path: str) -> str:
ext = ("." + path.rsplit(".", 1)[-1].lower()) if "." in path else ""
if ext in CODE_EXTENSIONS:
return "code"
if ext in PAPER_EXTENSIONS:
return "paper"
if ext in IMAGE_EXTENSIONS:
return "image"
return "doc"
def _top_level_dir(path: str) -> str:
"""Return the first path component - used to detect cross-repo edges."""
return path.split("/")[0] if "/" in path else path
def _surprise_score(
G: nx.Graph,
u: str,
v: str,
data: dict,
node_community: dict[str, int],
u_source: str,
v_source: str,
) -> tuple[int, list[str]]:
"""Score how surprising a cross-file edge is. Returns (score, reasons)."""
score = 0
reasons: list[str] = []
# 1. Confidence weight - uncertain connections are more noteworthy
conf = data.get("confidence", "EXTRACTED")
conf_bonus = {"AMBIGUOUS": 3, "INFERRED": 2, "EXTRACTED": 1}.get(conf, 1)
score += conf_bonus
if conf in ("AMBIGUOUS", "INFERRED"):
reasons.append(f"{conf.lower()} connection - not explicitly stated in source")
# 2. Cross file-type bonus - code↔paper or code↔image is non-obvious
cat_u = _file_category(u_source)
cat_v = _file_category(v_source)
if cat_u != cat_v:
score += 2
reasons.append(f"crosses file types ({cat_u} ↔ {cat_v})")
# 3. Cross-repo bonus - different top-level directory
if _top_level_dir(u_source) != _top_level_dir(v_source):
score += 2
reasons.append("connects across different repos/directories")
# 4. Cross-community bonus - Leiden says these are structurally distant
cid_u = node_community.get(u)
cid_v = node_community.get(v)
if cid_u is not None and cid_v is not None and cid_u != cid_v:
score += 1
reasons.append("bridges separate communities")
# 4b. Semantic similarity bonus - non-obvious conceptual links score higher
if data.get("relation") == "semantically_similar_to":
score = int(score * 1.5)
reasons.append("semantically similar concepts with no structural link")
# 5. Peripheral→hub: a low-degree node connecting to a high-degree one
deg_u = G.degree(u)
deg_v = G.degree(v)
if min(deg_u, deg_v) <= 2 and max(deg_u, deg_v) >= 5:
score += 1
peripheral = G.nodes[u].get("label", u) if deg_u <= 2 else G.nodes[v].get("label", v)
hub = G.nodes[v].get("label", v) if deg_u <= 2 else G.nodes[u].get("label", u)
reasons.append(f"peripheral node `{peripheral}` unexpectedly reaches hub `{hub}`")
return score, reasons
def _cross_file_surprises(G: nx.Graph, communities: dict[int, list[str]], top_n: int) -> list[dict]:
"""
Cross-file edges between real code/doc entities.
Excludes concept nodes, file hub nodes, and plain import edges.
Sorted AMBIGUOUS → INFERRED → EXTRACTED.
Cross-file edges between real code/doc entities, ranked by a composite
surprise score rather than confidence alone.
Surprise score accounts for:
- Confidence (AMBIGUOUS > INFERRED > EXTRACTED)
- Cross file-type (code↔paper is more surprising than code↔code)
- Cross-repo (different top-level directory)
- Cross-community (Leiden says structurally distant)
- Peripheral→hub (low-degree node reaching a god node)
Each result includes a 'why' field explaining what makes it non-obvious.
"""
surprises = []
order = {"AMBIGUOUS": 0, "INFERRED": 1, "EXTRACTED": 2}
node_community = _node_community_map(communities)
candidates = []
for u, v, data in G.edges(data=True):
# Skip structural scaffolding — not insights
relation = data.get("relation", "")
if relation in ("imports", "imports_from", "contains", "method"):
continue
# Skip if either endpoint is a concept or file-level node
if _is_concept_node(G, u) or _is_concept_node(G, v):
continue
if _is_file_node(G, u) or _is_file_node(G, v):
@@ -123,28 +213,36 @@ def _cross_file_surprises(G: nx.Graph, communities: dict[int, list[str]], top_n:
u_source = G.nodes[u].get("source_file", "")
v_source = G.nodes[v].get("source_file", "")
if u_source and v_source and u_source != v_source:
# Respect original edge direction stored in _src/_tgt (if present),
# otherwise fall back to u/v which may be in arbitrary order.
src_id = data.get("_src", u)
tgt_id = data.get("_tgt", v)
surprises.append({
"source": G.nodes[src_id].get("label", src_id),
"target": G.nodes[tgt_id].get("label", tgt_id),
"source_files": [
G.nodes[src_id].get("source_file", ""),
G.nodes[tgt_id].get("source_file", ""),
],
"confidence": data.get("confidence", "EXTRACTED"),
"relation": relation,
})
if not u_source or not v_source or u_source == v_source:
continue
surprises.sort(key=lambda x: order.get(x["confidence"], 3))
if surprises:
return surprises[:top_n]
score, reasons = _surprise_score(G, u, v, data, node_community, u_source, v_source)
src_id = data.get("_src", u)
if src_id not in G.nodes:
src_id = u
tgt_id = data.get("_tgt", v)
if tgt_id not in G.nodes:
tgt_id = v
candidates.append({
"_score": score,
"source": G.nodes[src_id].get("label", src_id),
"target": G.nodes[tgt_id].get("label", tgt_id),
"source_files": [
G.nodes[src_id].get("source_file", ""),
G.nodes[tgt_id].get("source_file", ""),
],
"confidence": data.get("confidence", "EXTRACTED"),
"relation": relation,
"why": "; ".join(reasons) if reasons else "cross-file semantic connection",
})
candidates.sort(key=lambda x: x["_score"], reverse=True)
for c in candidates:
c.pop("_score")
if candidates:
return candidates[:top_n]
# Fallback: no semantic cross-file edges found (pure AST corpus).
# Surface cross-community bridge edges as structural surprises instead.
return _cross_community_surprises(G, communities, top_n)
@@ -155,15 +253,17 @@ def _cross_community_surprises(
) -> list[dict]:
"""
For single-source corpora: find edges that bridge different communities.
These are surprising because Leiden grouped everything else tightly —
These are surprising because Leiden grouped everything else tightly -
these edges cut across the natural structure.
Falls back to high-betweenness edges if no community info is provided.
"""
if not communities:
# No community info — use edge betweenness centrality
# No community info - use edge betweenness centrality
if G.number_of_edges() == 0:
return []
if G.number_of_nodes() > 5000:
return []
betweenness = nx.edge_betweenness_centrality(G)
top_edges = sorted(betweenness.items(), key=lambda x: x[1], reverse=True)[:top_n]
result = []
@@ -183,7 +283,7 @@ def _cross_community_surprises(
return result
# Build node → community map
node_community = {n: cid for cid, nodes in communities.items() for n in nodes}
node_community = _node_community_map(communities)
surprises = []
for u, v, data in G.edges(data=True):
@@ -197,10 +297,14 @@ def _cross_community_surprises(
relation = data.get("relation", "")
if relation in ("imports", "imports_from", "contains", "method"):
continue
# This edge crosses community boundaries — interesting
# This edge crosses community boundaries - interesting
confidence = data.get("confidence", "EXTRACTED")
src_id = data.get("_src", u)
if src_id not in G.nodes:
src_id = u
tgt_id = data.get("_tgt", v)
if tgt_id not in G.nodes:
tgt_id = v
surprises.append({
"source": G.nodes[src_id].get("label", src_id),
"target": G.nodes[tgt_id].get("label", tgt_id),
@@ -218,7 +322,7 @@ def _cross_community_surprises(
order = {"AMBIGUOUS": 0, "INFERRED": 1, "EXTRACTED": 2}
surprises.sort(key=lambda x: order.get(x["confidence"], 3))
# Deduplicate by community pair — one representative edge per (A→B) boundary.
# Deduplicate by community pair - one representative edge per (A→B) boundary.
# Without this, a single high-betweenness god node dominates all results.
seen_pairs: set[tuple] = set()
deduped = []
@@ -242,7 +346,7 @@ def suggest_questions(
Each question has a 'type', 'question', and 'why' field.
"""
questions = []
node_community = {n: cid for cid, nodes in communities.items() for n in nodes}
node_community = _node_community_map(communities)
# 1. AMBIGUOUS edges → unresolved relationship questions
for u, v, data in G.edges(data=True):
@@ -253,12 +357,13 @@ def suggest_questions(
questions.append({
"type": "ambiguous_edge",
"question": f"What is the exact relationship between `{ul}` and `{vl}`?",
"why": f"Edge tagged AMBIGUOUS (relation: {relation}) — confidence is low.",
"why": f"Edge tagged AMBIGUOUS (relation: {relation}) - confidence is low.",
})
# 2. Bridge nodes (high betweenness) → cross-cutting concern questions
if G.number_of_edges() > 0:
betweenness = nx.betweenness_centrality(G)
k = min(100, G.number_of_nodes()) if G.number_of_nodes() > 1000 else None
betweenness = nx.betweenness_centrality(G, k=k)
# Top bridge nodes that are NOT file-level hubs
bridges = sorted(
[(n, s) for n, s in betweenness.items()
@@ -277,7 +382,7 @@ def suggest_questions(
questions.append({
"type": "bridge_node",
"question": f"Why does `{label}` connect `{comm_label}` to {', '.join(f'`{l}`' for l in other_labels)}?",
"why": f"High betweenness centrality ({score:.3f}) — this node is a cross-community bridge.",
"why": f"High betweenness centrality ({score:.3f}) - this node is a cross-community bridge.",
})
# 3. God nodes with many INFERRED edges → verification questions
@@ -298,13 +403,17 @@ def suggest_questions(
others = []
for u, v, d in inferred[:2]:
src_id = d.get("_src", u)
if src_id not in G.nodes:
src_id = u
tgt_id = d.get("_tgt", v)
if tgt_id not in G.nodes:
tgt_id = v
other_id = tgt_id if src_id == node_id else src_id
others.append(G.nodes[other_id].get("label", other_id))
questions.append({
"type": "verify_inferred",
"question": f"Are the {len(inferred)} inferred relationships involving `{label}` (e.g. with `{others[0]}` and `{others[1]}`) actually correct?",
"why": f"`{label}` has {len(inferred)} INFERRED edges — model-reasoned connections that need verification.",
"why": f"`{label}` has {len(inferred)} INFERRED edges - model-reasoned connections that need verification.",
})
# 4. Isolated or weakly-connected nodes → exploration questions
@@ -317,7 +426,7 @@ def suggest_questions(
questions.append({
"type": "isolated_nodes",
"question": f"What connects {', '.join(f'`{l}`' for l in labels)} to the rest of the system?",
"why": f"{len(isolated)} weakly-connected nodes found — possible documentation gaps or missing edges.",
"why": f"{len(isolated)} weakly-connected nodes found - possible documentation gaps or missing edges.",
})
# 5. Low-cohesion communities → structural questions
@@ -329,7 +438,7 @@ def suggest_questions(
questions.append({
"type": "low_cohesion",
"question": f"Should `{label}` be split into smaller, more focused modules?",
"why": f"Cohesion score {score} — nodes in this community are weakly interconnected.",
"why": f"Cohesion score {score} - nodes in this community are weakly interconnected.",
})
if not questions:
@@ -375,7 +484,9 @@ def graph_diff(G_old: nx.Graph, G_new: nx.Graph) -> dict:
]
def edge_key(G: nx.Graph, u: str, v: str, data: dict) -> tuple:
return (u, v, data.get("relation", ""))
if G.is_directed():
return (u, v, data.get("relation", ""))
return (min(u, v), max(u, v), data.get("relation", ""))
old_edge_keys = {
edge_key(G_old, u, v, d)
+7 -4
View File
@@ -1,4 +1,4 @@
"""Token-reduction benchmark — measures how much context graphify saves vs naive full-corpus approach."""
"""Token-reduction benchmark - measures how much context graphify saves vs naive full-corpus approach."""
from __future__ import annotations
import json
from pathlib import Path
@@ -62,7 +62,7 @@ _SAMPLE_QUESTIONS = [
def run_benchmark(
graph_path: str = ".graphify/graph.json",
graph_path: str = "graphify-out/graph.json",
corpus_words: int | None = None,
questions: list[str] | None = None,
) -> dict:
@@ -75,8 +75,11 @@ def run_benchmark(
Returns dict with: corpus_tokens, avg_query_tokens, reduction_ratio, per_question
"""
data = json.loads(Path(graph_path).read_text())
G = json_graph.node_link_graph(data, edges="links")
data = json.loads(Path(graph_path).read_text(encoding="utf-8"))
try:
G = json_graph.node_link_graph(data, edges="links")
except TypeError:
G = json_graph.node_link_graph(data)
if corpus_words is None:
# Rough estimate: each node label is ~3 words, plus source context
+70 -14
View File
@@ -1,31 +1,87 @@
# assemble node+edge dicts into a NetworkX graph, preserving edge direction
#
# Node deduplication — three layers:
#
# 1. Within a file (AST): each extractor tracks a `seen_ids` set. A node ID is
# emitted at most once per file, so duplicate class/function definitions in
# the same source file are collapsed to the first occurrence.
#
# 2. Between files (build): NetworkX G.add_node() is idempotent — calling it
# twice with the same ID overwrites the attributes with the second call's
# values. Nodes are added in extraction order (AST first, then semantic),
# so if the same entity is extracted by both passes the semantic node
# silently overwrites the AST node. This is intentional: semantic nodes
# carry richer labels and cross-file context, while AST nodes have precise
# source_location. If you need to change the priority, reorder extractions
# passed to build().
#
# 3. Semantic merge (skill): before calling build(), the skill merges cached
# and new semantic results using an explicit `seen` set keyed on node["id"],
# so duplicates across cache hits and new extractions are resolved there
# before any graph construction happens.
#
from __future__ import annotations
import sys
import networkx as nx
from .validate import validate_extraction
def build_from_json(extraction: dict) -> nx.Graph:
def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
"""Build a NetworkX graph from an extraction dict.
directed=True produces a DiGraph that preserves edge direction (source→target).
directed=False (default) produces an undirected Graph for backward compatibility.
"""
# 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"])
errors = validate_extraction(extraction)
if errors:
print(f"[graphify] Extraction warning ({len(errors)} issues): {errors[0]}", file=sys.stderr)
G = nx.Graph()
# 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]
if real_errors:
print(f"[graphify] Extraction warning ({len(real_errors)} issues): {real_errors[0]}", file=sys.stderr)
G: nx.Graph = nx.DiGraph() if directed else nx.Graph()
for node in extraction.get("nodes", []):
G.add_node(node["id"], **{k: v for k, v in node.items() if k != "id"})
node_set = set(G.nodes())
for edge in extraction.get("edges", []):
if "source" not in edge and "from" in edge:
edge["source"] = edge["from"]
if "target" not in edge and "to" in edge:
edge["target"] = edge["to"]
if "source" not in edge or "target" not in edge:
continue
src, tgt = edge["source"], edge["target"]
if src not in node_set or tgt not in node_set:
continue # skip edges to external/stdlib nodes - expected, not an error
attrs = {k: v for k, v in edge.items() if k not in ("source", "target")}
# Preserve original edge direction — undirected graphs lose it otherwise,
# Preserve original edge direction - undirected graphs lose it otherwise,
# causing display functions to show edges backwards.
attrs["_src"] = edge["source"]
attrs["_tgt"] = edge["target"]
G.add_edge(edge["source"], edge["target"], **attrs)
attrs["_src"] = src
attrs["_tgt"] = tgt
G.add_edge(src, tgt, **attrs)
hyperedges = extraction.get("hyperedges", [])
if hyperedges:
G.graph["hyperedges"] = hyperedges
return G
def build(extractions: list[dict]) -> nx.Graph:
"""Merge multiple extraction results into one graph."""
G = nx.Graph()
def build(extractions: list[dict], *, directed: bool = False) -> nx.Graph:
"""Merge multiple extraction results into one graph.
directed=True produces a DiGraph that preserves edge direction (source→target).
directed=False (default) produces an undirected Graph for backward compatibility.
Extractions are merged in order. For nodes with the same ID, the last
extraction's attributes win (NetworkX add_node overwrites). Pass AST
results before semantic results so semantic labels take precedence, or
reverse the order if you prefer AST source_location precision to win.
"""
combined: dict = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0}
for ext in extractions:
sub = build_from_json(ext)
G.update(sub)
return G
combined["nodes"].extend(ext.get("nodes", []))
combined["edges"].extend(ext.get("edges", []))
combined["hyperedges"].extend(ext.get("hyperedges", []))
combined["input_tokens"] += ext.get("input_tokens", 0)
combined["output_tokens"] += ext.get("output_tokens", 0)
return build_from_json(combined, directed=directed)
+69 -18
View File
@@ -1,20 +1,49 @@
# per-file extraction cache — skip unchanged files on re-run
# per-file extraction cache - skip unchanged files on re-run
from __future__ import annotations
import hashlib
import json
import shutil
import os
from pathlib import Path
def file_hash(path: Path) -> str:
"""SHA256 of file contents, hex digest."""
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def _body_content(content: bytes) -> bytes:
"""Strip YAML frontmatter from Markdown content, returning only the body."""
text = content.decode(errors="replace")
if text.startswith("---"):
end = text.find("\n---", 3)
if end != -1:
return text[end + 4:].encode()
return content
def file_hash(path: Path, root: Path = Path(".")) -> str:
"""SHA256 of file contents + path relative to root.
Using a relative path (not absolute) makes cache entries portable across
machines and checkout directories, so shared caches and CI work correctly.
Falls back to the resolved absolute path if the file is outside root.
For Markdown files (.md), only the body below the YAML frontmatter is hashed,
so metadata-only changes (e.g. reviewed, status, tags) do not invalidate the cache.
"""
p = Path(path)
raw = p.read_bytes()
content = _body_content(raw) if p.suffix.lower() == ".md" else raw
h = hashlib.sha256()
h.update(content)
h.update(b"\x00")
try:
rel = p.resolve().relative_to(Path(root).resolve())
h.update(str(rel).encode())
except ValueError:
h.update(str(p.resolve()).encode())
return h.hexdigest()
def cache_dir(root: Path = Path(".")) -> Path:
"""Returns .graphify/cache/ — creates it if needed."""
d = Path(root) / ".graphify" / "cache"
"""Returns graphify-out/cache/ - creates it if needed."""
d = Path(root) / "graphify-out" / "cache"
d.mkdir(parents=True, exist_ok=True)
return d
@@ -23,18 +52,18 @@ def load_cached(path: Path, root: Path = Path(".")) -> dict | None:
"""Return cached extraction for this file if hash matches, else None.
Cache key: SHA256 of file contents.
Cache value: stored as .graphify/cache/{hash}.json
Cache value: stored as graphify-out/cache/{hash}.json
Returns None if no cache entry or file has changed.
"""
try:
h = file_hash(path)
h = file_hash(path, root)
except OSError:
return None
entry = cache_dir(root) / f"{h}.json"
if not entry.exists():
return None
try:
return json.loads(entry.read_text())
return json.loads(entry.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
return None
@@ -42,12 +71,25 @@ def load_cached(path: Path, root: Path = Path(".")) -> dict | None:
def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
"""Save extraction result for this file.
Stores as .graphify/cache/{hash}.json where hash = SHA256 of current file contents.
Stores as graphify-out/cache/{hash}.json where hash = SHA256 of current file contents.
result should be a dict with 'nodes' and 'edges' lists.
"""
h = file_hash(path)
h = file_hash(path, root)
entry = cache_dir(root) / f"{h}.json"
entry.write_text(json.dumps(result))
tmp = entry.with_suffix(".tmp")
try:
tmp.write_text(json.dumps(result), encoding="utf-8")
try:
os.replace(tmp, entry)
except PermissionError:
# Windows: os.replace can fail with WinError 5 if the target is
# briefly locked. Fall back to copy-then-delete.
import shutil
shutil.copy2(tmp, entry)
tmp.unlink(missing_ok=True)
except Exception:
tmp.unlink(missing_ok=True)
raise
def cached_files(root: Path = Path(".")) -> set[str]:
@@ -57,7 +99,7 @@ def cached_files(root: Path = Path(".")) -> set[str]:
def clear_cache(root: Path = Path(".")) -> None:
"""Delete all .graphify/cache/*.json files."""
"""Delete all graphify-out/cache/*.json files."""
d = cache_dir(root)
for f in d.glob("*.json"):
f.unlink()
@@ -66,14 +108,15 @@ def clear_cache(root: Path = Path(".")) -> None:
def check_semantic_cache(
files: list[str],
root: Path = Path("."),
) -> tuple[list[dict], list[dict], list[str]]:
) -> tuple[list[dict], list[dict], list[dict], list[str]]:
"""Check semantic extraction cache for a list of absolute file paths.
Returns (cached_nodes, cached_edges, uncached_files).
Returns (cached_nodes, cached_edges, cached_hyperedges, uncached_files).
Uncached files need Claude extraction; cached files are merged directly.
"""
cached_nodes: list[dict] = []
cached_edges: list[dict] = []
cached_hyperedges: list[dict] = []
uncached: list[str] = []
for fpath in files:
@@ -81,15 +124,17 @@ def check_semantic_cache(
if result is not None:
cached_nodes.extend(result.get("nodes", []))
cached_edges.extend(result.get("edges", []))
cached_hyperedges.extend(result.get("hyperedges", []))
else:
uncached.append(fpath)
return cached_nodes, cached_edges, uncached
return cached_nodes, cached_edges, cached_hyperedges, uncached
def save_semantic_cache(
nodes: list[dict],
edges: list[dict],
hyperedges: list[dict] | None = None,
root: Path = Path("."),
) -> int:
"""Save semantic extraction results to cache, keyed by source_file.
@@ -99,7 +144,7 @@ def save_semantic_cache(
"""
from collections import defaultdict
by_file: dict[str, dict] = defaultdict(lambda: {"nodes": [], "edges": []})
by_file: dict[str, dict] = defaultdict(lambda: {"nodes": [], "edges": [], "hyperedges": []})
for n in nodes:
src = n.get("source_file", "")
if src:
@@ -108,10 +153,16 @@ def save_semantic_cache(
src = e.get("source_file", "")
if src:
by_file[src]["edges"].append(e)
for h in (hyperedges or []):
src = h.get("source_file", "")
if src:
by_file[src]["hyperedges"].append(h)
saved = 0
for fpath, result in by_file.items():
p = Path(fpath)
if not p.is_absolute():
p = Path(root) / p
if p.exists():
save_cached(p, result, root)
saved += 1
+56 -23
View File
@@ -1,24 +1,56 @@
"""Leiden community detection on NetworkX graphs. Splits oversized communities. Returns cohesion scores."""
"""Community detection on NetworkX graphs. Uses Leiden (graspologic) if available, falls back to Louvain (networkx). Splits oversized communities. Returns cohesion scores."""
from __future__ import annotations
import contextlib
import inspect
import io
import sys
import networkx as nx
def build_graph(nodes: list[dict], edges: list[dict]) -> nx.Graph:
"""Build a NetworkX graph from graphify node/edge dicts.
def _suppress_output():
"""Context manager to suppress stdout/stderr during library calls.
Preserves original edge direction as _src/_tgt attributes so that
display functions can show relationships in the correct direction,
even though the graph is undirected for structural analysis.
graspologic's leiden() emits ANSI escape sequences (progress bars,
colored warnings) that corrupt PowerShell 5.1's scroll buffer on
Windows (see issue #19). Redirecting stdout/stderr to devnull during
the call prevents this without losing any graphify output.
"""
G = nx.Graph()
for n in nodes:
G.add_node(n["id"], **{k: v for k, v in n.items() if k != "id"})
for e in edges:
attrs = {k: v for k, v in e.items() if k not in ("source", "target")}
attrs["_src"] = e["source"]
attrs["_tgt"] = e["target"]
G.add_edge(e["source"], e["target"], **attrs)
return G
return contextlib.redirect_stdout(io.StringIO())
def _partition(G: nx.Graph) -> dict[str, int]:
"""Run community detection. Returns {node_id: community_id}.
Tries Leiden (graspologic) first — best quality.
Falls back to Louvain (built into networkx) if graspologic is not installed.
Output from graspologic is suppressed to prevent ANSI escape codes
from corrupting terminal scroll buffers on Windows PowerShell 5.1.
"""
try:
from graspologic.partition import leiden
# Suppress graspologic output to prevent ANSI escape codes from
# corrupting PowerShell 5.1 scroll buffer (issue #19)
old_stderr = sys.stderr
try:
sys.stderr = io.StringIO()
with _suppress_output():
result = leiden(G)
finally:
sys.stderr = old_stderr
return result
except ImportError:
pass
# Fallback: networkx louvain (available since networkx 2.7).
# Inspect kwargs to stay compatible across NetworkX versions — max_level
# was added in a later release and prevents hangs on large sparse graphs.
kwargs: dict = {"seed": 42, "threshold": 1e-4}
if "max_level" in inspect.signature(nx.community.louvain_communities).parameters:
kwargs["max_level"] = 10
communities = nx.community.louvain_communities(G, **kwargs)
return {node: cid for cid, nodes in enumerate(communities) for node in nodes}
_MAX_COMMUNITY_FRACTION = 0.25 # communities larger than 25% of graph get split
_MIN_SPLIT_SIZE = 10 # only split if community has at least this many nodes
@@ -30,22 +62,25 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
Community IDs are stable across runs: 0 = largest community after splitting.
Oversized communities (> 25% of graph nodes, min 10) are split by running
a second Leiden pass on the subgraph.
Accepts directed or undirected graphs. DiGraphs are converted to undirected
internally since Louvain/Leiden require undirected input.
"""
if G.number_of_nodes() == 0:
return {}
if G.is_directed():
G = G.to_undirected()
if G.number_of_edges() == 0:
return {i: [n] for i, n in enumerate(sorted(G.nodes))}
from graspologic.partition import leiden # lazy — avoids 15s numba JIT on import
# Leiden warns and drops isolates — handle them separately
# Leiden warns and drops isolates - handle them separately
isolates = [n for n in G.nodes() if G.degree(n) == 0]
connected_nodes = [n for n in G.nodes() if G.degree(n) > 0]
connected = G.subgraph(connected_nodes)
raw: dict[int, list[str]] = {}
if connected.number_of_nodes() > 0:
partition: dict[str, int] = leiden(connected)
partition = _partition(connected)
for node, cid in partition.items():
raw.setdefault(cid, []).append(node)
@@ -73,16 +108,14 @@ def _split_community(G: nx.Graph, nodes: list[str]) -> list[list[str]]:
"""Run a second Leiden pass on a community subgraph to split it further."""
subgraph = G.subgraph(nodes)
if subgraph.number_of_edges() == 0:
# No edges — split into individual nodes
# No edges - split into individual nodes
return [[n] for n in sorted(nodes)]
try:
from graspologic.partition import leiden
sub_partition: dict[str, int] = leiden(subgraph)
sub_partition = _partition(subgraph)
sub_communities: dict[int, list[str]] = {}
for node, cid in sub_partition.items():
sub_communities.setdefault(cid, []).append(node)
if len(sub_communities) <= 1:
# Leiden couldn't split it — return as-is
return [sorted(nodes)]
return [sorted(v) for v in sub_communities.values()]
except Exception:
+259 -23
View File
@@ -1,6 +1,8 @@
# file discovery, type classification, and corpus health checks
from __future__ import annotations
import fnmatch
import json
import os
import re
from enum import Enum
from pathlib import Path
@@ -11,20 +13,23 @@ class FileType(str, Enum):
DOCUMENT = "document"
PAPER = "paper"
IMAGE = "image"
VIDEO = "video"
_MANIFEST_PATH = ".graphify/manifest.json"
_MANIFEST_PATH = "graphify-out/manifest.json"
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.tsx', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php'}
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.ejs', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.dart', '.v', '.sv'}
DOC_EXTENSIONS = {'.md', '.txt', '.rst'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
OFFICE_EXTENSIONS = {'.docx', '.xlsx'}
VIDEO_EXTENSIONS = {'.mp4', '.mov', '.webm', '.mkv', '.avi', '.m4v', '.mp3', '.wav', '.m4a', '.ogg'}
CORPUS_WARN_THRESHOLD = 50_000 # words — below this, warn "you may not need a graph"
CORPUS_UPPER_THRESHOLD = 500_000 # words — above this, warn about token cost
FILE_COUNT_UPPER = 200 # files — above this, warn about token cost
CORPUS_WARN_THRESHOLD = 50_000 # words - below this, warn "you may not need a graph"
CORPUS_UPPER_THRESHOLD = 500_000 # words - above this, warn about token cost
FILE_COUNT_UPPER = 200 # files - above this, warn about token cost
# Files that may contain secrets — skip silently
# Files that may contain secrets - skip silently
_SENSITIVE_PATTERNS = [
re.compile(r'(^|[\\/])\.(env|envrc)(\.|$)', re.IGNORECASE),
re.compile(r'\.(pem|key|p12|pfx|cert|crt|der|p8)$', re.IGNORECASE),
@@ -64,18 +69,27 @@ def _looks_like_paper(path: Path) -> bool:
"""Heuristic: does this text file read like an academic paper?"""
try:
# Only scan first 3000 chars for speed
text = path.read_text(errors="ignore")[:3000]
text = path.read_text(encoding="utf-8", errors="ignore")[:3000]
hits = sum(1 for pattern in _PAPER_SIGNALS if pattern.search(text))
return hits >= _PAPER_SIGNAL_THRESHOLD
except Exception:
return False
_ASSET_DIR_MARKERS = {".imageset", ".xcassets", ".appiconset", ".colorset", ".launchimage"}
def classify_file(path: Path) -> FileType | None:
# Compound extensions must be checked before simple suffix lookup
if path.name.lower().endswith(".blade.php"):
return FileType.CODE
ext = path.suffix.lower()
if ext in CODE_EXTENSIONS:
return FileType.CODE
if ext in PAPER_EXTENSIONS:
# PDFs inside Xcode asset catalogs are vector icons, not papers
if any(part.endswith(tuple(_ASSET_DIR_MARKERS)) for part in path.parts):
return None
return FileType.PAPER
if ext in IMAGE_EXTENSIONS:
return FileType.IMAGE
@@ -84,6 +98,10 @@ def classify_file(path: Path) -> FileType | None:
if _looks_like_paper(path):
return FileType.PAPER
return FileType.DOCUMENT
if ext in OFFICE_EXTENSIONS:
return FileType.DOCUMENT
if ext in VIDEO_EXTENSIONS:
return FileType.VIDEO
return None
@@ -102,16 +120,121 @@ def extract_pdf_text(path: Path) -> str:
return ""
def docx_to_markdown(path: Path) -> str:
"""Convert a .docx file to markdown text using python-docx."""
try:
from docx import Document
from docx.oxml.ns import qn
doc = Document(str(path))
lines = []
for para in doc.paragraphs:
style = para.style.name if para.style else ""
text = para.text.strip()
if not text:
lines.append("")
continue
if style.startswith("Heading 1"):
lines.append(f"# {text}")
elif style.startswith("Heading 2"):
lines.append(f"## {text}")
elif style.startswith("Heading 3"):
lines.append(f"### {text}")
elif style.startswith("List"):
lines.append(f"- {text}")
else:
lines.append(text)
# Tables
for table in doc.tables:
rows = [[cell.text.strip() for cell in row.cells] for row in table.rows]
if not rows:
continue
header = "| " + " | ".join(rows[0]) + " |"
sep = "| " + " | ".join("---" for _ in rows[0]) + " |"
lines.extend([header, sep])
for row in rows[1:]:
lines.append("| " + " | ".join(row) + " |")
return "\n".join(lines)
except ImportError:
return ""
except Exception:
return ""
def xlsx_to_markdown(path: Path) -> str:
"""Convert an .xlsx file to markdown text using openpyxl."""
try:
import openpyxl
wb = openpyxl.load_workbook(str(path), read_only=True, data_only=True)
sections = []
for sheet_name in wb.sheetnames:
ws = wb[sheet_name]
rows = []
for row in ws.iter_rows(values_only=True):
# Skip entirely empty rows
if all(cell is None for cell in row):
continue
rows.append([str(cell) if cell is not None else "" for cell in row])
if not rows:
continue
sections.append(f"## Sheet: {sheet_name}")
if len(rows) >= 1:
header = "| " + " | ".join(rows[0]) + " |"
sep = "| " + " | ".join("---" for _ in rows[0]) + " |"
sections.extend([header, sep])
for row in rows[1:]:
sections.append("| " + " | ".join(row) + " |")
wb.close()
return "\n".join(sections)
except ImportError:
return ""
except Exception:
return ""
def convert_office_file(path: Path, out_dir: Path) -> Path | None:
"""Convert a .docx or .xlsx to a markdown sidecar in out_dir.
Returns the path of the converted .md file, or None if conversion failed
or the required library is not installed.
"""
ext = path.suffix.lower()
if ext == ".docx":
text = docx_to_markdown(path)
elif ext == ".xlsx":
text = xlsx_to_markdown(path)
else:
return None
if not text.strip():
return None
out_dir.mkdir(parents=True, exist_ok=True)
# Use a stable name derived from the original path to avoid collisions
import hashlib
name_hash = hashlib.sha256(str(path.resolve()).encode()).hexdigest()[:8]
out_path = out_dir / f"{path.stem}_{name_hash}.md"
out_path.write_text(
f"<!-- converted from {path.name} -->\n\n{text}",
encoding="utf-8",
)
return out_path
def count_words(path: Path) -> int:
try:
if path.suffix.lower() == ".pdf":
ext = path.suffix.lower()
if ext == ".pdf":
return len(extract_pdf_text(path).split())
return len(path.read_text(errors="ignore").split())
if ext == ".docx":
return len(docx_to_markdown(path).split())
if ext == ".xlsx":
return len(xlsx_to_markdown(path).split())
return len(path.read_text(encoding="utf-8", errors="ignore").split())
except Exception:
return 0
# Directory names to always skip — venvs, caches, build artifacts, deps
# Directory names to always skip - venvs, caches, build artifacts, deps
_SKIP_DIRS = {
"venv", ".venv", "env", ".env",
"node_modules", "__pycache__", ".git",
@@ -121,6 +244,13 @@ _SKIP_DIRS = {
".tox", ".eggs", "*.egg-info",
}
# Large generated files that are never useful to extract
_SKIP_FILES = {
"package-lock.json", "yarn.lock", "pnpm-lock.yaml",
"Cargo.lock", "poetry.lock", "Gemfile.lock",
"composer.lock", "go.sum", "go.work.sum",
}
def _is_noise_dir(part: str) -> bool:
"""Return True if this directory name looks like a venv, cache, or dep dir."""
if part in _SKIP_DIRS:
@@ -133,19 +263,92 @@ def _is_noise_dir(part: str) -> bool:
return False
def detect(root: Path) -> dict:
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
"""Read .graphifyignore from root **and ancestor directories**.
Returns a list of (anchor_dir, pattern) pairs. Each pattern is matched
against paths relative to both the scan root and the anchor_dir where
the .graphifyignore file was found — so patterns written relative to a
parent directory still work when graphify is run on a subfolder.
Walks upward from *root* towards the filesystem root, stopping at a
``.git`` boundary. Lines starting with # are comments; blank lines ignored.
"""
patterns: list[tuple[Path, str]] = []
current = root.resolve()
while True:
ignore_file = current / ".graphifyignore"
if ignore_file.exists():
for line in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
line = line.strip()
if line and not line.startswith("#"):
patterns.append((current, line))
# Stop climbing once we've processed the git repo root
if (current / ".git").exists():
break
parent = current.parent
if parent == current:
break # filesystem root
current = parent
return patterns
def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
"""Return True if path matches any .graphifyignore pattern."""
if not patterns:
return False
def _matches(rel: str, p: str) -> bool:
parts = rel.split("/")
if fnmatch.fnmatch(rel, p):
return True
if fnmatch.fnmatch(path.name, p):
return True
for i, part in enumerate(parts):
if fnmatch.fnmatch(part, p):
return True
if fnmatch.fnmatch("/".join(parts[:i + 1]), p):
return True
return False
for anchor, pattern in patterns:
p = pattern.strip("/")
if not p:
continue
# Try path relative to the scan root
try:
rel = str(path.relative_to(root)).replace(os.sep, "/")
if _matches(rel, p):
return True
except ValueError:
pass
# Also try relative to the anchor dir (the .graphifyignore's location),
# so patterns written at a parent level still fire when running on a subfolder
if anchor != root:
try:
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
if _matches(rel_anchor, p):
return True
except ValueError:
pass
return False
def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
files: dict[FileType, list[str]] = {
FileType.CODE: [],
FileType.DOCUMENT: [],
FileType.PAPER: [],
FileType.IMAGE: [],
FileType.VIDEO: [],
}
total_words = 0
skipped_sensitive: list[str] = []
ignore_patterns = _load_graphifyignore(root)
# Always include .graphify/memory/ — query results filed back into the graph
memory_dir = root / ".graphify" / "memory"
# Always include graphify-out/memory/ - query results filed back into the graph
memory_dir = root / "graphify-out" / "memory"
scan_paths = [root]
if memory_dir.exists():
scan_paths.append(memory_dir)
@@ -155,21 +358,32 @@ def detect(root: Path) -> dict:
for scan_root in scan_paths:
in_memory_tree = memory_dir.exists() and str(scan_root).startswith(str(memory_dir))
import os
for dirpath, dirnames, filenames in os.walk(scan_root, followlinks=False):
for dirpath, dirnames, filenames in os.walk(scan_root, followlinks=follow_symlinks):
dp = Path(dirpath)
if follow_symlinks and os.path.islink(dirpath):
real = os.path.realpath(dirpath)
parent_real = os.path.realpath(os.path.dirname(dirpath))
if parent_real == real or parent_real.startswith(real + os.sep):
dirnames.clear()
continue
if not in_memory_tree:
# Prune noise dirs in-place so os.walk never descends into them
dirnames[:] = [
d for d in dirnames
if not d.startswith(".") and not _is_noise_dir(d)
if not d.startswith(".")
and not _is_noise_dir(d)
and not _is_ignored(dp / d, root, ignore_patterns)
]
for fname in filenames:
if fname in _SKIP_FILES:
continue
p = dp / fname
if p not in seen:
seen.add(p)
all_files.append(p)
converted_dir = root / "graphify-out" / "converted"
for p in all_files:
# For memory dir files, skip hidden/noise filtering
in_memory = memory_dir.exists() and str(p).startswith(str(memory_dir))
@@ -178,22 +392,38 @@ def detect(root: Path) -> dict:
# but catch hidden files at the root level
if p.name.startswith("."):
continue
# Skip files inside our own converted/ dir (avoid re-processing sidecars)
if str(p).startswith(str(converted_dir)):
continue
if _is_ignored(p, root, ignore_patterns):
continue
if _is_sensitive(p):
skipped_sensitive.append(str(p))
continue
ftype = classify_file(p)
if ftype:
# Office files: convert to markdown sidecar so subagents can read them
if p.suffix.lower() in OFFICE_EXTENSIONS:
md_path = convert_office_file(p, converted_dir)
if md_path:
files[ftype].append(str(md_path))
total_words += count_words(md_path)
else:
# Conversion failed (library not installed) - skip with note
skipped_sensitive.append(str(p) + " [office conversion failed - pip install graphifyy[office]]")
continue
files[ftype].append(str(p))
total_words += count_words(p)
if ftype != FileType.VIDEO:
total_words += count_words(p)
total_files = sum(len(v) for v in files.values())
needs_graph = total_words >= CORPUS_WARN_THRESHOLD
# Determine warning — lower bound, upper bound, or sensitive files skipped
# Determine warning - lower bound, upper bound, or sensitive files skipped
warning: str | None = None
if not needs_graph:
warning = (
f"Corpus is ~{total_words:,} words — fits in a single context window. "
f"Corpus is ~{total_words:,} words - fits in a single context window. "
f"You may not need a graph."
)
elif total_words >= CORPUS_UPPER_THRESHOLD or total_files >= FILE_COUNT_UPPER:
@@ -210,13 +440,14 @@ def detect(root: Path) -> dict:
"needs_graph": needs_graph,
"warning": warning,
"skipped_sensitive": skipped_sensitive,
"graphifyignore_patterns": len(ignore_patterns),
}
def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict[str, float]:
"""Load the file modification time manifest from a previous run."""
try:
return json.loads(Path(manifest_path).read_text())
return json.loads(Path(manifest_path).read_text(encoding="utf-8"))
except Exception:
return {}
@@ -229,9 +460,9 @@ def save_manifest(files: dict[str, list[str]], manifest_path: str = _MANIFEST_PA
try:
manifest[f] = Path(f).stat().st_mtime
except OSError:
pass # file deleted between detect() and manifest write — skip it
pass # file deleted between detect() and manifest write - skip it
Path(manifest_path).parent.mkdir(parents=True, exist_ok=True)
Path(manifest_path).write_text(json.dumps(manifest, indent=2))
Path(manifest_path).write_text(json.dumps(manifest, indent=2), encoding="utf-8")
def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
@@ -244,7 +475,7 @@ def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
manifest = load_manifest(manifest_path)
if not manifest:
# No previous run — treat everything as new
# No previous run - treat everything as new
full["incremental"] = True
full["new_files"] = full["files"]
full["unchanged_files"] = {k: [] for k in full["files"]}
@@ -266,9 +497,14 @@ def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
else:
unchanged_files[ftype].append(f)
# Files in manifest that no longer exist - their cached nodes are now ghost nodes
current_files = {f for flist in full["files"].values() for f in flist}
deleted_files = [f for f in manifest if f not in current_files]
new_total = sum(len(v) for v in new_files.values())
full["incremental"] = True
full["new_files"] = new_files
full["unchanged_files"] = unchanged_files
full["new_total"] = new_total
full["deleted_files"] = deleted_files
return full
+448 -90
View File
@@ -1,5 +1,6 @@
# write graph to HTML, JSON, SVG, Obsidian vault, and Neo4j Cypher
# write graph to HTML, JSON, SVG, GraphML, Obsidian vault, and Neo4j Cypher
from __future__ import annotations
import html as _html
import json
import math
import re
@@ -8,6 +9,13 @@ from pathlib import Path
import networkx as nx
from networkx.readwrite import json_graph
from graphify.security import sanitize_label
from graphify.analyze import _node_community_map
def _strip_diacritics(text: str) -> str:
import unicodedata
nfkd = unicodedata.normalize("NFKD", text)
return "".join(c for c in nfkd if not unicodedata.combining(c))
COMMUNITY_COLORS = [
"#4E79A7", "#F28E2B", "#E15759", "#76B7B2", "#59A14F",
@@ -17,30 +25,317 @@ COMMUNITY_COLORS = [
MAX_NODES_FOR_VIZ = 5_000
def _html_styles() -> str:
return """<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { background: #0f0f1a; color: #e0e0e0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; display: flex; height: 100vh; overflow: hidden; }
#graph { flex: 1; }
#sidebar { width: 280px; background: #1a1a2e; border-left: 1px solid #2a2a4e; display: flex; flex-direction: column; overflow: hidden; }
#search-wrap { padding: 12px; border-bottom: 1px solid #2a2a4e; }
#search { width: 100%; background: #0f0f1a; border: 1px solid #3a3a5e; color: #e0e0e0; padding: 7px 10px; border-radius: 6px; font-size: 13px; outline: none; }
#search:focus { border-color: #4E79A7; }
#search-results { max-height: 140px; overflow-y: auto; padding: 4px 12px; border-bottom: 1px solid #2a2a4e; display: none; }
.search-item { padding: 4px 6px; cursor: pointer; border-radius: 4px; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.search-item:hover { background: #2a2a4e; }
#info-panel { padding: 14px; border-bottom: 1px solid #2a2a4e; min-height: 140px; }
#info-panel h3 { font-size: 13px; color: #aaa; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.05em; }
#info-content { font-size: 13px; color: #ccc; line-height: 1.6; }
#info-content .field { margin-bottom: 5px; }
#info-content .field b { color: #e0e0e0; }
#info-content .empty { color: #555; font-style: italic; }
.neighbor-link { display: block; padding: 2px 6px; margin: 2px 0; border-radius: 3px; cursor: pointer; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border-left: 3px solid #333; }
.neighbor-link:hover { background: #2a2a4e; }
#neighbors-list { max-height: 160px; overflow-y: auto; margin-top: 4px; }
#legend-wrap { flex: 1; overflow-y: auto; padding: 12px; }
#legend-wrap h3 { font-size: 13px; color: #aaa; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.05em; }
.legend-item { display: flex; align-items: center; gap: 8px; padding: 4px 0; cursor: pointer; border-radius: 4px; font-size: 12px; }
.legend-item:hover { background: #2a2a4e; padding-left: 4px; }
.legend-item.dimmed { opacity: 0.35; }
.legend-dot { width: 12px; height: 12px; border-radius: 50%; flex-shrink: 0; }
.legend-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.legend-count { color: #666; font-size: 11px; }
#stats { padding: 10px 14px; border-top: 1px solid #2a2a4e; font-size: 11px; color: #555; }
</style>"""
def _hyperedge_script(hyperedges_json: str) -> str:
return f"""<script>
// Render hyperedges as shaded regions
const hyperedges = {hyperedges_json};
// afterDrawing passes ctx already transformed to network coordinate space.
// Draw node positions raw — no manual pan/zoom/DPR math needed.
network.on('afterDrawing', function(ctx) {{
hyperedges.forEach(h => {{
const positions = h.nodes
.map(nid => network.getPositions([nid])[nid])
.filter(p => p !== undefined);
if (positions.length < 2) return;
ctx.save();
ctx.globalAlpha = 0.12;
ctx.fillStyle = '#6366f1';
ctx.strokeStyle = '#6366f1';
ctx.lineWidth = 2;
ctx.beginPath();
// Centroid and expanded hull in network coordinates
const cx = positions.reduce((s, p) => s + p.x, 0) / positions.length;
const cy = positions.reduce((s, p) => s + p.y, 0) / positions.length;
const expanded = positions.map(p => ({{
x: cx + (p.x - cx) * 1.15,
y: cy + (p.y - cy) * 1.15
}}));
ctx.moveTo(expanded[0].x, expanded[0].y);
expanded.slice(1).forEach(p => ctx.lineTo(p.x, p.y));
ctx.closePath();
ctx.fill();
ctx.globalAlpha = 0.4;
ctx.stroke();
// Label
ctx.globalAlpha = 0.8;
ctx.fillStyle = '#4f46e5';
ctx.font = 'bold 11px sans-serif';
ctx.textAlign = 'center';
ctx.fillText(h.label, cx, cy - 5);
ctx.restore();
}});
}});
</script>"""
def _html_script(nodes_json: str, edges_json: str, legend_json: str) -> str:
return f"""<script>
const RAW_NODES = {nodes_json};
const RAW_EDGES = {edges_json};
const LEGEND = {legend_json};
// HTML-escape helper — prevents XSS when injecting graph data into innerHTML
function esc(s) {{
return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}}
// Build vis datasets
const nodesDS = new vis.DataSet(RAW_NODES.map(n => ({{
id: n.id, label: n.label, color: n.color, size: n.size,
font: n.font, title: n.title,
_community: n.community, _community_name: n.community_name,
_source_file: n.source_file, _file_type: n.file_type, _degree: n.degree,
}})));
const edgesDS = new vis.DataSet(RAW_EDGES.map((e, i) => ({{
id: i, from: e.from, to: e.to,
label: '',
title: e.title,
dashes: e.dashes,
width: e.width,
color: e.color,
arrows: {{ to: {{ enabled: true, scaleFactor: 0.5 }} }},
}})));
const container = document.getElementById('graph');
const network = new vis.Network(container, {{ nodes: nodesDS, edges: edgesDS }}, {{
physics: {{
enabled: true,
solver: 'forceAtlas2Based',
forceAtlas2Based: {{
gravitationalConstant: -60,
centralGravity: 0.005,
springLength: 120,
springConstant: 0.08,
damping: 0.4,
avoidOverlap: 0.8,
}},
stabilization: {{ iterations: 200, fit: true }},
}},
interaction: {{
hover: true,
tooltipDelay: 100,
hideEdgesOnDrag: true,
navigationButtons: false,
keyboard: false,
}},
nodes: {{ shape: 'dot', borderWidth: 1.5 }},
edges: {{ smooth: {{ type: 'continuous', roundness: 0.2 }}, selectionWidth: 3 }},
}});
network.once('stabilizationIterationsDone', () => {{
network.setOptions({{ physics: {{ enabled: false }} }});
}});
function showInfo(nodeId) {{
const n = nodesDS.get(nodeId);
if (!n) return;
const neighborIds = network.getConnectedNodes(nodeId);
const neighborItems = neighborIds.map(nid => {{
const nb = nodesDS.get(nid);
const color = nb ? nb.color.background : '#555';
return `<span class="neighbor-link" style="border-left-color:${{esc(color)}}" onclick="focusNode(${{JSON.stringify(nid)}})">${{esc(nb ? nb.label : nid)}}</span>`;
}}).join('');
document.getElementById('info-content').innerHTML = `
<div class="field"><b>${{esc(n.label)}}</b></div>
<div class="field">Type: ${{esc(n._file_type || 'unknown')}}</div>
<div class="field">Community: ${{esc(n._community_name)}}</div>
<div class="field">Source: ${{esc(n._source_file || '-')}}</div>
<div class="field">Degree: ${{n._degree}}</div>
${{neighborIds.length ? `<div class="field" style="margin-top:8px;color:#aaa;font-size:11px">Neighbors (${{neighborIds.length}})</div><div id="neighbors-list">${{neighborItems}}</div>` : ''}}
`;
}}
function focusNode(nodeId) {{
network.focus(nodeId, {{ scale: 1.4, animation: true }});
network.selectNodes([nodeId]);
showInfo(nodeId);
}}
// Track hovered node — hover detection is more reliable than click params
let hoveredNodeId = null;
network.on('hoverNode', params => {{
hoveredNodeId = params.node;
container.style.cursor = 'pointer';
}});
network.on('blurNode', () => {{
hoveredNodeId = null;
container.style.cursor = 'default';
}});
container.addEventListener('click', () => {{
if (hoveredNodeId !== null) {{
showInfo(hoveredNodeId);
network.selectNodes([hoveredNodeId]);
}}
}});
network.on('click', params => {{
if (params.nodes.length > 0) {{
showInfo(params.nodes[0]);
}} else if (hoveredNodeId === null) {{
document.getElementById('info-content').innerHTML = '<span class="empty">Click a node to inspect it</span>';
}}
}});
const searchInput = document.getElementById('search');
const searchResults = document.getElementById('search-results');
searchInput.addEventListener('input', () => {{
const q = searchInput.value.toLowerCase().trim();
searchResults.innerHTML = '';
if (!q) {{ searchResults.style.display = 'none'; return; }}
const matches = RAW_NODES.filter(n => n.label.toLowerCase().includes(q)).slice(0, 20);
if (!matches.length) {{ searchResults.style.display = 'none'; return; }}
searchResults.style.display = 'block';
matches.forEach(n => {{
const el = document.createElement('div');
el.className = 'search-item';
el.textContent = n.label;
el.style.borderLeft = `3px solid ${{n.color.background}}`;
el.style.paddingLeft = '8px';
el.onclick = () => {{
network.focus(n.id, {{ scale: 1.5, animation: true }});
network.selectNodes([n.id]);
showInfo(n.id);
searchResults.style.display = 'none';
searchInput.value = '';
}};
searchResults.appendChild(el);
}});
}});
document.addEventListener('click', e => {{
if (!searchResults.contains(e.target) && e.target !== searchInput)
searchResults.style.display = 'none';
}});
const hiddenCommunities = new Set();
const legendEl = document.getElementById('legend');
LEGEND.forEach(c => {{
const item = document.createElement('div');
item.className = 'legend-item';
item.innerHTML = `<div class="legend-dot" style="background:${{c.color}}"></div>
<span class="legend-label">${{c.label}}</span>
<span class="legend-count">${{c.count}}</span>`;
item.onclick = () => {{
if (hiddenCommunities.has(c.cid)) {{
hiddenCommunities.delete(c.cid);
item.classList.remove('dimmed');
}} else {{
hiddenCommunities.add(c.cid);
item.classList.add('dimmed');
}}
const updates = RAW_NODES
.filter(n => n.community === c.cid)
.map(n => ({{ id: n.id, hidden: hiddenCommunities.has(c.cid) }}));
nodesDS.update(updates);
}};
legendEl.appendChild(item);
}});
</script>"""
_CONFIDENCE_SCORE_DEFAULTS = {"EXTRACTED": 1.0, "INFERRED": 0.5, "AMBIGUOUS": 0.2}
def attach_hyperedges(G: nx.Graph, hyperedges: list) -> None:
"""Store hyperedges in the graph's metadata dict."""
existing = G.graph.get("hyperedges", [])
seen_ids = {h["id"] for h in existing}
for h in hyperedges:
if h.get("id") and h["id"] not in seen_ids:
existing.append(h)
seen_ids.add(h["id"])
G.graph["hyperedges"] = existing
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) -> None:
node_community = {n: cid for cid, nodes in communities.items() for n in nodes}
data = json_graph.node_link_data(G, edges="links")
node_community = _node_community_map(communities)
try:
data = json_graph.node_link_data(G, edges="links")
except TypeError:
data = json_graph.node_link_data(G)
for node in data["nodes"]:
node["community"] = node_community.get(node["id"])
with open(output_path, "w") as f:
node["norm_label"] = _strip_diacritics(node.get("label", "")).lower()
for link in data["links"]:
if "confidence_score" not in link:
conf = link.get("confidence", "EXTRACTED")
link["confidence_score"] = _CONFIDENCE_SCORE_DEFAULTS.get(conf, 1.0)
data["hyperedges"] = getattr(G, "graph", {}).get("hyperedges", [])
with open(output_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
def prune_dangling_edges(graph_data: dict) -> tuple[dict, int]:
"""Remove edges whose source or target node is not in the node set.
Returns the cleaned graph_data dict and the number of pruned edges.
"""
node_ids = {n["id"] for n in graph_data["nodes"]}
links_key = "links" if "links" in graph_data else "edges"
before = len(graph_data[links_key])
graph_data[links_key] = [
e for e in graph_data[links_key]
if e["source"] in node_ids and e["target"] in node_ids
]
return graph_data, before - len(graph_data[links_key])
def _cypher_escape(s: str) -> str:
"""Escape a string for safe embedding in a Cypher single-quoted literal."""
return s.replace("\\", "\\\\").replace("'", "\\'")
def to_cypher(G: nx.Graph, output_path: str) -> None:
lines = ["// Neo4j Cypher import — generated by /graphify", ""]
lines = ["// Neo4j Cypher import - generated by /graphify", ""]
for node_id, data in G.nodes(data=True):
label = data.get("label", node_id).replace("'", "\\'")
ftype = data.get("file_type", "unknown").capitalize()
lines.append(f"MERGE (n:{ftype} {{id: '{node_id}', label: '{label}'}});")
label = _cypher_escape(data.get("label", node_id))
node_id_esc = _cypher_escape(node_id)
_ft = re.sub(r"[^A-Za-z0-9_]", "", data.get("file_type", "unknown").capitalize())
ftype = (_ft if _ft and _ft[0].isalpha() else "Entity")
lines.append(f"MERGE (n:{ftype} {{id: '{node_id_esc}', label: '{label}'}});")
lines.append("")
for u, v, data in G.edges(data=True):
rel = data.get("relation", "RELATES_TO").upper().replace(" ", "_").replace("-", "_")
conf = data.get("confidence", "EXTRACTED")
rel = re.sub(r"[^A-Za-z0-9_]", "_", data.get("relation", "RELATES_TO").upper())
conf = _cypher_escape(data.get("confidence", "EXTRACTED"))
u_esc = _cypher_escape(u)
v_esc = _cypher_escape(v)
lines.append(
f"MATCH (a {{id: '{u}'}}), (b {{id: '{v}'}}) "
f"MATCH (a {{id: '{u_esc}'}}), (b {{id: '{v_esc}'}}) "
f"MERGE (a)-[:{rel} {{confidence: '{conf}'}}]->(b);"
)
with open(output_path, "w") as f:
with open(output_path, "w", encoding="utf-8") as f:
f.write("\n".join(lines))
@@ -50,76 +345,115 @@ def to_html(
output_path: str,
community_labels: dict[int, str] | None = None,
) -> None:
"""Generate an interactive pyvis HTML visualization of the graph.
"""Generate an interactive vis.js HTML visualization of the graph.
Merged from visualizer.py. Raises ValueError if graph exceeds MAX_NODES_FOR_VIZ.
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.
"""
from pyvis.network import Network
if G.number_of_nodes() > MAX_NODES_FOR_VIZ:
raise ValueError(
f"Graph has {G.number_of_nodes()} nodes — too large for pyvis. "
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz. "
f"Use --no-viz or reduce input size."
)
node_community = {n: cid for cid, nodes in communities.items() for n in nodes}
net = Network(height="800px", width="100%", bgcolor="#1a1a2e", font_color="white")
net.barnes_hut()
node_community = _node_community_map(communities)
degree = dict(G.degree())
max_deg = max(degree.values(), default=1) or 1
# Build nodes list for vis.js
vis_nodes = []
for node_id, data in G.nodes(data=True):
cid = node_community.get(node_id, 0)
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
net.add_node(
node_id,
label=sanitize_label(data.get("label", node_id)),
color=color,
title=sanitize_label(
f"Source: {data.get('source_file', 'unknown')}\n"
f"Type: {data.get('file_type', 'unknown')}\n"
f"Community: {community_labels.get(cid, str(cid)) if community_labels else cid}"
),
)
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
vis_nodes.append({
"id": node_id,
"label": label,
"color": {"background": color, "border": color, "highlight": {"background": "#ffffff", "border": color}},
"size": round(size, 1),
"font": {"size": font_size, "color": "#ffffff"},
"title": _html.escape(label),
"community": cid,
"community_name": sanitize_label((community_labels or {}).get(cid, f"Community {cid}")),
"source_file": sanitize_label(data.get("source_file", "")),
"file_type": data.get("file_type", ""),
"degree": deg,
})
# Build edges list
vis_edges = []
for u, v, data in G.edges(data=True):
confidence = data.get("confidence", "EXTRACTED")
width = {"EXTRACTED": 2, "INFERRED": 1, "AMBIGUOUS": 1}.get(confidence, 1)
net.add_edge(
u, v,
title=f"{data.get('relation', '')} [{confidence}]",
width=width,
dashes=(confidence != "EXTRACTED"),
)
relation = data.get("relation", "")
vis_edges.append({
"from": u,
"to": v,
"label": relation,
"title": _html.escape(f"{relation} [{confidence}]"),
"dashes": confidence != "EXTRACTED",
"width": 2 if confidence == "EXTRACTED" else 1,
"color": {"opacity": 0.7 if confidence == "EXTRACTED" else 0.35},
"confidence": confidence,
})
net.save_graph(output_path)
# Build community legend data
legend_data = []
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, []))
legend_data.append({"cid": cid, "color": color, "label": lbl, "count": n})
# Inject community legend into saved HTML
if community_labels:
legend_items = ""
for cid in sorted(community_labels.keys()):
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
label = community_labels[cid]
n_nodes = len(communities.get(cid, []))
legend_items += (
f'<div style="margin:4px 0">'
f'<span style="color:{color};font-size:18px">■</span> '
f'<span style="font-size:13px">{label} ({n_nodes})</span>'
f'</div>'
)
legend_html = (
'<div style="position:fixed;top:10px;right:10px;background:#2a2a4e;'
'padding:12px 16px;border-radius:8px;font-family:sans-serif;color:white;'
'z-index:9999;min-width:180px;">'
'<b style="font-size:14px">Communities</b><br>'
+ legend_items +
'</div>'
)
content = Path(output_path).read_text()
content = content.replace("</body>", legend_html + "\n</body>")
Path(output_path).write_text(content)
# Escape </script> sequences so embedded JSON cannot break out of the script tag
def _js_safe(obj) -> str:
return json.dumps(obj).replace("</", "<\\/")
nodes_json = _js_safe(vis_nodes)
edges_json = _js_safe(vis_edges)
legend_json = _js_safe(legend_data)
hyperedges_json = _js_safe(getattr(G, "graph", {}).get("hyperedges", []))
title = _html.escape(sanitize_label(str(output_path)))
stats = f"{G.number_of_nodes()} nodes &middot; {G.number_of_edges()} edges &middot; {len(communities)} communities"
html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>graphify - {title}</title>
<script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>
{_html_styles()}
</head>
<body>
<div id="graph"></div>
<div id="sidebar">
<div id="search-wrap">
<input id="search" type="text" placeholder="Search nodes..." autocomplete="off">
<div id="search-results"></div>
</div>
<div id="info-panel">
<h3>Node Info</h3>
<div id="info-content"><span class="empty">Click a node to inspect it</span></div>
</div>
<div id="legend-wrap">
<h3>Communities</h3>
<div id="legend"></div>
</div>
<div id="stats">{stats}</div>
</div>
{_html_script(nodes_json, edges_json, legend_json)}
{_hyperedge_script(hyperedges_json)}
</body>
</html>"""
Path(output_path).write_text(html, encoding="utf-8")
# Keep backward-compatible alias — skill.md calls generate_html
# Keep backward-compatible alias - skill.md calls generate_html
generate_html = to_html
@@ -130,7 +464,7 @@ def to_obsidian(
community_labels: dict[int, str] | None = None,
cohesion: dict[int, float] | None = None,
) -> int:
"""Export graph as an Obsidian vault — one .md file per node with [[wikilinks]],
"""Export graph as an Obsidian vault - one .md file per node with [[wikilinks]],
plus one _COMMUNITY_name.md overview note per community (sorted to top by underscore prefix).
Open the output directory as a vault in Obsidian to get an interactive
@@ -141,12 +475,15 @@ def to_obsidian(
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
node_community = {n: cid for cid, nodes in communities.items() for n in nodes}
node_community = _node_community_map(communities)
# Map node_id → safe filename so wikilinks stay consistent.
# Deduplicate: if two nodes produce the same filename, append a numeric suffix.
def safe_name(label: str) -> str:
return re.sub(r'[\\/*?:"<>|#^[\]]', "", label).strip() or "unnamed"
cleaned = re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip()
# Strip trailing .md/.mdx/.markdown so "CLAUDE.md" doesn't become "CLAUDE.md.md"
cleaned = re.sub(r"\.(md|mdx|markdown)$", "", cleaned, flags=re.IGNORECASE)
return cleaned or "unnamed"
node_filename: dict[str, str] = {}
seen_names: dict[str, int] = {}
@@ -196,7 +533,7 @@ def to_obsidian(
lines: list[str] = []
# YAML frontmatter — readable in Obsidian's properties panel
# YAML frontmatter - readable in Obsidian's properties panel
lines += [
"---",
f'source_file: "{data.get("source_file", "")}"',
@@ -220,7 +557,7 @@ def to_obsidian(
neighbor_label = node_filename[neighbor]
relation = edge_data.get("relation", "")
confidence = edge_data.get("confidence", "EXTRACTED")
lines.append(f"- [[{neighbor_label}]] — `{relation}` [{confidence}]")
lines.append(f"- [[{neighbor_label}]] - `{relation}` [{confidence}]")
lines.append("")
# Inline tags at bottom of note body (for Obsidian tag panel)
@@ -283,7 +620,7 @@ def to_obsidian(
else "moderately connected" if coh_value >= 0.4
else "loosely connected"
)
lines.append(f"**Cohesion:** {coh_value:.2f} — {cohesion_desc}")
lines.append(f"**Cohesion:** {coh_value:.2f} - {cohesion_desc}")
lines.append(f"**Members:** {n_members} nodes")
lines.append("")
@@ -296,9 +633,9 @@ def to_obsidian(
source = data.get("source_file", "")
entry = f"- [[{node_label}]]"
if ftype:
entry += f" — {ftype}"
entry += f" - {ftype}"
if source:
entry += f" — {source}"
entry += f" - {source}"
lines.append(entry)
lines.append("")
@@ -326,7 +663,7 @@ def to_obsidian(
lines.append(f"- {edge_count} edge{'s' if edge_count != 1 else ''} to [[_COMMUNITY_{other_safe}]]")
lines.append("")
# Top bridge nodes — highest degree nodes that connect to other communities
# Top bridge nodes - highest degree nodes that connect to other communities
bridge_nodes = [
(node_id, G.degree(node_id), _community_reach(node_id))
for node_id in members
@@ -339,7 +676,7 @@ def to_obsidian(
for node_id, degree, reach in top_bridges:
node_label = node_filename[node_id]
lines.append(
f"- [[{node_label}]] — degree {degree}, connects to {reach} "
f"- [[{node_label}]] - degree {degree}, connects to {reach} "
f"{'community' if reach == 1 else 'communities'}"
)
@@ -360,7 +697,7 @@ def to_obsidian(
for cid, label in sorted((community_labels or {}).items())
]
}
(obsidian_dir / "graph.json").write_text(json.dumps(graph_config, indent=2))
(obsidian_dir / "graph.json").write_text(json.dumps(graph_config, indent=2), encoding="utf-8")
return G.number_of_nodes() + community_notes_written
@@ -372,7 +709,7 @@ def to_canvas(
community_labels: dict[int, str] | None = None,
node_filenames: dict[str, str] | None = None,
) -> None:
"""Export graph as an Obsidian Canvas file — communities as groups, nodes as cards.
"""Export graph as an Obsidian Canvas file - communities as groups, nodes as cards.
Generates a structured layout: communities arranged in a grid, nodes within
each community arranged in rows. Edges shown between connected nodes.
@@ -382,7 +719,9 @@ def to_canvas(
CANVAS_COLORS = ["1", "2", "3", "4", "5", "6"] # red, orange, yellow, green, cyan, purple
def safe_name(label: str) -> str:
return re.sub(r'[\\/*?:"<>|#^[\]]', "", label).strip() or "unnamed"
cleaned = re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip()
cleaned = re.sub(r"\.(md|mdx|markdown)$", "", cleaned, flags=re.IGNORECASE)
return cleaned or "unnamed"
# Build node_filenames if not provided (same dedup logic as to_obsidian)
if node_filenames is None:
@@ -481,7 +820,7 @@ def to_canvas(
"color": canvas_color,
})
# Node cards inside the group — rows of 3
# Node cards inside the group - rows of 3
sorted_members = sorted(members, key=lambda n: G.nodes[n].get("label", n))
for m_idx, node_id in enumerate(sorted_members):
col = m_idx % 3
@@ -499,7 +838,7 @@ def to_canvas(
"height": 60,
})
# Generate edges — only between nodes both in canvas, cap at 200 highest-weight
# Generate edges - only between nodes both in canvas, cap at 200 highest-weight
all_edges_weighted: list[tuple[float, str, str, str]] = []
for u, v, edata in G.edges(data=True):
if u in all_canvas_nodes and v in all_canvas_nodes:
@@ -533,7 +872,7 @@ def push_to_neo4j(
Requires: pip install neo4j
Uses MERGE so re-running is safe — nodes and edges are upserted, not duplicated.
Uses MERGE so re-running is safe - nodes and edges are upserted, not duplicated.
Returns a dict with counts of nodes and edges pushed.
"""
try:
@@ -543,14 +882,16 @@ def push_to_neo4j(
"neo4j driver not installed. Run: pip install neo4j"
) from e
node_community = (
{n: cid for cid, nodes in communities.items() for n in nodes}
if communities else {}
)
node_community = _node_community_map(communities) if communities else {}
def _safe_rel(relation: str) -> str:
return re.sub(r"[^A-Z0-9_]", "_", relation.upper().replace(" ", "_").replace("-", "_")) or "RELATED_TO"
def _safe_label(label: str) -> str:
"""Sanitize a Neo4j node label to prevent Cypher injection."""
sanitized = re.sub(r"[^A-Za-z0-9_]", "", label)
return sanitized if sanitized else "Entity"
driver = GraphDatabase.driver(uri, auth=(user, password))
nodes_pushed = 0
edges_pushed = 0
@@ -562,7 +903,7 @@ def push_to_neo4j(
cid = node_community.get(node_id)
if cid is not None:
props["community"] = cid
ftype = data.get("file_type", "Entity").capitalize()
ftype = _safe_label(data.get("file_type", "Entity").capitalize())
session.run(
f"MERGE (n:{ftype} {{id: $id}}) SET n += $props",
id=node_id,
@@ -586,6 +927,23 @@ def push_to_neo4j(
return {"nodes": nodes_pushed, "edges": edges_pushed}
def to_graphml(
G: nx.Graph,
communities: dict[int, list[str]],
output_path: str,
) -> None:
"""Export graph as GraphML - opens in Gephi, yEd, and any GraphML-compatible tool.
Community IDs are written as a node attribute so Gephi can colour by community.
Edge confidence (EXTRACTED/INFERRED/AMBIGUOUS) is preserved as an edge attribute.
"""
H = G.copy()
node_community = _node_community_map(communities)
for node_id in H.nodes():
H.nodes[node_id]["community"] = node_community.get(node_id, -1)
nx.write_graphml(H, output_path)
def to_svg(
G: nx.Graph,
communities: dict[int, list[str]],
@@ -595,10 +953,10 @@ def to_svg(
) -> None:
"""Export graph as an SVG file using matplotlib + spring layout.
Lightweight and embeddable — works in Obsidian notes, Notion, GitHub READMEs,
Lightweight and embeddable - works in Obsidian notes, Notion, GitHub READMEs,
and any markdown renderer. No JavaScript required.
Node size scales with degree. Community colors match the pyvis HTML output.
Node size scales with degree. Community colors match the HTML output.
"""
try:
import matplotlib
@@ -608,7 +966,7 @@ def to_svg(
except ImportError as e:
raise ImportError("matplotlib not installed. Run: pip install matplotlib") from e
node_community = {n: cid for cid, nodes in communities.items() for n in nodes}
node_community = _node_community_map(communities)
fig, ax = plt.subplots(figsize=figsize, facecolor="#1a1a2e")
ax.set_facecolor("#1a1a2e")
@@ -617,12 +975,12 @@ def to_svg(
pos = nx.spring_layout(G, seed=42, k=2.0 / (G.number_of_nodes() ** 0.5 + 1))
degree = dict(G.degree())
max_deg = max(degree.values()) if degree else 1
max_deg = max(degree.values(), default=1) or 1
node_colors = [COMMUNITY_COLORS[node_community.get(n, 0) % len(COMMUNITY_COLORS)] for n in G.nodes()]
node_sizes = [300 + 1200 * (degree.get(n, 1) / max_deg) for n in G.nodes()]
# Draw edges — dashed for non-EXTRACTED
# Draw edges - dashed for non-EXTRACTED
for u, v, data in G.edges(data=True):
conf = data.get("confidence", "EXTRACTED")
style = "solid" if conf == "EXTRACTED" else "dashed"
+2473 -1677
View File
File diff suppressed because it is too large. Load diff
+198
View File
@@ -0,0 +1,198 @@
# git hook integration - install/uninstall graphify post-commit and post-checkout hooks
from __future__ import annotations
import re
from pathlib import Path
_HOOK_MARKER = "# graphify-hook-start"
_HOOK_MARKER_END = "# graphify-hook-end"
_CHECKOUT_MARKER = "# graphify-checkout-hook-start"
_CHECKOUT_MARKER_END = "# graphify-checkout-hook-end"
_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 "$_SHEBANG" in
*/env\\ *) GRAPHIFY_PYTHON="${_SHEBANG#*/env }" ;;
*) GRAPHIFY_PYTHON="$_SHEBANG" ;;
esac
# Allowlist: only keep characters valid in a filesystem path to prevent
# injection if the shebang contains shell metacharacters
case "$GRAPHIFY_PYTHON" in
*[!a-zA-Z0-9/_.-]*) GRAPHIFY_PYTHON="" ;;
esac
if [ -n "$GRAPHIFY_PYTHON" ] && ! "$GRAPHIFY_PYTHON" -c "import graphify" 2>/dev/null; then
GRAPHIFY_PYTHON=""
fi
fi
# Fall back: try python3, then python (Windows has no python3 shim)
if [ -z "$GRAPHIFY_PYTHON" ]; then
if command -v python3 >/dev/null 2>&1 && python3 -c "import graphify" 2>/dev/null; then
GRAPHIFY_PYTHON="python3"
elif command -v python >/dev/null 2>&1 && python -c "import graphify" 2>/dev/null; then
GRAPHIFY_PYTHON="python"
else
exit 0
fi
fi
"""
_HOOK_SCRIPT = """\
# graphify-hook-start
# Auto-rebuilds the knowledge graph after each commit (code files only, no LLM needed).
# Installed by: graphify hook install
CHANGED=$(git diff --name-only HEAD~1 HEAD 2>/dev/null || git diff --name-only HEAD 2>/dev/null)
if [ -z "$CHANGED" ]; then
exit 0
fi
""" + _PYTHON_DETECT + """
export GRAPHIFY_CHANGED="$CHANGED"
$GRAPHIFY_PYTHON -c "
import os, sys
from pathlib import Path
changed_raw = os.environ.get('GRAPHIFY_CHANGED', '')
changed = [Path(f.strip()) for f in changed_raw.strip().splitlines() if f.strip()]
if not changed:
sys.exit(0)
print(f'[graphify hook] {len(changed)} file(s) changed - rebuilding graph...')
try:
from graphify.watch import _rebuild_code
_rebuild_code(Path('.'))
except Exception as exc:
print(f'[graphify hook] Rebuild failed: {exc}')
sys.exit(1)
"
# graphify-hook-end
"""
_CHECKOUT_SCRIPT = """\
# graphify-checkout-hook-start
# Auto-rebuilds the knowledge graph (code only) when switching branches.
# Installed by: graphify hook install
PREV_HEAD=$1
NEW_HEAD=$2
BRANCH_SWITCH=$3
# Only run on branch switches, not file checkouts
if [ "$BRANCH_SWITCH" != "1" ]; then
exit 0
fi
# Only run if graphify-out/ exists (graph has been built before)
if [ ! -d "graphify-out" ]; then
exit 0
fi
""" + _PYTHON_DETECT + """
echo "[graphify] Branch switched - rebuilding knowledge graph (code files)..."
$GRAPHIFY_PYTHON -c "
from graphify.watch import _rebuild_code
from pathlib import Path
import sys
try:
_rebuild_code(Path('.'))
except Exception as exc:
print(f'[graphify] Rebuild failed: {exc}')
sys.exit(1)
"
# graphify-checkout-hook-end
"""
def _git_root(path: Path) -> Path | None:
"""Walk up to find .git directory."""
current = path.resolve()
for parent in [current, *current.parents]:
if (parent / ".git").exists():
return parent
return None
def _install_hook(hooks_dir: Path, name: str, script: str, marker: str) -> str:
"""Install a single git hook, appending if an existing hook is present."""
hook_path = hooks_dir / name
if hook_path.exists():
content = hook_path.read_text(encoding="utf-8")
if marker in content:
return f"already installed at {hook_path}"
hook_path.write_text(content.rstrip() + "\n\n" + script, encoding="utf-8", newline="\n")
return f"appended to existing {name} hook at {hook_path}"
hook_path.write_text("#!/bin/sh\n" + script, encoding="utf-8", newline="\n")
hook_path.chmod(0o755)
return f"installed at {hook_path}"
def _uninstall_hook(hooks_dir: Path, name: str, marker: str, marker_end: str) -> str:
"""Remove graphify section from a git hook using start/end markers."""
hook_path = hooks_dir / name
if not hook_path.exists():
return f"no {name} hook found - nothing to remove."
content = hook_path.read_text(encoding="utf-8")
if marker not in content:
return f"graphify hook not found in {name} - nothing to remove."
new_content = re.sub(
rf"{re.escape(marker)}.*?{re.escape(marker_end)}\n?",
"",
content,
flags=re.DOTALL,
).strip()
if not new_content or new_content in ("#!/bin/bash", "#!/bin/sh"):
hook_path.unlink()
return f"removed {name} hook at {hook_path}"
hook_path.write_text(new_content + "\n", encoding="utf-8", newline="\n")
return f"graphify removed from {name} at {hook_path} (other hook content preserved)"
def install(path: Path = Path(".")) -> str:
"""Install graphify post-commit and post-checkout hooks in the nearest git repo."""
root = _git_root(path)
if root is None:
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
hooks_dir = root / ".git" / "hooks"
hooks_dir.mkdir(exist_ok=True)
commit_msg = _install_hook(hooks_dir, "post-commit", _HOOK_SCRIPT, _HOOK_MARKER)
checkout_msg = _install_hook(hooks_dir, "post-checkout", _CHECKOUT_SCRIPT, _CHECKOUT_MARKER)
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
def uninstall(path: Path = Path(".")) -> str:
"""Remove graphify post-commit and post-checkout hooks."""
root = _git_root(path)
if root is None:
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
hooks_dir = root / ".git" / "hooks"
commit_msg = _uninstall_hook(hooks_dir, "post-commit", _HOOK_MARKER, _HOOK_MARKER_END)
checkout_msg = _uninstall_hook(hooks_dir, "post-checkout", _CHECKOUT_MARKER, _CHECKOUT_MARKER_END)
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
def status(path: Path = Path(".")) -> str:
"""Check if graphify hooks are installed."""
root = _git_root(path)
if root is None:
return "Not in a git repository."
hooks_dir = root / ".git" / "hooks"
def _check(name: str, marker: str) -> str:
p = hooks_dir / name
if not p.exists():
return "not installed"
return "installed" if marker in p.read_text(encoding="utf-8") else "not installed (hook exists but graphify not found)"
commit = _check("post-commit", _HOOK_MARKER)
checkout = _check("post-checkout", _CHECKOUT_MARKER)
return f"post-commit: {commit}\npost-checkout: {checkout}"
+28 -20
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import json
import re
import sys
import urllib.error
import urllib.parse
from datetime import datetime, timezone
@@ -11,6 +10,11 @@ from pathlib import Path
from graphify.security import safe_fetch, safe_fetch_text, validate_url
def _yaml_str(s: str) -> str:
"""Escape a string for embedding in a YAML double-quoted scalar."""
return s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
def _safe_filename(url: str, suffix: str) -> str:
"""Turn a URL into a safe filename."""
parsed = urllib.parse.urlparse(url)
@@ -68,23 +72,21 @@ def _fetch_tweet(url: str, author: str | None, contributor: str | None) -> tuple
oembed_url = url.replace("x.com", "twitter.com")
oembed_api = f"https://publish.twitter.com/oembed?url={urllib.parse.quote(oembed_url)}&omit_script=true"
try:
req = urllib.request.Request(oembed_api, headers={"User-Agent": "graphify/1.0"})
with urllib.request.urlopen(req, timeout=10) as resp:
data = json.loads(resp.read())
data = json.loads(safe_fetch_text(oembed_api))
tweet_text = re.sub(r"<[^>]+>", "", data.get("html", "")).strip()
tweet_author = data.get("author_name", "unknown")
except Exception:
# oEmbed failed — save URL stub
# oEmbed failed - save URL stub
tweet_text = f"Tweet at {url} (could not fetch content)"
tweet_author = "unknown"
now = datetime.now(timezone.utc).isoformat()
content = f"""---
source_url: {url}
source_url: "{_yaml_str(url)}"
type: tweet
author: {tweet_author}
author: "{_yaml_str(tweet_author)}"
captured_at: {now}
contributor: {contributor or author or 'unknown'}
contributor: "{_yaml_str(contributor or author or 'unknown')}"
---
# Tweet by @{tweet_author}
@@ -107,11 +109,11 @@ def _fetch_webpage(url: str, author: str | None, contributor: str | None) -> tup
markdown = _html_to_markdown(html, url)
now = datetime.now(timezone.utc).isoformat()
content = f"""---
source_url: {url}
source_url: "{_yaml_str(url)}"
type: webpage
title: "{title}"
title: "{_yaml_str(title)}"
captured_at: {now}
contributor: {contributor or author or 'unknown'}
contributor: "{_yaml_str(contributor or author or 'unknown')}"
---
# {title}
@@ -147,13 +149,13 @@ def _fetch_arxiv(url: str, author: str | None, contributor: str | None) -> tuple
now = datetime.now(timezone.utc).isoformat()
content = f"""---
source_url: {url}
arxiv_id: {arxiv_id.group(1) if arxiv_id else ''}
source_url: "{_yaml_str(url)}"
arxiv_id: "{_yaml_str(arxiv_id.group(1) if arxiv_id else '')}"
type: paper
title: "{title}"
paper_authors: "{paper_authors}"
title: "{_yaml_str(title)}"
paper_authors: "{_yaml_str(paper_authors)}"
captured_at: {now}
contributor: {contributor or author or 'unknown'}
contributor: "{_yaml_str(contributor or author or 'unknown')}"
---
# {title}
@@ -205,6 +207,12 @@ def ingest(url: str, target_dir: Path, author: str | None = None, contributor: s
print(f"Downloaded image: {out.name}")
return out
if url_type == "youtube":
from graphify.transcribe import download_audio
out = download_audio(url, target_dir)
print(f"Downloaded audio: {out.name}")
return out
if url_type == "tweet":
content, filename = _fetch_tweet(url, author, contributor)
elif url_type == "arxiv":
@@ -215,9 +223,9 @@ def ingest(url: str, target_dir: Path, author: str | None = None, contributor: s
raise RuntimeError(f"ingest: failed to fetch {url!r}: {exc}") from exc
out_path = target_dir / filename
# Avoid overwriting — append counter if needed
# Avoid overwriting - append counter if needed
counter = 1
while out_path.exists():
while out_path.exists() and counter < 1000:
stem = Path(filename).stem
out_path = target_dir / f"{stem}_{counter}.md"
counter += 1
@@ -236,7 +244,7 @@ def save_query_result(
) -> Path:
"""Save a Q&A result as markdown so it gets extracted into the graph on next --update.
Files are stored in memory_dir (typically .graphify/memory/) with YAML frontmatter
Files are stored in memory_dir (typically graphify-out/memory/) with YAML frontmatter
that graphify's extractor reads as node metadata. This closes the feedback loop:
the system grows smarter from both what you add AND what you ask.
"""
@@ -251,7 +259,7 @@ def save_query_result(
"---",
f'type: "{query_type}"',
f'date: "{now.isoformat()}"',
f'question: "{re.sub(chr(10) + chr(13), " ", question).replace(chr(34), chr(39))}"',
f'question: "{_yaml_str(question)}"',
'contributor: "graphify"',
]
if source_nodes:
+54 -12
View File
@@ -1,9 +1,17 @@
# generate GRAPH_REPORT.md — the human-readable audit trail
# generate GRAPH_REPORT.md - the human-readable audit trail
from __future__ import annotations
import re
from datetime import date
import networkx as nx
def _safe_community_name(label: str) -> str:
"""Mirrors export.safe_name so community hub filenames and report wikilinks always agree."""
cleaned = re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip()
cleaned = re.sub(r"\.(md|mdx|markdown)$", "", cleaned, flags=re.IGNORECASE)
return cleaned or "unnamed"
def generate(
G: nx.Graph,
communities: dict[int, list[str]],
@@ -24,8 +32,12 @@ def generate(
inf_pct = round(confidences.count("INFERRED") / total * 100)
amb_pct = round(confidences.count("AMBIGUOUS") / total * 100)
inf_edges = [(u, v, d) for u, v, d in G.edges(data=True) if d.get("confidence") == "INFERRED"]
inf_scores = [d.get("confidence_score", 0.5) for _, _, d in inf_edges]
inf_avg = round(sum(inf_scores) / len(inf_scores), 2) if inf_scores else None
lines = [
f"# Graph Report — {root} ({today})",
f"# Graph Report - {root} ({today})",
"",
"## Corpus Check",
]
@@ -41,13 +53,26 @@ def generate(
"",
"## Summary",
f"- {G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(communities)} communities detected",
f"- Extraction: {ext_pct}% EXTRACTED · {inf_pct}% INFERRED · {amb_pct}% AMBIGUOUS",
f"- Extraction: {ext_pct}% EXTRACTED · {inf_pct}% INFERRED · {amb_pct}% AMBIGUOUS"
+ (f" · INFERRED: {len(inf_edges)} edges (avg confidence: {inf_avg})" if inf_avg is not None else ""),
f"- Token cost: {token_cost.get('input', 0):,} input · {token_cost.get('output', 0):,} output",
]
# Community hub navigation - links to _COMMUNITY_*.md files in the Obsidian vault.
# Without these, GRAPH_REPORT.md is a dead-end and the vault splits into disconnected components.
if communities:
lines += ["", "## Community Hubs (Navigation)"]
for cid in communities:
label = community_labels.get(cid, f"Community {cid}")
safe = _safe_community_name(label)
lines.append(f"- [[_COMMUNITY_{safe}|{label}]]")
lines += [
"",
"## God Nodes (most connected — your core abstractions)",
"## God Nodes (most connected - your core abstractions)",
]
for i, node in enumerate(god_node_list, 1):
lines.append(f"{i}. `{node['label']}` — {node['edges']} edges")
lines.append(f"{i}. `{node['label']}` - {node['degree']} edges")
lines += ["", "## Surprising Connections (you probably didn't know these)"]
if surprise_list:
@@ -55,32 +80,49 @@ def generate(
relation = s.get("relation", "related_to")
note = s.get("note", "")
files = s.get("source_files", ["", ""])
conf = s.get("confidence", "EXTRACTED")
cscore = s.get("confidence_score")
if conf == "INFERRED" and cscore is not None:
conf_tag = f"INFERRED {cscore:.2f}"
else:
conf_tag = conf
sem_tag = " [semantically similar]" if relation == "semantically_similar_to" else ""
lines += [
f"- `{s['source']}` --{relation}--> `{s['target']}` [{s['confidence']}]",
f"- `{s['source']}` --{relation}--> `{s['target']}` [{conf_tag}]{sem_tag}",
f" {files[0]} → {files[1]}" + (f" _{note}_" if note else ""),
]
else:
lines.append("- None detected — all connections are within the same source files.")
lines.append("- None detected - all connections are within the same source files.")
hyperedges = G.graph.get("hyperedges", [])
if hyperedges:
lines += ["", "## Hyperedges (group relationships)"]
for h in hyperedges:
node_labels = ", ".join(h.get("nodes", []))
conf = h.get("confidence", "INFERRED")
cscore = h.get("confidence_score")
conf_tag = f"{conf} {cscore:.2f}" if cscore is not None else conf
lines.append(f"- **{h.get('label', h.get('id', ''))}** — {node_labels} [{conf_tag}]")
lines += ["", "## Communities"]
from .analyze import _is_file_node as _ifn
for cid, nodes in communities.items():
label = community_labels.get(cid, f"Community {cid}")
score = cohesion_scores.get(cid, 0.0)
# Filter method/function stubs from display — they're structural noise
# Filter method/function stubs from display - they're structural noise
real_nodes = [n for n in nodes if not _ifn(G, n)]
display = [G.nodes[n].get("label", n) for n in real_nodes[:8]]
suffix = f" (+{len(real_nodes)-8} more)" if len(real_nodes) > 8 else ""
lines += [
"",
f"### Community {cid} — \"{label}\"",
f"### Community {cid} - \"{label}\"",
f"Cohesion: {score}",
f"Nodes ({len(real_nodes)}): {', '.join(display)}{suffix}",
]
ambiguous = [(u, v, d) for u, v, d in G.edges(data=True) if d.get("confidence") == "AMBIGUOUS"]
if ambiguous:
lines += ["", "## Ambiguous Edges — Review These"]
lines += ["", "## Ambiguous Edges - Review These"]
for u, v, d in ambiguous:
ul = G.nodes[u].get("label", u)
vl = G.nodes[v].get("label", v)
@@ -107,13 +149,13 @@ def generate(
isolated_labels = [G.nodes[n].get("label", n) for n in isolated[:5]]
suffix = f" (+{len(isolated)-5} more)" if len(isolated) > 5 else ""
lines.append(f"- **{len(isolated)} isolated node(s):** {', '.join(f'`{l}`' for l in isolated_labels)}{suffix}")
lines.append(" These have ≤1 connection — possible missing edges or undocumented components.")
lines.append(" These have ≤1 connection - possible missing edges or undocumented components.")
if thin_communities:
for cid, nodes in thin_communities.items():
label = community_labels.get(cid, f"Community {cid}")
node_labels = [G.nodes[n].get("label", n) for n in nodes]
lines.append(f"- **Thin community `{label}`** ({len(nodes)} nodes): {', '.join(f'`{l}`' for l in node_labels)}")
lines.append(" Too small to be a meaningful cluster — may be noise or needs more connections extracted.")
lines.append(" Too small to be a meaningful cluster - may be noise or needs more connections extracted.")
if amb_pct > 20:
lines.append(f"- **High ambiguity: {amb_pct}% of edges are AMBIGUOUS.** Review the Ambiguous Edges section above.")
+55 -18
View File
@@ -1,4 +1,4 @@
# Security helpers — URL validation, safe fetch, path guards, label sanitisation
# Security helpers - URL validation, safe fetch, path guards, label sanitisation
from __future__ import annotations
import html
@@ -8,27 +8,59 @@ import urllib.parse
import urllib.request
from pathlib import Path
import ipaddress
import socket
_ALLOWED_SCHEMES = {"http", "https"}
_MAX_FETCH_BYTES = 52_428_800 # 50 MB hard cap for binary downloads
_MAX_TEXT_BYTES = 10_485_760 # 10 MB hard cap for HTML / text
# AWS metadata, link-local, and common cloud metadata endpoints
_BLOCKED_HOSTS = {"metadata.google.internal", "metadata.google.com"}
# ---------------------------------------------------------------------------
# URL validation
# ---------------------------------------------------------------------------
def validate_url(url: str) -> str:
"""Raise ValueError if *url* is not http or https.
"""Raise ValueError if *url* is not http or https, or targets a private/internal IP.
Blocks file://, ftp://, data:, and any other scheme that could be used
for SSRF or local file access.
for SSRF or local file access. Also blocks requests to private/reserved
IP ranges (127.x, 10.x, 169.254.x, etc.) and cloud metadata endpoints
to prevent SSRF in cloud environments.
"""
parsed = urllib.parse.urlparse(url)
if parsed.scheme.lower() not in _ALLOWED_SCHEMES:
raise ValueError(
f"Blocked URL scheme '{parsed.scheme}' — only http and https are allowed. "
f"Blocked URL scheme '{parsed.scheme}' - only http and https are allowed. "
f"Got: {url!r}"
)
hostname = parsed.hostname
if hostname:
# Block known cloud metadata hostnames
if hostname.lower() in _BLOCKED_HOSTS:
raise ValueError(
f"Blocked cloud metadata endpoint '{hostname}'. "
f"Got: {url!r}"
)
# Resolve hostname and block private/reserved IP ranges
try:
infos = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM)
for info in infos:
addr = info[4][0]
ip = ipaddress.ip_address(addr)
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local:
raise ValueError(
f"Blocked private/internal IP {addr} (resolved from '{hostname}'). "
f"Got: {url!r}"
)
except socket.gaierror:
pass # DNS failure will surface later during fetch
return url
@@ -63,10 +95,10 @@ def safe_fetch(url: str, max_bytes: int = _MAX_FETCH_BYTES, timeout: int = 30) -
- Network errors propagate as urllib.error.URLError / OSError
Raises:
ValueError — disallowed scheme or redirect target
urllib.error.HTTPError — non-2xx HTTP status
urllib.error.URLError — DNS / connection failure
OSError — size cap exceeded
ValueError - disallowed scheme or redirect target
urllib.error.HTTPError - non-2xx HTTP status
urllib.error.URLError - DNS / connection failure
OSError - size cap exceeded
"""
validate_url(url)
opener = _build_opener()
@@ -112,16 +144,22 @@ def safe_fetch_text(url: str, max_bytes: int = _MAX_TEXT_BYTES, timeout: int = 1
def validate_graph_path(path: str | Path, base: Path | None = None) -> Path:
"""Resolve *path* and verify it stays inside *base*.
*base* defaults to the `.graphify` directory relative to CWD.
*base* defaults to the `graphify-out` directory relative to CWD.
Also requires the base directory to exist, so a caller cannot
trick graphify into reading files before any graph has been built.
Raises:
ValueError — path escapes base, or base does not exist
FileNotFoundError — resolved path does not exist
ValueError - path escapes base, or base does not exist
FileNotFoundError - resolved path does not exist
"""
if base is None:
base = Path(".graphify").resolve()
resolved_hint = Path(path).resolve()
for candidate in [resolved_hint, *resolved_hint.parents]:
if candidate.name == "graphify-out":
base = candidate
break
if base is None:
base = Path("graphify-out").resolve()
base = base.resolve()
if not base.exists():
@@ -136,7 +174,7 @@ def validate_graph_path(path: str | Path, base: Path | None = None) -> Path:
except ValueError:
raise ValueError(
f"Path {path!r} escapes the allowed directory {base}. "
"Only paths inside .graphify/ are permitted."
"Only paths inside graphify-out/ are permitted."
)
if not resolved.exists():
@@ -154,13 +192,12 @@ _MAX_LABEL_LEN = 256
def sanitize_label(text: str) -> str:
"""Strip control characters, cap length, then HTML-escape.
"""Strip control characters and cap length.
Applied to all node labels and edge titles before they are embedded
in pyvis HTML output or returned via the MCP server, preventing both
XSS and broken visualisations from malformed source identifiers.
Safe for embedding in JSON data (inside <script> tags) and plain text.
For direct HTML injection, wrap the result with html.escape().
"""
text = _CONTROL_CHAR_RE.sub("", text)
if len(text) > _MAX_LABEL_LEN:
text = text[:_MAX_LABEL_LEN]
return html.escape(text)
return text
+194 -149
View File
@@ -1,18 +1,26 @@
# MCP stdio server — exposes graph query tools to Claude and other agents
# MCP stdio server - exposes graph query tools to Claude and other agents
from __future__ import annotations
import json
import sys
from pathlib import Path
import networkx as nx
from networkx.readwrite import json_graph
from graphify.security import validate_graph_path, sanitize_label
from graphify.security import sanitize_label
def _load_graph(graph_path: str) -> nx.Graph:
try:
safe = validate_graph_path(graph_path)
data = json.loads(safe.read_text())
return json_graph.node_link_graph(data, edges="links")
resolved = Path(graph_path).resolve()
if resolved.suffix != ".json":
raise ValueError(f"Graph path must be a .json file, got: {graph_path!r}")
if not resolved.exists():
raise FileNotFoundError(f"Graph file not found: {resolved}")
safe = resolved
data = json.loads(safe.read_text(encoding="utf-8"))
try:
return json_graph.node_link_graph(data, edges="links")
except TypeError:
return json_graph.node_link_graph(data)
except (ValueError, FileNotFoundError) as exc:
print(f"error: {exc}", file=sys.stderr)
sys.exit(1)
@@ -31,12 +39,19 @@ def _communities_from_graph(G: nx.Graph) -> dict[int, list[str]]:
return communities
def _strip_diacritics(text: str) -> str:
import unicodedata
nfkd = unicodedata.normalize("NFKD", text)
return "".join(c for c in nfkd if not unicodedata.combining(c))
def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
scored = []
norm_terms = [_strip_diacritics(t).lower() for t in terms]
for nid, data in G.nodes(data=True):
label = data.get("label", "").lower()
source = data.get("source_file", "").lower()
score = sum(1 for t in terms if t in label) + sum(0.5 for t in terms if t in source)
norm_label = data.get("norm_label") or _strip_diacritics(data.get("label") or "").lower()
source = (data.get("source_file") or "").lower()
score = sum(1 for t in norm_terms if t in norm_label) + sum(0.5 for t in norm_terms if t in source)
if score > 0:
scored.append((score, nid))
return sorted(scored, reverse=True)
@@ -75,8 +90,8 @@ def _dfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], lis
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000) -> str:
"""Render subgraph as text, cutting at token_budget (approx 4 chars/token)."""
char_budget = token_budget * 4
"""Render subgraph as text, cutting at token_budget (approx 3 chars/token)."""
char_budget = token_budget * 3
lines = []
for nid in sorted(nodes, key=lambda n: G.degree(n), reverse=True):
d = G.nodes[nid]
@@ -84,7 +99,8 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
lines.append(line)
for u, v in edges:
if u in nodes and v in nodes:
d = G.edges[u, v]
raw = G[u][v]
d = next(iter(raw.values()), {}) if isinstance(G, (nx.MultiGraph, nx.MultiDiGraph)) else raw
line = f"EDGE {sanitize_label(G.nodes[u].get('label', u))} --{d.get('relation', '')} [{d.get('confidence', '')}]--> {sanitize_label(G.nodes[v].get('label', v))}"
lines.append(line)
output = "\n".join(lines)
@@ -93,7 +109,45 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
return output
def serve(graph_path: str = ".graphify/graph.json") -> None:
def _find_node(G: nx.Graph, label: str) -> list[str]:
"""Return node IDs whose label or ID matches the search term (diacritic-insensitive)."""
term = _strip_diacritics(label).lower()
return [nid for nid, d in G.nodes(data=True)
if term in (d.get("norm_label") or _strip_diacritics(d.get("label") or "").lower())
or term == nid.lower()]
def _filter_blank_stdin() -> None:
"""Filter blank lines from stdin before MCP reads it.
Some MCP clients (Claude Desktop, etc.) send blank lines between JSON
messages. The MCP stdio transport tries to parse every line as a
JSONRPCMessage, so a bare newline triggers a Pydantic ValidationError.
This installs an OS-level pipe that relays stdin while dropping blanks.
"""
import os
import threading
r_fd, w_fd = os.pipe()
saved_fd = os.dup(sys.stdin.fileno())
def _relay() -> None:
try:
with open(saved_fd, "rb") as src, open(w_fd, "wb") as dst:
for line in src:
if line.strip():
dst.write(line)
dst.flush()
except Exception:
pass
threading.Thread(target=_relay, daemon=True).start()
os.dup2(r_fd, sys.stdin.fileno())
os.close(r_fd)
sys.stdin = open(0, "r", closefd=False)
def serve(graph_path: str = "graphify-out/graph.json") -> None:
"""Start the MCP server. Requires pip install mcp."""
try:
from mcp.server import Server
@@ -130,9 +184,7 @@ def serve(graph_path: str = ".graphify/graph.json") -> None:
description="Get full details for a specific node by label or ID.",
inputSchema={
"type": "object",
"properties": {
"label": {"type": "string", "description": "Node label or ID to look up"},
},
"properties": {"label": {"type": "string", "description": "Node label or ID to look up"}},
"required": ["label"],
},
),
@@ -150,24 +202,17 @@ def serve(graph_path: str = ".graphify/graph.json") -> None:
),
types.Tool(
name="get_community",
description="Get all nodes in a community by community ID or label.",
description="Get all nodes in a community by community ID.",
inputSchema={
"type": "object",
"properties": {
"community_id": {"type": "integer", "description": "Community ID (0-indexed by size)"},
},
"properties": {"community_id": {"type": "integer", "description": "Community ID (0-indexed by size)"}},
"required": ["community_id"],
},
),
types.Tool(
name="god_nodes",
description="Return the most connected nodes — the core abstractions of the knowledge graph.",
inputSchema={
"type": "object",
"properties": {
"top_n": {"type": "integer", "default": 10},
},
},
description="Return the most connected nodes - the core abstractions of the knowledge graph.",
inputSchema={"type": "object", "properties": {"top_n": {"type": "integer", "default": 10}}},
),
types.Tool(
name="graph_stats",
@@ -189,130 +234,129 @@ def serve(graph_path: str = ".graphify/graph.json") -> None:
),
]
def _tool_query_graph(arguments: dict) -> str:
question = arguments["question"]
mode = arguments.get("mode", "bfs")
depth = min(int(arguments.get("depth", 3)), 6)
budget = int(arguments.get("token_budget", 2000))
terms = [t.lower() for t in question.split() if len(t) > 2]
scored = _score_nodes(G, terms)
start_nodes = [nid for _, nid in scored[:3]]
if not start_nodes:
return "No matching nodes found."
nodes, edges = _dfs(G, start_nodes, depth) if mode == "dfs" else _bfs(G, start_nodes, depth)
header = f"Traversal: {mode.upper()} depth={depth} | Start: {[G.nodes[n].get('label', n) for n in start_nodes]} | {len(nodes)} nodes found\n\n"
return header + _subgraph_to_text(G, nodes, edges, budget)
def _tool_get_node(arguments: dict) -> str:
label = arguments["label"].lower()
matches = [(nid, d) for nid, d in G.nodes(data=True)
if label in (d.get("label") or "").lower() or label == nid.lower()]
if not matches:
return f"No node matching '{label}' found."
nid, d = matches[0]
return "\n".join([
f"Node: {d.get('label', nid)}",
f" ID: {nid}",
f" Source: {d.get('source_file', '')} {d.get('source_location', '')}",
f" Type: {d.get('file_type', '')}",
f" Community: {d.get('community', '')}",
f" Degree: {G.degree(nid)}",
])
def _tool_get_neighbors(arguments: dict) -> str:
label = arguments["label"].lower()
rel_filter = arguments.get("relation_filter", "").lower()
matches = _find_node(G, label)
if not matches:
return f"No node matching '{label}' found."
nid = matches[0]
lines = [f"Neighbors of {G.nodes[nid].get('label', nid)}:"]
for neighbor in G.neighbors(nid):
d = G.edges[nid, neighbor]
rel = d.get("relation", "")
if rel_filter and rel_filter not in rel.lower():
continue
lines.append(f" --> {G.nodes[neighbor].get('label', neighbor)} [{rel}] [{d.get('confidence', '')}]")
return "\n".join(lines)
def _tool_get_community(arguments: dict) -> str:
cid = int(arguments["community_id"])
nodes = communities.get(cid, [])
if not nodes:
return f"Community {cid} not found."
lines = [f"Community {cid} ({len(nodes)} nodes):"]
for n in nodes:
d = G.nodes[n]
lines.append(f" {d.get('label', n)} [{d.get('source_file', '')}]")
return "\n".join(lines)
def _tool_god_nodes(arguments: dict) -> str:
from .analyze import god_nodes as _god_nodes
nodes = _god_nodes(G, top_n=int(arguments.get("top_n", 10)))
lines = ["God nodes (most connected):"]
lines += [f" {i}. {n['label']} - {n['degree']} edges" for i, n in enumerate(nodes, 1)]
return "\n".join(lines)
def _tool_graph_stats(_: dict) -> str:
confs = [d.get("confidence", "EXTRACTED") for _, _, d in G.edges(data=True)]
total = len(confs) or 1
return (
f"Nodes: {G.number_of_nodes()}\n"
f"Edges: {G.number_of_edges()}\n"
f"Communities: {len(communities)}\n"
f"EXTRACTED: {round(confs.count('EXTRACTED')/total*100)}%\n"
f"INFERRED: {round(confs.count('INFERRED')/total*100)}%\n"
f"AMBIGUOUS: {round(confs.count('AMBIGUOUS')/total*100)}%\n"
)
def _tool_shortest_path(arguments: dict) -> str:
src_scored = _score_nodes(G, [t.lower() for t in arguments["source"].split()])
tgt_scored = _score_nodes(G, [t.lower() for t in arguments["target"].split()])
if not src_scored:
return f"No node matching source '{arguments['source']}' found."
if not tgt_scored:
return f"No node matching target '{arguments['target']}' found."
src_nid, tgt_nid = src_scored[0][1], tgt_scored[0][1]
max_hops = int(arguments.get("max_hops", 8))
try:
path_nodes = nx.shortest_path(G, src_nid, tgt_nid)
except (nx.NetworkXNoPath, nx.NodeNotFound):
return f"No path found between '{G.nodes[src_nid].get('label', src_nid)}' and '{G.nodes[tgt_nid].get('label', tgt_nid)}'."
hops = len(path_nodes) - 1
if hops > max_hops:
return f"Path exceeds max_hops={max_hops} ({hops} hops found)."
segments = []
for i in range(len(path_nodes) - 1):
u, v = path_nodes[i], path_nodes[i + 1]
edata = G.edges[u, v]
rel = edata.get("relation", "")
conf = edata.get("confidence", "")
conf_str = f" [{conf}]" if conf else ""
if i == 0:
segments.append(G.nodes[u].get("label", u))
segments.append(f"--{rel}{conf_str}--> {G.nodes[v].get('label', v)}")
return f"Shortest path ({hops} hops):\n " + " ".join(segments)
_handlers = {
"query_graph": _tool_query_graph,
"get_node": _tool_get_node,
"get_neighbors": _tool_get_neighbors,
"get_community": _tool_get_community,
"god_nodes": _tool_god_nodes,
"graph_stats": _tool_graph_stats,
"shortest_path": _tool_shortest_path,
}
@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
if name == "query_graph":
question = arguments["question"]
mode = arguments.get("mode", "bfs")
depth = min(int(arguments.get("depth", 3)), 6)
budget = int(arguments.get("token_budget", 2000))
terms = [t.lower() for t in question.split() if len(t) > 2]
scored = _score_nodes(G, terms)
start_nodes = [nid for _, nid in scored[:3]]
if not start_nodes:
return [types.TextContent(type="text", text="No matching nodes found.")]
if mode == "dfs":
nodes, edges = _dfs(G, start_nodes, depth)
else:
nodes, edges = _bfs(G, start_nodes, depth)
text = f"Traversal: {mode.upper()} depth={depth} | Start: {[G.nodes[n].get('label', n) for n in start_nodes]} | {len(nodes)} nodes found\n\n"
text += _subgraph_to_text(G, nodes, edges, budget)
return [types.TextContent(type="text", text=text)]
elif name == "get_node":
label = arguments["label"].lower()
matches = [(nid, d) for nid, d in G.nodes(data=True)
if label in d.get("label", "").lower() or label == nid.lower()]
if not matches:
return [types.TextContent(type="text", text=f"No node matching '{label}' found.")]
nid, d = matches[0]
lines = [f"Node: {d.get('label', nid)}",
f" ID: {nid}",
f" Source: {d.get('source_file', '')} {d.get('source_location', '')}",
f" Type: {d.get('file_type', '')}",
f" Community: {d.get('community', '')}",
f" Degree: {G.degree(nid)}"]
return [types.TextContent(type="text", text="\n".join(lines))]
elif name == "get_neighbors":
label = arguments["label"].lower()
rel_filter = arguments.get("relation_filter", "").lower()
matches = [nid for nid, d in G.nodes(data=True)
if label in d.get("label", "").lower() or label == nid.lower()]
if not matches:
return [types.TextContent(type="text", text=f"No node matching '{label}' found.")]
nid = matches[0]
lines = [f"Neighbors of {G.nodes[nid].get('label', nid)}:"]
for neighbor in G.neighbors(nid):
d = G.edges[nid, neighbor]
rel = d.get("relation", "")
if rel_filter and rel_filter not in rel.lower():
continue
conf = d.get("confidence", "")
nlabel = G.nodes[neighbor].get("label", neighbor)
lines.append(f" --> {nlabel} [{rel}] [{conf}]")
return [types.TextContent(type="text", text="\n".join(lines))]
elif name == "get_community":
cid = int(arguments["community_id"])
nodes = communities.get(cid, [])
if not nodes:
return [types.TextContent(type="text", text=f"Community {cid} not found.")]
lines = [f"Community {cid} ({len(nodes)} nodes):"]
for n in nodes:
d = G.nodes[n]
lines.append(f" {d.get('label', n)} [{d.get('source_file', '')}]")
return [types.TextContent(type="text", text="\n".join(lines))]
elif name == "god_nodes":
from .analyze import god_nodes as _god_nodes
top_n = int(arguments.get("top_n", 10))
nodes = _god_nodes(G, top_n=top_n)
lines = ["God nodes (most connected):"]
for i, n in enumerate(nodes, 1):
lines.append(f" {i}. {n['label']} — {n['edges']} edges")
return [types.TextContent(type="text", text="\n".join(lines))]
elif name == "graph_stats":
confs = [d.get("confidence", "EXTRACTED") for _, _, d in G.edges(data=True)]
total = len(confs) or 1
text = (
f"Nodes: {G.number_of_nodes()}\n"
f"Edges: {G.number_of_edges()}\n"
f"Communities: {len(communities)}\n"
f"EXTRACTED: {round(confs.count('EXTRACTED')/total*100)}%\n"
f"INFERRED: {round(confs.count('INFERRED')/total*100)}%\n"
f"AMBIGUOUS: {round(confs.count('AMBIGUOUS')/total*100)}%\n"
)
return [types.TextContent(type="text", text=text)]
elif name == "shortest_path":
src_terms = [t.lower() for t in arguments["source"].split()]
tgt_terms = [t.lower() for t in arguments["target"].split()]
max_hops = int(arguments.get("max_hops", 8))
src_scored = _score_nodes(G, src_terms)
tgt_scored = _score_nodes(G, tgt_terms)
if not src_scored:
return [types.TextContent(type="text", text=f"No node matching source '{arguments['source']}' found.")]
if not tgt_scored:
return [types.TextContent(type="text", text=f"No node matching target '{arguments['target']}' found.")]
src_nid = src_scored[0][1]
tgt_nid = tgt_scored[0][1]
try:
path_nodes = nx.shortest_path(G, src_nid, tgt_nid)
except (nx.NetworkXNoPath, nx.NodeNotFound):
src_label = G.nodes[src_nid].get("label", src_nid)
tgt_label = G.nodes[tgt_nid].get("label", tgt_nid)
return [types.TextContent(type="text", text=f"No path found between '{src_label}' and '{tgt_label}'.")]
hops = len(path_nodes) - 1
if hops > max_hops:
return [types.TextContent(type="text", text=f"Path exceeds max_hops={max_hops} ({hops} hops found).")]
segments = []
for i in range(len(path_nodes) - 1):
u, v = path_nodes[i], path_nodes[i + 1]
u_label = G.nodes[u].get("label", u)
v_label = G.nodes[v].get("label", v)
edata = G.edges[u, v]
rel = edata.get("relation", "")
conf = edata.get("confidence", "")
conf_str = f" [{conf}]" if conf else ""
if i == 0:
segments.append(f"{u_label}")
segments.append(f"--{rel}{conf_str}--> {v_label}")
text = f"Shortest path ({hops} hops):\n " + " ".join(segments)
return [types.TextContent(type="text", text=text)]
return [types.TextContent(type="text", text=f"Unknown tool: {name}")]
handler = _handlers.get(name)
if not handler:
return [types.TextContent(type="text", text=f"Unknown tool: {name}")]
try:
return [types.TextContent(type="text", text=handler(arguments))]
except Exception as exc:
return [types.TextContent(type="text", text=f"Error executing {name}: {exc}")]
import asyncio
@@ -320,9 +364,10 @@ def serve(graph_path: str = ".graphify/graph.json") -> None:
async with stdio_server() as streams:
await server.run(streams[0], streams[1], server.create_initialization_options())
_filter_blank_stdin()
asyncio.run(main())
if __name__ == "__main__":
graph_path = sys.argv[1] if len(sys.argv) > 1 else ".graphify/graph.json"
graph_path = sys.argv[1] if len(sys.argv) > 1 else "graphify-out/graph.json"
serve(graph_path)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+253
View File
@@ -0,0 +1,253 @@
---
name: graphify
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
trigger: /graphify
---
# /graphify
Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.
## Usage
```
/graphify # full pipeline on current directory
/graphify <path> # full pipeline on specific path
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --no-viz # skip visualization, just report + JSON
/graphify <path> --wiki # build agent-crawlable wiki
/graphify query "<question>" # BFS traversal - broad context
```
## What You Must Do When Invoked
If no path was given, use `.` (current directory). Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
**All commands use `python -c "..."` syntax — no bash heredocs, no shell redirects, no `&&`/`||`. This runs correctly on Windows PowerShell and macOS/Linux alike.**
### Step 1 - Ensure graphify is installed
```python
python -c "import graphify; import sys; from pathlib import Path; Path('graphify-out').mkdir(exist_ok=True); Path('graphify-out/.graphify_python').write_text(sys.executable)"
```
If the import fails, install first:
```python
python -m pip install graphifyy -q
```
Then re-run the Step 1 command.
### Step 2 - Detect files
```python
python -c "
import json, sys
from graphify.detect import detect
from pathlib import Path
result = detect(Path('INPUT_PATH'))
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, indent=2))
total = result.get('total_files', 0)
words = result.get('total_words', 0)
print(f'Corpus: {total} files, ~{words} words')
for ftype, files in result.get('files', {}).items():
if files:
print(f' {ftype}: {len(files)} files')
"
```
Replace `INPUT_PATH` with the actual path. Present a clean summary — do not dump the raw JSON.
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `total_words` > 2,000,000 OR `total_files` > 200: warn the user and ask which subfolder to run on.
- Otherwise: proceed to Step 3.
### Step 3 - Extract entities and relationships
#### Part A - Structural extraction (AST, free, no API cost)
```python
python -c "
import json
from graphify.extract import collect_files, extract
from pathlib import Path
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
code_files = []
for f in detect.get('files', {}).get('code', []):
p = Path(f)
code_files.extend(collect_files(p) if p.is_dir() else [p])
if code_files:
result = extract(code_files)
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-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
print('No code files - skipping AST extraction')
"
```
#### Part B - Semantic extraction (AI, costs tokens)
Skip if corpus is code-only (no docs, papers, or images).
Check cache first:
```python
python -c "
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
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:
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)} hit, {len(uncached)} need extraction')
"
```
For each chunk of uncached files (20-25 files per chunk), dispatch a subagent with this prompt:
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
Output ONLY valid JSON: {"nodes": [...], "edges": [...], "hyperedges": [...]}
Each node: {"id": "unique_id", "label": "Human Name", "file_type": "code|document|paper|image"}
Each edge: {"source": "id", "target": "id", "relation": "verb_phrase", "confidence": "EXTRACTED|INFERRED|AMBIGUOUS"}
hyperedges: [] unless you find a genuine group relationship
Files:
FILE_LIST
```
Collect all subagent responses and merge them:
```python
python -c "
import json
from pathlib import Path
# Merge: combine AST + cached + all semantic chunk results
all_nodes, all_edges, all_hyperedges = [], [], []
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text())
all_nodes.extend(ast.get('nodes', []))
all_edges.extend(ast.get('edges', []))
cached_path = Path('graphify-out/.graphify_cached.json')
if cached_path.exists():
cached = json.loads(cached_path.read_text())
all_nodes.extend(cached.get('nodes', []))
all_edges.extend(cached.get('edges', []))
all_hyperedges.extend(cached.get('hyperedges', []))
# PASTE each subagent response here as chunk_1, chunk_2, etc.
for chunk_json in []: # replace [] with your chunk results
chunk = json.loads(chunk_json) if isinstance(chunk_json, str) else chunk_json
all_nodes.extend(chunk.get('nodes', []))
all_edges.extend(chunk.get('edges', []))
all_hyperedges.extend(chunk.get('hyperedges', []))
merged = {'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges, 'input_tokens': 0, 'output_tokens': 0}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2))
print(f'Merged: {len(all_nodes)} nodes, {len(all_edges)} edges')
"
```
### Step 4 - Build graph and cluster
```python
python -c "
import json
from graphify.build import build_from_json
from graphify.cluster import cluster
from graphify.analyze import god_nodes, surprising_connections
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
G = build_from_json(extraction)
communities = cluster(G)
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
import networkx as nx
from networkx.readwrite import json_graph
graph_data = json_graph.node_link_data(G)
Path('graphify-out/graph.json').write_text(json.dumps(graph_data, indent=2))
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps({
'communities': {str(k): v for k, v in communities.items()},
'cohesion': {},
'god_nodes': gods,
'surprises': surprises,
}, indent=2))
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
print(f'God nodes: {[g[\"label\"] for g in gods[:5]]}')
"
```
### Step 5 - Generate report and visualization
```python
python -c "
import json
from graphify.build import build_from_json
from graphify.cluster import cluster
from graphify.analyze import god_nodes, surprising_connections
from graphify.report import generate
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())
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
report = generate(G, communities, {}, {}, gods, surprises, extraction)
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
print('GRAPH_REPORT.md written')
"
```
```python
python -c "
import json
from graphify.build import build_from_json
from graphify.cluster import cluster
from graphify.export import to_html
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
G = build_from_json(extraction)
communities = cluster(G)
try:
to_html(G, communities, 'graphify-out/graph.html')
print('graph.html written')
except ValueError as e:
print(f'Visualization skipped: {e}')
"
```
### After completing all steps
Print this summary:
```
graphify complete
graph.json — GraphRAG-ready, queryable by MCP or CLI
graph.html — interactive visualization (open in browser)
GRAPH_REPORT.md — plain-language architecture summary
```
Read `graphify-out/GRAPH_REPORT.md` and share the **God Nodes** and **Surprising Connections** sections directly in the chat — do not ask the user to open the file themselves.
File diff suppressed because it is too large. Load diff
+510 -240
View File
File diff suppressed because it is too large. Load diff
+182
View File
@@ -0,0 +1,182 @@
# Video transcription using faster-whisper
# Converts video/audio files to text transcripts for graph extraction
from __future__ import annotations
import os
from pathlib import Path
VIDEO_EXTENSIONS = {'.mp4', '.mov', '.webm', '.mkv', '.avi', '.m4v', '.mp3', '.wav', '.m4a', '.ogg'}
URL_PREFIXES = ('http://', 'https://', 'www.')
_DEFAULT_MODEL = "base"
_TRANSCRIPTS_DIR = "graphify-out/transcripts"
_FALLBACK_PROMPT = "Use proper punctuation and paragraph breaks."
def _model_name() -> str:
return os.environ.get("GRAPHIFY_WHISPER_MODEL", _DEFAULT_MODEL)
def _get_whisper():
try:
from faster_whisper import WhisperModel
return WhisperModel
except ImportError as exc:
raise ImportError(
"Video transcription requires faster-whisper. "
"Run: pip install 'graphifyy[video]'"
) from exc
def _get_yt_dlp():
try:
import yt_dlp
return yt_dlp
except ImportError as exc:
raise ImportError(
"YouTube/URL download requires yt-dlp. "
"Run: pip install 'graphifyy[video]'"
) from exc
def is_url(path: str) -> bool:
"""Return True if the string looks like a URL rather than a file path."""
return any(path.startswith(p) for p in URL_PREFIXES)
def download_audio(url: str, output_dir: Path) -> Path:
"""Download audio-only stream from a URL using yt-dlp.
Returns the path to the downloaded audio file (.m4a or .opus).
Uses cached file if already downloaded.
"""
yt_dlp = _get_yt_dlp()
output_dir.mkdir(parents=True, exist_ok=True)
# yt-dlp uses %(title)s which can be long/weird — use a stable name based on URL hash
import hashlib
url_hash = hashlib.sha1(url.encode()).hexdigest()[:12]
out_template = str(output_dir / f"yt_{url_hash}.%(ext)s")
# Check for already-downloaded file
for ext in ('.m4a', '.opus', '.mp3', '.ogg', '.wav', '.webm'):
candidate = output_dir / f"yt_{url_hash}{ext}"
if candidate.exists():
print(f" cached audio: {candidate.name}")
return candidate
ydl_opts = {
'format': 'bestaudio[ext=m4a]/bestaudio/best',
'outtmpl': out_template,
'quiet': True,
'no_warnings': True,
'noplaylist': True,
'postprocessors': [], # no ffmpeg needed — use native audio
}
print(f" downloading audio: {url[:80]} ...", flush=True)
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
ext = info.get('ext', 'm4a')
downloaded = output_dir / f"yt_{url_hash}.{ext}"
if not downloaded.exists():
# yt-dlp may have picked a different extension
for p in output_dir.glob(f"yt_{url_hash}.*"):
downloaded = p
break
return downloaded
def build_whisper_prompt(god_nodes: list[dict]) -> str:
"""Build a domain hint for Whisper from god nodes extracted from the corpus.
Formats the top god node labels into a topic string for Whisper.
The coding agent (Claude Code, Codex, etc.) generates the actual one-sentence
domain hint from these labels and passes it via GRAPHIFY_WHISPER_PROMPT or
as initial_prompt — no separate API call needed here.
"""
if not god_nodes:
return _FALLBACK_PROMPT
override = os.environ.get("GRAPHIFY_WHISPER_PROMPT")
if override:
return override
labels = [n.get("label", "") for n in god_nodes[:10] if n.get("label")]
if not labels:
return _FALLBACK_PROMPT
topics = ", ".join(labels[:5])
return f"Technical discussion about {topics}. Use proper punctuation and paragraph breaks."
def transcribe(
video_path: Path | str,
output_dir: Path | None = None,
initial_prompt: str | None = None,
force: bool = False,
) -> Path:
"""Transcribe a video/audio file or URL to a .txt transcript.
If video_path is a URL, audio is downloaded first via yt-dlp.
Returns the path to the saved transcript file.
Uses cached transcript if it exists unless force=True.
initial_prompt: domain hint for Whisper (built from corpus god nodes).
force: re-transcribe even if transcript already exists.
"""
out_dir = Path(output_dir) if output_dir else Path(_TRANSCRIPTS_DIR)
out_dir.mkdir(parents=True, exist_ok=True)
if is_url(str(video_path)):
audio_path = download_audio(str(video_path), out_dir / "downloads")
else:
audio_path = Path(video_path)
transcript_path = out_dir / (audio_path.stem + ".txt")
if transcript_path.exists() and not force:
return transcript_path
WhisperModel = _get_whisper()
model_name = _model_name()
prompt = initial_prompt or _FALLBACK_PROMPT
print(f" transcribing {audio_path.name} (model={model_name}) ...", flush=True)
model = WhisperModel(model_name, device="cpu", compute_type="int8")
segments, info = model.transcribe(
str(audio_path),
beam_size=5,
initial_prompt=prompt,
)
lines = [segment.text.strip() for segment in segments if segment.text.strip()]
transcript = "\n".join(lines)
transcript_path.write_text(transcript, encoding="utf-8")
lang = info.language if hasattr(info, "language") else "unknown"
print(f" transcript saved -> {transcript_path} (lang={lang}, {len(lines)} segments)")
return transcript_path
def transcribe_all(
video_files: list[str],
output_dir: Path | None = None,
initial_prompt: str | None = None,
) -> list[str]:
"""Transcribe a list of video/audio files or URLs, return paths to transcript .txt files.
Already-transcribed files are returned from cache instantly.
initial_prompt is shared across all files — built once from corpus god nodes.
"""
if not video_files:
return []
transcript_paths = []
for vf in video_files:
try:
t = transcribe(vf, output_dir, initial_prompt=initial_prompt)
transcript_paths.append(str(t))
except Exception as exc:
print(f" warning: could not transcribe {vf}: {exc}")
return transcript_paths
+9 -8
View File
@@ -1,7 +1,7 @@
# validate extraction JSON against the graphify schema before graph assembly
from __future__ import annotations
VALID_FILE_TYPES = {"code", "document", "paper", "image"}
VALID_FILE_TYPES = {"code", "document", "paper", "image", "rationale"}
VALID_CONFIDENCES = {"EXTRACTED", "INFERRED", "AMBIGUOUS"}
REQUIRED_NODE_FIELDS = {"id", "label", "file_type", "source_file"}
REQUIRED_EDGE_FIELDS = {"source", "target", "relation", "confidence", "source_file"}
@@ -10,7 +10,7 @@ REQUIRED_EDGE_FIELDS = {"source", "target", "relation", "confidence", "source_fi
def validate_extraction(data: dict) -> list[str]:
"""
Validate an extraction JSON dict against the graphify schema.
Returns a list of error strings — empty list means valid.
Returns a list of error strings - empty list means valid.
"""
if not isinstance(data, dict):
return ["Extraction must be a JSON object"]
@@ -33,17 +33,18 @@ def validate_extraction(data: dict) -> list[str]:
if "file_type" in node and node["file_type"] not in VALID_FILE_TYPES:
errors.append(
f"Node {i} (id={node.get('id', '?')!r}) has invalid file_type "
f"'{node['file_type']}' — must be one of {sorted(VALID_FILE_TYPES)}"
f"'{node['file_type']}' - must be one of {sorted(VALID_FILE_TYPES)}"
)
# Edges
if "edges" not in data:
# Edges - accept "links" (NetworkX <= 3.1) as fallback for "edges"
edge_list = data.get("edges") if "edges" in data else data.get("links")
if edge_list is None:
errors.append("Missing required key 'edges'")
elif not isinstance(data["edges"], list):
elif not isinstance(edge_list, list):
errors.append("'edges' must be a list")
else:
node_ids = {n["id"] for n in data.get("nodes", []) if isinstance(n, dict) and "id" in n}
for i, edge in enumerate(data["edges"]):
for i, edge in enumerate(edge_list):
if not isinstance(edge, dict):
errors.append(f"Edge {i} must be an object")
continue
@@ -53,7 +54,7 @@ def validate_extraction(data: dict) -> list[str]:
if "confidence" in edge and edge["confidence"] not in VALID_CONFIDENCES:
errors.append(
f"Edge {i} has invalid confidence '{edge['confidence']}' "
f"— must be one of {sorted(VALID_CONFIDENCES)}"
f"- must be one of {sorted(VALID_CONFIDENCES)}"
)
if "source" in edge and node_ids and edge["source"] not in node_ids:
errors.append(f"Edge {i} source '{edge['source']}' does not match any node id")
+119 -15
View File
@@ -1,42 +1,134 @@
# monitor a folder and auto-trigger --update when files change
from __future__ import annotations
import json
import sys
import time
from pathlib import Path
_WATCHED_EXTENSIONS = {
".py", ".ts", ".js", ".go", ".rs", ".java", ".cpp", ".c", ".rb", ".swift", ".kt",
".cs", ".scala", ".php", ".cc", ".cxx", ".hpp", ".h", ".kts",
".md", ".txt", ".rst", ".pdf",
".png", ".jpg", ".jpeg", ".webp", ".gif", ".svg",
}
from graphify.detect import CODE_EXTENSIONS, DOC_EXTENSIONS, PAPER_EXTENSIONS, IMAGE_EXTENSIONS
_WATCHED_EXTENSIONS = CODE_EXTENSIONS | DOC_EXTENSIONS | PAPER_EXTENSIONS | IMAGE_EXTENSIONS
_CODE_EXTENSIONS = CODE_EXTENSIONS
def _run_update(watch_path: Path) -> None:
"""Write a flag file and print a notification when files change."""
flag = watch_path / ".graphify" / "needs_update"
def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
"""Re-run AST extraction + build + cluster + report for code files. No LLM needed.
Returns True on success, False on error.
"""
try:
from graphify.extract import extract
from graphify.detect import detect
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
detected = detect(watch_path, follow_symlinks=follow_symlinks)
code_files = [Path(f) for f in detected['files']['code']]
if not code_files:
print("[graphify watch] No code files found - nothing to rebuild.")
return False
result = extract(code_files)
# Preserve semantic nodes/edges from a previous full run.
# AST-only rebuild replaces code nodes; doc/paper/image nodes are kept.
out = watch_path / "graphify-out"
existing_graph = out / "graph.json"
if existing_graph.exists():
try:
existing = json.loads(existing_graph.read_text(encoding="utf-8"))
code_ids = {n["id"] for n in existing.get("nodes", []) if n.get("file_type") == "code"}
sem_nodes = [n for n in existing.get("nodes", []) if n.get("file_type") != "code"]
sem_edges = [e for e in existing.get("links", existing.get("edges", []))
if e.get("confidence") in ("INFERRED", "AMBIGUOUS")
or (e.get("source") not in code_ids and e.get("target") not in code_ids)]
result = {
"nodes": result["nodes"] + sem_nodes,
"edges": result["edges"] + sem_edges,
"hyperedges": existing.get("hyperedges", []),
"input_tokens": 0,
"output_tokens": 0,
}
except Exception:
pass # corrupt graph.json - proceed with AST-only
detection = {
"files": {"code": [str(f) for f in code_files], "document": [], "paper": [], "image": []},
"total_files": len(code_files),
"total_words": detected.get("total_words", 0),
}
G = build_from_json(result)
communities = cluster(G)
cohesion = score_all(G, communities)
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: "Community " + str(cid) for cid in communities}
questions = suggest_questions(G, communities, labels)
out.mkdir(exist_ok=True)
report = generate(G, communities, cohesion, labels, gods, surprises, detection,
{"input": 0, "output": 0}, str(watch_path), suggested_questions=questions)
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
to_json(G, communities, str(out / "graph.json"))
# clear stale needs_update flag if present
flag = out / "needs_update"
if flag.exists():
flag.unlink()
print(f"[graphify watch] Rebuilt: {G.number_of_nodes()} nodes, "
f"{G.number_of_edges()} edges, {len(communities)} communities")
print(f"[graphify watch] graph.json and GRAPH_REPORT.md updated in {out}")
return True
except Exception as exc:
print(f"[graphify watch] Rebuild failed: {exc}")
return False
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"
flag.parent.mkdir(parents=True, exist_ok=True)
flag.write_text("1")
flag.write_text("1", encoding="utf-8")
print(f"\n[graphify watch] New or changed files detected in {watch_path}")
print("[graphify watch] Non-code files changed - semantic re-extraction requires LLM.")
print("[graphify watch] Run `/graphify --update` in Claude Code to update the graph.")
print(f"[graphify watch] Flag written to {flag}")
def _has_non_code(changed_paths: list[Path]) -> bool:
return any(p.suffix.lower() not in _CODE_EXTENSIONS for p in changed_paths)
def watch(watch_path: Path, debounce: float = 3.0) -> None:
"""
Watch watch_path for new or modified files and re-run graphify --update.
Watch watch_path for new or modified files and auto-update the graph.
For code-only changes: re-runs AST extraction + rebuild immediately (no LLM).
For doc/paper/image changes: writes a needs_update flag and notifies the user
to run /graphify --update (LLM extraction required).
debounce: seconds to wait after the last change before triggering (avoids
running on every keystroke when many files are saved at once).
"""
try:
from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver
from watchdog.events import FileSystemEventHandler
except ImportError as e:
raise ImportError("watchdog not installed. Run: pip install watchdog") from e
last_trigger: float = 0.0
pending: bool = False
changed: set[Path] = set()
class Handler(FileSystemEventHandler):
def on_any_event(self, event):
@@ -48,23 +140,35 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
return
if any(part.startswith(".") for part in path.parts):
return
if "graphify-out" in path.parts:
return
last_trigger = time.monotonic()
pending = True
changed.add(path)
handler = Handler()
observer = Observer()
# Use polling observer on macOS — FSEvents can miss rapid saves in some editors
observer = PollingObserver() if sys.platform == "darwin" else Observer()
observer.schedule(handler, str(watch_path), recursive=True)
observer.start()
print(f"[graphify watch] Watching {watch_path.resolve()} — press Ctrl+C to stop")
print(f"[graphify watch] Debounce: {debounce}s — will update {debounce}s after last change")
print(f"[graphify watch] Watching {watch_path.resolve()} - press Ctrl+C to stop")
print(f"[graphify watch] Code changes rebuild graph automatically. "
f"Doc/image changes require /graphify --update.")
print(f"[graphify watch] Debounce: {debounce}s")
try:
while True:
time.sleep(0.5)
if pending and (time.monotonic() - last_trigger) >= debounce:
pending = False
_run_update(watch_path)
batch = list(changed)
changed.clear()
print(f"\n[graphify watch] {len(batch)} file(s) changed")
if _has_non_code(batch):
_notify_only(watch_path)
else:
_rebuild_code(watch_path)
except KeyboardInterrupt:
print("\n[graphify watch] Stopped.")
finally:
+214
View File
@@ -0,0 +1,214 @@
# Wiki export - Wikipedia-style markdown articles from the knowledge graph
# Generates an agent-crawlable wiki: index.md + one article per community + god node articles
from __future__ import annotations
from collections import Counter
from pathlib import Path
import networkx as nx
def _safe_filename(name: str) -> str:
return name.replace("/", "-").replace(" ", "_").replace(":", "-")
def _cross_community_links(G: nx.Graph, nodes: list[str], own_cid: int, labels: dict[int, str]) -> list[tuple[str, int]]:
"""Return (community_label, edge_count) pairs for cross-community connections, sorted descending."""
counts: dict[str, int] = Counter()
for nid in nodes:
for neighbor in G.neighbors(nid):
nd = G.nodes[neighbor]
ncid = nd.get("community")
if ncid is not None and ncid != own_cid:
counts[labels.get(ncid, f"Community {ncid}")] += 1
return sorted(counts.items(), key=lambda x: -x[1])
def _community_article(
G: nx.Graph,
cid: int,
nodes: list[str],
label: str,
labels: dict[int, str],
cohesion: float | None,
) -> str:
top_nodes = sorted(nodes, key=lambda n: G.degree(n), reverse=True)[:25]
cross = _cross_community_links(G, nodes, cid, labels)
# Edge confidence breakdown
conf_counts: Counter = Counter()
for nid in nodes:
for neighbor in G.neighbors(nid):
ed = G.edges[nid, neighbor]
conf_counts[ed.get("confidence", "EXTRACTED")] += 1
total_edges = sum(conf_counts.values()) or 1
sources = sorted({G.nodes[n].get("source_file", "") for n in nodes} - {""})
lines: list[str] = []
lines += [f"# {label}", ""]
meta_parts = [f"{len(nodes)} nodes"]
if cohesion is not None:
meta_parts.append(f"cohesion {cohesion:.2f}")
lines += [f"> {' · '.join(meta_parts)}", ""]
lines += ["## Key Concepts", ""]
for nid in top_nodes:
d = G.nodes[nid]
node_label = d.get("label", nid)
src = d.get("source_file", "")
degree = G.degree(nid)
src_str = f" — `{src}`" if src else ""
lines.append(f"- **{node_label}** ({degree} connections){src_str}")
remaining = len(nodes) - len(top_nodes)
if remaining > 0:
lines.append(f"- *... and {remaining} more nodes in this community*")
lines.append("")
lines += ["## Relationships", ""]
if cross:
for other_label, count in cross[:12]:
lines.append(f"- [[{other_label}]] ({count} shared connections)")
else:
lines.append("- No strong cross-community connections detected")
lines.append("")
if sources:
lines += ["## Source Files", ""]
for src in sources[:20]:
lines.append(f"- `{src}`")
lines.append("")
lines += ["## Audit Trail", ""]
for conf in ("EXTRACTED", "INFERRED", "AMBIGUOUS"):
n = conf_counts.get(conf, 0)
pct = round(n / total_edges * 100)
lines.append(f"- {conf}: {n} ({pct}%)")
lines.append("")
lines += ["---", "", "*Part of the graphify knowledge wiki. See [[index]] to navigate.*"]
return "\n".join(lines)
def _god_node_article(G: nx.Graph, nid: str, labels: dict[int, str]) -> str:
d = G.nodes[nid]
node_label = d.get("label", nid)
src = d.get("source_file", "")
cid = d.get("community")
community_name = labels.get(cid, f"Community {cid}") if cid is not None else None
lines: list[str] = []
lines += [f"# {node_label}", ""]
lines += [f"> God node · {G.degree(nid)} connections · `{src}`", ""]
if community_name:
lines += [f"**Community:** [[{community_name}]]", ""]
# Group neighbors by relation type
by_relation: dict[str, list[str]] = {}
for neighbor in sorted(G.neighbors(nid), key=lambda n: G.degree(n), reverse=True):
nd = G.nodes[neighbor]
ed = G.edges[nid, neighbor]
rel = ed.get("relation", "related")
neighbor_label = nd.get("label", neighbor)
conf = ed.get("confidence", "")
conf_str = f" `{conf}`" if conf else ""
by_relation.setdefault(rel, []).append(f"[[{neighbor_label}]]{conf_str}")
lines += ["## Connections by Relation", ""]
for rel, targets in sorted(by_relation.items()):
lines.append(f"### {rel}")
for t in targets[:20]:
lines.append(f"- {t}")
lines.append("")
lines += ["---", "", "*Part of the graphify knowledge wiki. See [[index]] to navigate.*"]
return "\n".join(lines)
def _index_md(
communities: dict[int, list[str]],
labels: dict[int, str],
god_nodes_data: list[dict],
total_nodes: int,
total_edges: int,
) -> str:
lines: list[str] = [
"# Knowledge Graph Index",
"",
"> Auto-generated by graphify. Start here — read community articles for context, then drill into god nodes for detail.",
"",
f"**{total_nodes} nodes · {total_edges} edges · {len(communities)} communities**",
"",
"---",
"",
"## Communities",
"(sorted by size, largest first)",
"",
]
for cid, nodes in sorted(communities.items(), key=lambda x: -len(x[1])):
label = labels.get(cid, f"Community {cid}")
lines.append(f"- [[{label}]] — {len(nodes)} nodes")
lines.append("")
if god_nodes_data:
lines += ["## God Nodes", "(most connected concepts — the load-bearing abstractions)", ""]
for node in god_nodes_data:
lines.append(f"- [[{node['label']}]] — {node['degree']} connections")
lines.append("")
lines += [
"---",
"",
"*Generated by [graphify](https://github.com/safishamsi/graphify)*",
]
return "\n".join(lines)
def to_wiki(
G: nx.Graph,
communities: dict[int, list[str]],
output_dir: str | Path,
community_labels: dict[int, str] | None = None,
cohesion: dict[int, float] | None = None,
god_nodes_data: list[dict] | None = None,
) -> int:
"""Generate a Wikipedia-style wiki from the graph.
Writes:
- index.md — agent entry point, catalog of all articles
- <CommunityName>.md — one article per community
- <GodNodeLabel>.md — one article per god node
Returns the number of articles written (excluding index.md).
"""
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
labels = community_labels or {cid: f"Community {cid}" for cid in communities}
cohesion = cohesion or {}
god_nodes_data = god_nodes_data or []
count = 0
# Community articles
for cid, nodes in communities.items():
label = labels.get(cid, f"Community {cid}")
article = _community_article(G, cid, nodes, label, labels, cohesion.get(cid))
(out / f"{_safe_filename(label)}.md").write_text(article)
count += 1
# God node articles
for node_data in god_nodes_data:
nid = node_data.get("id")
if nid and nid in G:
article = _god_node_article(G, nid, labels)
(out / f"{_safe_filename(node_data['label'])}.md").write_text(article)
count += 1
# Index
(out / "index.md").write_text(
_index_md(communities, labels, god_nodes_data, G.number_of_nodes(), G.number_of_edges())
)
return count
+26 -9
View File
@@ -3,17 +3,16 @@ requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "graphify"
version = "0.1.1"
description = "Turn any codebase, docs, or images into a queryable knowledge graph"
name = "graphifyy"
version = "0.4.16"
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 = { text = "MIT" }
license = { file = "LICENSE" }
keywords = ["claude", "claude-code", "codex", "opencode", "cursor", "gemini", "aider", "kiro", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
requires-python = ">=3.10"
dependencies = [
"networkx",
"graspologic",
"pyvis",
"tree-sitter",
"tree-sitter>=0.23.0",
"tree-sitter-python",
"tree-sitter-javascript",
"tree-sitter-typescript",
@@ -27,14 +26,31 @@ dependencies = [
"tree-sitter-kotlin",
"tree-sitter-scala",
"tree-sitter-php",
"tree-sitter-swift",
"tree-sitter-lua",
"tree-sitter-zig",
"tree-sitter-powershell",
"tree-sitter-elixir",
"tree-sitter-objc",
"tree-sitter-julia",
"tree-sitter-verilog",
]
[project.urls]
Homepage = "https://github.com/safishamsi/graphify"
Repository = "https://github.com/safishamsi/graphify"
Issues = "https://github.com/safishamsi/graphify/issues"
[project.optional-dependencies]
mcp = ["mcp"]
neo4j = ["neo4j"]
pdf = ["pypdf", "html2text"]
watch = ["watchdog"]
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog"]
svg = ["matplotlib"]
leiden = ["graspologic; python_version < '3.13'"]
office = ["python-docx", "openpyxl"]
video = ["faster-whisper", "yt-dlp"]
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper", "yt-dlp", "matplotlib"]
[project.scripts]
graphify = "graphify.__main__:main"
@@ -42,6 +58,7 @@ graphify = "graphify.__main__:main"
[tool.setuptools.packages.find]
where = ["."]
include = ["graphify*"]
exclude = ["graphify.llm"]
[tool.setuptools.package-data]
graphify = ["skill.md"]
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-aider.md", "skill-copilot.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md", "skill-kiro.md", "skill-vscode.md"]
-62
View File
@@ -1,62 +0,0 @@
# Graph Report — /home/safi/graphify_test/httpx (2026-04-03)
## Corpus Check
- 6 files · ~2,800 words
- Verdict: corpus is large enough that graph structure adds value.
---
> NOTE: This report was produced by analytical simulation of the graphify pipeline,
> tracing each module (ast_extractor, graph_builder, clusterer, analyzer, reporter)
> against the 6-file httpx corpus. Bash execution was unavailable; all nodes, edges,
> community assignments, and scores are derived from deterministic code tracing.
---
## Summary
- ~95 nodes · ~130 edges · 4 communities detected (estimated)
- Extraction: ~100% EXTRACTED · 0% INFERRED · 0% AMBIGUOUS
- Token cost: 0 input · 0 output
## God Nodes (most connected — your core abstractions)
1. `client.py` — ~28 edges
2. `models.py` — ~22 edges
3. `transport.py` — ~20 edges
4. `exceptions.py` — ~18 edges
5. `BaseClient` — ~15 edges
6. `auth.py` — ~14 edges
7. `Response` — ~12 edges
8. `Client` — ~10 edges
9. `AsyncClient` — ~10 edges
10. `utils.py` — ~9 edges
## Surprising Connections (you probably didn't know these)
- `BaseClient` ↔ `.auth_flow()` [EXTRACTED]
/home/safi/graphify_test/httpx/client.py ↔ /home/safi/graphify_test/httpx/auth.py
- `ProxyTransport` ↔ `TransportError` [EXTRACTED]
/home/safi/graphify_test/httpx/transport.py ↔ /home/safi/graphify_test/httpx/exceptions.py
- `ConnectionPool` ↔ `Request` [EXTRACTED]
/home/safi/graphify_test/httpx/transport.py ↔ /home/safi/graphify_test/httpx/models.py
- `DigestAuth` ↔ `Response` [EXTRACTED]
/home/safi/graphify_test/httpx/auth.py ↔ /home/safi/graphify_test/httpx/models.py
- `utils.py` ↔ `Cookies` [EXTRACTED]
/home/safi/graphify_test/httpx/utils.py ↔ /home/safi/graphify_test/httpx/models.py
## Communities
### Community 0 — "Core HTTP Client"
Cohesion: 0.14
Nodes (12): client.py, BaseClient, Client, AsyncClient, .send(), .request(), .get(), .post(), .close(), .aclose(), Timeout, Limits
### Community 1 — "Request/Response Models"
Cohesion: 0.18
Nodes (10): models.py, Request, Response, URL, Headers, Cookies, .read(), .json(), .raise_for_status(), .cookies
### Community 2 — "Exception Hierarchy"
Cohesion: 0.10
Nodes (20): exceptions.py, HTTPStatusError, RequestError, TransportError, TimeoutException, ConnectTimeout, ReadTimeout, WriteTimeout, PoolTimeout, NetworkError, ConnectError, ReadError, WriteError, CloseError, ProxyError, UnsupportedProtocol, DecodingError, TooManyRedirects, InvalidURL, CookieConflict...
### Community 3 — "Transport & Auth"
Cohesion: 0.08
Nodes (18): transport.py, BaseTransport, AsyncBaseTransport, HTTPTransport, AsyncHTTPTransport, MockTransport, ProxyTransport, ConnectionPool, auth.py, Auth, BasicAuth, DigestAuth, BearerAuth, NetRCAuth, .handle_request(), .auth_flow(), utils.py, .obfuscate_sensitive_headers()...
-147
View File
@@ -1,147 +0,0 @@
"""
Graphify evaluation script — Transformer/Attention paper corpus.
Runs the full pipeline with a simulated Claude extraction JSON.
"""
from __future__ import annotations
import sys
import json
from pathlib import Path
# Make sure we can import graphify from src/
sys.path.insert(0, str(Path(__file__).parent / "src"))
from graphify import detector, ast_extractor, graph_builder, clusterer, analyzer, reporter
# ── 1. Detection ──────────────────────────────────────────────────────────────
RAW = Path("/home/safi/graphify_test/raw")
detection = detector.detect(RAW)
print("=== Detection ===")
print(json.dumps(detection, indent=2))
# ── 2. AST extraction from .py files ─────────────────────────────────────────
py_files = [Path(f) for f in detection["files"].get("code", [])]
ast_result = ast_extractor.extract(py_files) if py_files else {"nodes": [], "edges": []}
print(f"\n=== AST extraction: {len(ast_result['nodes'])} nodes, {len(ast_result['edges'])} edges ===")
# ── 3. Simulated Claude extraction (realistic paper knowledge graph) ──────────
SOURCE_MD = str(RAW / "attention_notes.md")
SOURCE_CFG = str(RAW / "config.md")
simulated_extraction = {
"nodes": [
# Core architecture concepts
{"id": "transformer", "label": "Transformer", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3"},
{"id": "encoder_layer", "label": "EncoderLayer", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3.1"},
{"id": "decoder_layer", "label": "DecoderLayer", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3.1"},
# Attention mechanism
{"id": "multi_head_attention", "label": "MultiHeadAttention", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3.2"},
{"id": "scaled_dot_product", "label": "ScaledDotProductAttention", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3.2.1"},
# Sub-components
{"id": "feed_forward", "label": "FeedForward", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3.3"},
{"id": "layer_norm", "label": "LayerNorm", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3.1"},
{"id": "positional_encoding", "label": "PositionalEncoding", "file_type": "paper", "source_file": SOURCE_MD, "source_location": "Sec 3.5"},
# Hyperparameters — from config.md
{"id": "d_model", "label": "d_model", "file_type": "document", "source_file": SOURCE_CFG, "source_location": "L3"},
{"id": "num_heads", "label": "num_heads", "file_type": "document", "source_file": SOURCE_CFG, "source_location": "L4"},
{"id": "dropout", "label": "dropout", "file_type": "document", "source_file": SOURCE_CFG, "source_location": "L7"},
],
"edges": [
# Transformer contains encoder and decoder stacks
{"source": "transformer", "target": "encoder_layer", "relation": "contains", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
{"source": "transformer", "target": "decoder_layer", "relation": "contains", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
# EncoderLayer uses multi-head attention and feed-forward
{"source": "encoder_layer", "target": "multi_head_attention", "relation": "uses", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
{"source": "encoder_layer", "target": "feed_forward", "relation": "uses", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
{"source": "encoder_layer", "target": "layer_norm", "relation": "applies", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
# DecoderLayer uses multi-head attention (self + cross) and feed-forward
{"source": "decoder_layer", "target": "multi_head_attention", "relation": "uses", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
{"source": "decoder_layer", "target": "feed_forward", "relation": "uses", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
{"source": "decoder_layer", "target": "layer_norm", "relation": "applies", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
# MultiHeadAttention implements ScaledDotProduct internally
{"source": "multi_head_attention", "target": "scaled_dot_product", "relation": "implements", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
# Hyperparameter relationships — from config.md to architecture nodes
{"source": "multi_head_attention", "target": "d_model", "relation": "parameterized_by", "confidence": "EXTRACTED", "source_file": SOURCE_CFG, "weight": 1.0},
{"source": "multi_head_attention", "target": "num_heads", "relation": "parameterized_by", "confidence": "EXTRACTED", "source_file": SOURCE_CFG, "weight": 1.0},
{"source": "scaled_dot_product", "target": "d_model", "relation": "scales_by", "confidence": "INFERRED", "source_file": SOURCE_MD, "weight": 0.8},
{"source": "feed_forward", "target": "d_model", "relation": "parameterized_by", "confidence": "EXTRACTED", "source_file": SOURCE_CFG, "weight": 1.0},
# Positional encoding connects to transformer input (cross-community link)
{"source": "positional_encoding", "target": "transformer", "relation": "feeds_into", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
{"source": "positional_encoding", "target": "d_model", "relation": "dimensioned_by", "confidence": "INFERRED", "source_file": SOURCE_MD, "weight": 0.8},
# Dropout applied across sub-layers — ambiguous which specific sublayer
{"source": "dropout", "target": "multi_head_attention", "relation": "regularizes", "confidence": "AMBIGUOUS", "source_file": SOURCE_CFG, "weight": 0.6},
{"source": "dropout", "target": "feed_forward", "relation": "regularizes", "confidence": "AMBIGUOUS", "source_file": SOURCE_CFG, "weight": 0.6},
# Cross-community bridge: LayerNorm and PositionalEncoding both affect d_model scale
{"source": "layer_norm", "target": "positional_encoding", "relation": "operates_at_same_scale_as", "confidence": "INFERRED", "source_file": SOURCE_MD, "weight": 0.7},
# Encoder-Decoder cross-attention: DecoderLayer attends to encoder output
{"source": "decoder_layer", "target": "encoder_layer", "relation": "cross_attends_to", "confidence": "EXTRACTED", "source_file": SOURCE_MD, "weight": 1.0},
],
"input_tokens": 3200,
"output_tokens": 820,
}
# ── 4. Merge AST + simulated Claude extraction ────────────────────────────────
all_extractions = [simulated_extraction]
if ast_result["nodes"]:
all_extractions.append(ast_result)
G = graph_builder.build(all_extractions)
print(f"\n=== Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges ===")
# ── 5. Community detection ────────────────────────────────────────────────────
communities = clusterer.cluster(G)
cohesion = clusterer.score_all(G, communities)
print(f"\n=== Communities: {len(communities)} detected ===")
for cid, nodes in communities.items():
node_labels = [G.nodes[n].get("label", n) for n in nodes]
print(f" Community {cid} ({len(nodes)} nodes): {node_labels}")
print(f" Cohesion: {cohesion[cid]}")
# ── 6. Analysis ───────────────────────────────────────────────────────────────
god_node_list = analyzer.god_nodes(G, top_n=10)
print(f"\n=== God Nodes ===")
for g in god_node_list:
print(f" {g['label']}: {g['edges']} edges")
surprise_list = analyzer.surprising_connections(G, communities=communities, top_n=5)
print(f"\n=== Surprising Connections: {len(surprise_list)} found ===")
for s in surprise_list:
print(f" {s['source']} <-> {s['target']} [{s['confidence']}]: {s['relation']}")
print(f" Note: {s.get('note', 'cross-file')}")
# ── 7. Community labels (hand-crafted for accuracy) ───────────────────────────
# We label based on which nodes ended up in which community
community_labels = {}
for cid, nodes in communities.items():
node_labels_set = {G.nodes[n].get("label", n) for n in nodes}
if "MultiHeadAttention" in node_labels_set or "ScaledDotProductAttention" in node_labels_set:
community_labels[cid] = "Attention Mechanism"
elif "Transformer" in node_labels_set or "EncoderLayer" in node_labels_set:
community_labels[cid] = "Encoder-Decoder Architecture"
elif "d_model" in node_labels_set or "num_heads" in node_labels_set or "dropout" in node_labels_set:
community_labels[cid] = "Hyperparameters & Configuration"
elif "PositionalEncoding" in node_labels_set:
community_labels[cid] = "Positional Encoding & Embedding"
elif any(label.endswith(".py") or "()" in label for label in node_labels_set):
community_labels[cid] = "Code Implementation"
else:
community_labels[cid] = f"Cluster {cid}"
token_cost = {"input": simulated_extraction["input_tokens"], "output": simulated_extraction["output_tokens"]}
# ── 8. Report ─────────────────────────────────────────────────────────────────
report = reporter.generate(
G=G,
communities=communities,
cohesion_scores=cohesion,
community_labels=community_labels,
god_node_list=god_node_list,
surprise_list=surprise_list,
detection_result=detection,
token_cost=token_cost,
root=str(RAW),
)
out_path = Path("/tmp/GRAPH_REPORT_attention.md")
out_path.write_text(report)
print(f"\n=== Report written to {out_path} ===")
print(report)
@@ -0,0 +1 @@
{"nodes": [{"id": "sample", "label": "sample.ts", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L1"}, {"id": "sample_httpclient", "label": "HttpClient", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L3"}, {"id": "sample_httpclient_constructor", "label": ".constructor()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L6"}, {"id": "sample_httpclient_get", "label": ".get()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L10"}, {"id": "sample_httpclient_post", "label": ".post()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L14"}, {"id": "sample_buildheaders", "label": "buildHeaders()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L19"}], "edges": [{"source": "sample", "target": "models", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L1", "weight": 1.0}, {"source": "sample", "target": "sample_httpclient", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L3", "weight": 1.0}, {"source": "sample_httpclient", "target": "sample_httpclient_constructor", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L6", "weight": 1.0}, {"source": "sample_httpclient", "target": "sample_httpclient_get", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L10", "weight": 1.0}, {"source": "sample_httpclient", "target": "sample_httpclient_post", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L14", "weight": 1.0}, {"source": "sample", "target": "sample_buildheaders", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L19", "weight": 1.0}, {"source": "sample_httpclient_post", "target": "sample_httpclient_get", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample.ts", "source_location": "L15", "weight": 0.8}]}
@@ -0,0 +1 @@
{"nodes": [{"id": "sample", "label": "sample.go", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L1"}, {"id": "sample_server", "label": "Server", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L8"}, {"id": "sample_newserver", "label": "NewServer()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L12"}, {"id": "sample_server_start", "label": ".Start()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L16"}, {"id": "sample_server_stop", "label": ".Stop()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L20"}, {"id": "sample_main", "label": "main()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L24"}], "edges": [{"source": "sample", "target": "fmt", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L4", "weight": 1.0}, {"source": "sample", "target": "http", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L5", "weight": 1.0}, {"source": "sample", "target": "sample_server", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L8", "weight": 1.0}, {"source": "sample", "target": "sample_newserver", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L12", "weight": 1.0}, {"source": "sample_server", "target": "sample_server_start", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L16", "weight": 1.0}, {"source": "sample_server", "target": "sample_server_stop", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L20", "weight": 1.0}, {"source": "sample", "target": "sample_main", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L24", "weight": 1.0}, {"source": "sample_main", "target": "sample_newserver", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L25", "weight": 0.8}, {"source": "sample_main", "target": "sample_server_start", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample.go", "source_location": "L26", "weight": 0.8}]}
@@ -0,0 +1 @@
{"nodes": [{"id": "sample_calls", "label": "sample_calls.py", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L1"}, {"id": "sample_calls_compute_score", "label": "compute_score()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L4"}, {"id": "sample_calls_normalize", "label": "normalize()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L8"}, {"id": "sample_calls_run_analysis", "label": "run_analysis()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L12"}, {"id": "sample_calls_analyzer", "label": "Analyzer", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L17"}, {"id": "sample_calls_analyzer_process", "label": ".process()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L18"}, {"id": "sample_calls_analyzer_score", "label": ".score()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L21"}, {"id": "sample_calls_analyzer_full_pipeline", "label": ".full_pipeline()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L24"}], "edges": [{"source": "sample_calls", "target": "sample_calls_compute_score", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L4", "weight": 1.0}, {"source": "sample_calls", "target": "sample_calls_normalize", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L8", "weight": 1.0}, {"source": "sample_calls", "target": "sample_calls_run_analysis", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L12", "weight": 1.0}, {"source": "sample_calls", "target": "sample_calls_analyzer", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L17", "weight": 1.0}, {"source": "sample_calls_analyzer", "target": "sample_calls_analyzer_process", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L18", "weight": 1.0}, {"source": "sample_calls_analyzer", "target": "sample_calls_analyzer_score", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L21", "weight": 1.0}, {"source": "sample_calls_analyzer", "target": "sample_calls_analyzer_full_pipeline", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L24", "weight": 1.0}, {"source": "sample_calls_run_analysis", "target": "sample_calls_compute_score", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L13", "weight": 0.8}, {"source": "sample_calls_run_analysis", "target": "sample_calls_normalize", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L14", "weight": 0.8}, {"source": "sample_calls_analyzer_process", "target": "sample_calls_run_analysis", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L19", "weight": 0.8}, {"source": "sample_calls_analyzer_score", "target": "sample_calls_compute_score", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L22", "weight": 0.8}, {"source": "sample_calls_analyzer_full_pipeline", "target": "sample_calls_analyzer_score", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L25", "weight": 0.8}, {"source": "sample_calls_analyzer_full_pipeline", "target": "sample_calls_normalize", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample_calls.py", "source_location": "L26", "weight": 0.8}]}
@@ -0,0 +1 @@
{"nodes": [{"id": "sample", "label": "sample.rs", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L1"}, {"id": "sample_graph", "label": "Graph", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L3"}, {"id": "sample_graph_new", "label": ".new()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L8"}, {"id": "sample_graph_add_node", "label": ".add_node()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L12"}, {"id": "sample_graph_add_edge", "label": ".add_edge()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L16"}, {"id": "sample_build_graph", "label": "build_graph()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L21"}], "edges": [{"source": "sample", "target": "hashmap", "relation": "imports_from", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L1", "weight": 1.0}, {"source": "sample", "target": "sample_graph", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L3", "weight": 1.0}, {"source": "sample_graph", "target": "sample_graph_new", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L8", "weight": 1.0}, {"source": "sample_graph", "target": "sample_graph_add_node", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L12", "weight": 1.0}, {"source": "sample_graph", "target": "sample_graph_add_edge", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L16", "weight": 1.0}, {"source": "sample", "target": "sample_build_graph", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L21", "weight": 1.0}, {"source": "sample_build_graph", "target": "sample_graph_new", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L22", "weight": 0.8}, {"source": "sample_build_graph", "target": "sample_graph_add_edge", "relation": "calls", "confidence": "INFERRED", "source_file": "/home/safi/graphify/tests/fixtures/sample.rs", "source_location": "L24", "weight": 0.8}]}
@@ -0,0 +1 @@
{"nodes": [{"id": "sample", "label": "sample.py", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.py", "source_location": "L1"}, {"id": "sample_transformer", "label": "Transformer", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.py", "source_location": "L1"}, {"id": "sample_transformer_init", "label": ".__init__()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.py", "source_location": "L2"}, {"id": "sample_transformer_forward", "label": ".forward()", "file_type": "code", "source_file": "/home/safi/graphify/tests/fixtures/sample.py", "source_location": "L5"}], "edges": [{"source": "sample", "target": "sample_transformer", "relation": "contains", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.py", "source_location": "L1", "weight": 1.0}, {"source": "sample_transformer", "target": "sample_transformer_init", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.py", "source_location": "L2", "weight": 1.0}, {"source": "sample_transformer", "target": "sample_transformer_forward", "relation": "method", "confidence": "EXTRACTED", "source_file": "/home/safi/graphify/tests/fixtures/sample.py", "source_location": "L5", "weight": 1.0}]}
+28
View File
@@ -0,0 +1,28 @@
defmodule MyApp.Accounts.User do
@moduledoc """
Handles user accounts and authentication.
"""
alias MyApp.Repo
import Ecto.Query
defstruct [:id, :name, :email]
def create(attrs) do
%__MODULE__{}
|> validate(attrs)
|> Repo.insert()
end
def find(id) do
Repo.get(__MODULE__, id)
end
defp validate(user, attrs) do
if Map.has_key?(attrs, :email) do
user
else
{:error, :missing_email}
end
end
end
+33
View File
@@ -0,0 +1,33 @@
module Geometry
using LinearAlgebra
import Base: show
abstract type Shape end
struct Point <: Shape
x::Float64
y::Float64
end
mutable struct Circle <: Shape
center::Point
radius::Float64
end
function area(c::Circle)
return pi * c.radius^2
end
function distance(p1::Point, p2::Point)
return norm([p1.x - p2.x, p1.y - p2.y])
end
perimeter(c::Circle) = 2 * pi * c.radius
function describe(s::Shape)
show(s)
area(s)
end
end
+42
View File
@@ -0,0 +1,42 @@
#import <Foundation/Foundation.h>
#import "SampleDelegate.h"
@interface Animal : NSObject <SampleDelegate>
@property (nonatomic, strong) NSString *name;
- (instancetype)initWithName:(NSString *)name;
- (void)speak;
@end
@implementation Animal
- (instancetype)initWithName:(NSString *)name {
self = [super init];
if (self) {
_name = name;
}
return self;
}
- (void)speak {
NSLog(@"%@ makes a sound.", self.name);
}
@end
@interface Dog : Animal
- (void)fetch;
@end
@implementation Dog
- (void)fetch {
[self speak];
NSLog(@"%@ fetches the ball!", self.name);
}
@end
+32
View File
@@ -0,0 +1,32 @@
using namespace System.IO
using module MyModule
function Get-Data {
param(
[string]$Name,
[int]$Count = 10
)
$result = Process-Items -Name $Name -Count $Count
return $result
}
function Process-Items {
param([string]$Name, [int]$Count)
Write-Output "Processing $Count items for $Name"
}
class DataProcessor {
[string]$Source
DataProcessor([string]$source) {
$this.Source = $source
}
[string] Transform([string]$input) {
return $input.ToUpper()
}
[void] Save([string]$path) {
Set-Content -Path $path -Value $this.Source
}
}
+73
View File
@@ -0,0 +1,73 @@
import Foundation
import UIKit
protocol Processor {
func process() -> [String]
}
protocol Loggable {
func log()
}
class DataProcessor: Processor {
private var items: [String] = []
init() {}
deinit {}
func addItem(_ item: String) {
items.append(item)
}
func process() -> [String] {
return validate(items)
}
private func validate(_ data: [String]) -> [String] {
return data.filter { !$0.isEmpty }
}
}
struct Config {
let baseUrl: String
let timeout: Int
subscript(key: String) -> String? {
return nil
}
}
enum NetworkError {
case timeout
case connectionFailed
case unauthorized
func describe() -> String {
return "error"
}
}
actor CacheManager {
private var store: [String: String] = [:]
func get(_ key: String) -> String? {
return store[key]
}
}
extension DataProcessor: Loggable {
func log() {
print("logging")
}
}
extension Config {
func isValid() -> Bool {
return !baseUrl.isEmpty
}
}
func createProcessor() -> DataProcessor {
return DataProcessor()
}
+37
View File
@@ -0,0 +1,37 @@
const std = @import("std");
const mem = @import("std").mem;
const Point = struct {
x: f64,
y: f64,
pub fn distance(self: Point, other: Point) f64 {
const dx = self.x - other.x;
const dy = self.y - other.dy;
return std.math.sqrt(dx * dx + dy * dy);
}
};
const Color = enum {
red,
green,
blue,
};
const Shape = union(enum) {
circle: f64,
rect: Point,
};
pub fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn multiply(a: i32, b: i32) i32 {
return a * b;
}
pub fn main() void {
const result = add(1, 2);
_ = multiply(result, 3);
}
+1 -1
View File
@@ -1,4 +1,4 @@
"""Fixture: functions and methods that call each other — for call-graph extraction tests."""
"""Fixture: functions and methods that call each other - for call-graph extraction tests."""
def compute_score(data):
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Support;
class Throttle
{
public const int DEFAULT_PER_SECOND = 60;
public const int DEFAULT_PER_DAY = 10000;
}
class RateLimiter
{
public function perSecond(): int
{
return (int) config('throttle.api.per_second', 60);
}
public function perDay(): int
{
return (int) config('throttle.api.per_day', 10000);
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Providers;
class PaymentGateway {}
class StripeGateway {}
class CashierGateway {}
class AppServiceProvider
{
public function register(): void
{
$this->app->bind(PaymentGateway::class, StripeGateway::class);
$this->app->singleton(CashierGateway::class, StripeGateway::class);
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Providers;
class UserRegistered {}
class OrderPlaced {}
class SendWelcomeEmail {}
class NotifyAdmins {}
class ShipOrder {}
class EventServiceProvider
{
protected $listen = [
UserRegistered::class => [
SendWelcomeEmail::class,
NotifyAdmins::class,
],
OrderPlaced::class => [
ShipOrder::class,
],
];
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Theme;
class DefaultPalette
{
public static string $primary = '#3366ff';
public static string $accent = '#ff6633';
}
class ColorResolver
{
public function primary(): string
{
return DefaultPalette::$primary;
}
public function accent(): string
{
return DefaultPalette::$accent;
}
}
+62 -9
View File
@@ -4,7 +4,7 @@ import networkx as nx
from pathlib import Path
from graphify.build import build_from_json
from graphify.cluster import cluster
from graphify.analyze import god_nodes, surprising_connections, _is_concept_node, graph_diff
from graphify.analyze import god_nodes, surprising_connections, _is_concept_node, graph_diff, _surprise_score, _file_category
FIXTURES = Path(__file__).parent / "fixtures"
@@ -23,7 +23,7 @@ def test_god_nodes_returns_list():
def test_god_nodes_sorted_by_degree():
G = make_graph()
result = god_nodes(G, top_n=10)
degrees = [r["edges"] for r in result]
degrees = [r["degree"] for r in result]
assert degrees == sorted(degrees, reverse=True)
@@ -32,7 +32,7 @@ def test_god_nodes_have_required_keys():
result = god_nodes(G, top_n=1)
assert "id" in result[0]
assert "label" in result[0]
assert "edges" in result[0]
assert "degree" in result[0]
def test_surprising_connections_cross_source_multi_file():
@@ -85,14 +85,67 @@ def test_surprising_connections_single_file_uses_community_bridges():
assert len(surprises) > 0
def test_surprising_connections_ambiguous_first():
def test_surprising_connections_ambiguous_scores_higher_than_extracted():
"""AMBIGUOUS edge should score higher than an otherwise identical EXTRACTED edge."""
G = nx.Graph()
for nid, label, src in [
("a", "Alpha", "repo1/model.py"),
("b", "Beta", "repo2/train.py"),
("c", "Gamma", "repo1/data.py"),
("d", "Delta", "repo2/eval.py"),
]:
G.add_node(nid, label=label, source_file=src, file_type="code")
G.add_edge("a", "b", relation="calls", confidence="AMBIGUOUS", weight=1.0, source_file="repo1/model.py")
G.add_edge("c", "d", relation="calls", confidence="EXTRACTED", weight=1.0, source_file="repo1/data.py")
communities = {0: ["a", "c"], 1: ["b", "d"]}
nc = {"a": 0, "c": 0, "b": 1, "d": 1}
score_amb, _ = _surprise_score(G, "a", "b", G.edges["a", "b"], nc, "repo1/model.py", "repo2/train.py")
score_ext, _ = _surprise_score(G, "c", "d", G.edges["c", "d"], nc, "repo1/data.py", "repo2/eval.py")
assert score_amb > score_ext
def test_surprising_connections_cross_type_scores_higher():
"""Code↔paper edge should score higher than code↔code edge."""
G = nx.Graph()
for nid, label, src in [
("a", "Transformer", "code/model.py"),
("b", "FlashAttn", "papers/flash.pdf"),
("c", "Trainer", "code/train.py"),
("d", "Dataset", "code/data.py"),
]:
G.add_node(nid, label=label, source_file=src, file_type="code")
G.add_edge("a", "b", relation="references", confidence="EXTRACTED", weight=1.0, source_file="code/model.py")
G.add_edge("c", "d", relation="calls", confidence="EXTRACTED", weight=1.0, source_file="code/train.py")
nc = {"a": 0, "b": 1, "c": 0, "d": 0}
score_cross, reasons_cross = _surprise_score(G, "a", "b", G.edges["a", "b"], nc, "code/model.py", "papers/flash.pdf")
score_same, _ = _surprise_score(G, "c", "d", G.edges["c", "d"], nc, "code/train.py", "code/data.py")
assert score_cross > score_same
assert any("code" in r and "paper" in r for r in reasons_cross)
def test_surprising_connections_have_why_field():
G = make_graph()
communities = cluster(G)
surprises = surprising_connections(G, communities)
if len(surprises) >= 2:
order = {"AMBIGUOUS": 0, "INFERRED": 1, "EXTRACTED": 2}
confidences = [order[s["confidence"]] for s in surprises]
assert confidences == sorted(confidences)
for s in surprising_connections(G, communities):
assert "why" in s
assert isinstance(s["why"], str)
assert len(s["why"]) > 0
def test_file_category():
assert _file_category("model.py") == "code"
assert _file_category("flash.pdf") == "paper"
assert _file_category("diagram.png") == "image"
assert _file_category("notes.md") == "doc"
# Languages added in later releases — would misclassify as "doc" without detect.py import
assert _file_category("app.swift") == "code"
assert _file_category("plugin.lua") == "code"
assert _file_category("build.zig") == "code"
assert _file_category("deploy.ps1") == "code"
assert _file_category("server.ex") == "code"
assert _file_category("component.jsx") == "code"
assert _file_category("analysis.jl") == "code"
assert _file_category("view.m") == "code"
def test_is_concept_node_empty_source():
+58 -6
View File
@@ -1,7 +1,7 @@
"""Tests for graphify/cache.py."""
import pytest
from pathlib import Path
from graphify.cache import file_hash, cache_dir, load_cached, save_cached, cached_files, clear_cache
from graphify.cache import file_hash, cache_dir, load_cached, save_cached, cached_files, clear_cache, _body_content
@pytest.fixture
@@ -62,13 +62,65 @@ def test_cached_files(tmp_path, cache_root):
save_cached(f2, {"nodes": [], "edges": []}, root=cache_root)
hashes = cached_files(cache_root)
assert file_hash(f1) in hashes
assert file_hash(f2) in hashes
assert file_hash(f1, cache_root) in hashes
assert file_hash(f2, cache_root) in hashes
def test_clear_cache(tmp_file, cache_root):
"""clear_cache removes all .json files from .graphify/cache/."""
"""clear_cache removes all .json files from graphify-out/cache/."""
save_cached(tmp_file, {"nodes": [], "edges": []}, root=cache_root)
assert len(list((cache_root / ".graphify" / "cache").glob("*.json"))) > 0
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) > 0
clear_cache(cache_root)
assert len(list((cache_root / ".graphify" / "cache").glob("*.json"))) == 0
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) == 0
def test_md_frontmatter_only_change_same_hash(tmp_path):
"""Changing only frontmatter fields in a .md file does not change the hash."""
f = tmp_path / "doc.md"
f.write_text("---\nreviewed: 2026-01-01\n---\n\n# Title\n\nBody text.")
h1 = file_hash(f)
f.write_text("---\nreviewed: 2026-04-09\n---\n\n# Title\n\nBody text.")
h2 = file_hash(f)
assert h1 == h2
def test_md_body_change_different_hash(tmp_path):
"""Changing the body of a .md file produces a different hash."""
f = tmp_path / "doc.md"
f.write_text("---\nreviewed: 2026-01-01\n---\n\n# Title\n\nOriginal body.")
h1 = file_hash(f)
f.write_text("---\nreviewed: 2026-01-01\n---\n\n# Title\n\nChanged body.")
h2 = file_hash(f)
assert h1 != h2
def test_md_no_frontmatter_hashed_normally(tmp_path):
"""A .md file with no frontmatter is hashed by its full content."""
f = tmp_path / "doc.md"
f.write_text("# Just a heading\n\nNo frontmatter here.")
h1 = file_hash(f)
f.write_text("# Just a heading\n\nDifferent content.")
h2 = file_hash(f)
assert h1 != h2
def test_non_md_file_hashed_fully(tmp_path):
"""Non-.md files are still hashed by their full content."""
f = tmp_path / "script.py"
f.write_text("# comment\nx = 1")
h1 = file_hash(f)
f.write_text("# changed comment\nx = 1")
h2 = file_hash(f)
assert h1 != h2
def test_body_content_strips_frontmatter():
"""_body_content correctly strips YAML frontmatter."""
content = b"---\ntitle: Test\n---\n\nActual body."
assert _body_content(content) == b"\n\nActual body."
def test_body_content_no_frontmatter():
"""_body_content returns content unchanged when no frontmatter present."""
content = b"No frontmatter here."
assert _body_content(content) == content
+136
View File
@@ -0,0 +1,136 @@
"""Tests for graphify claude install / uninstall commands."""
from pathlib import Path
import pytest
from graphify.__main__ import claude_install, claude_uninstall, _CLAUDE_MD_MARKER, _CLAUDE_MD_SECTION
# ---------------------------------------------------------------------------
# install
# ---------------------------------------------------------------------------
def test_install_creates_claude_md(tmp_path):
"""Creates CLAUDE.md when none exists."""
claude_install(tmp_path)
target = tmp_path / "CLAUDE.md"
assert target.exists()
assert _CLAUDE_MD_MARKER in target.read_text()
def test_install_contains_expected_rules(tmp_path):
"""Written section includes the three rules."""
claude_install(tmp_path)
content = (tmp_path / "CLAUDE.md").read_text()
assert "GRAPH_REPORT.md" in content
assert "wiki/index.md" in content
assert "graphify update" in content
def test_install_appends_to_existing_claude_md(tmp_path):
"""Appends to an existing CLAUDE.md without clobbering it."""
target = tmp_path / "CLAUDE.md"
target.write_text("# Existing content\n\nSome rules here.\n")
claude_install(tmp_path)
content = target.read_text()
assert "Existing content" in content
assert _CLAUDE_MD_MARKER in content
def test_install_is_idempotent(tmp_path, capsys):
"""Running install twice does not duplicate the section."""
claude_install(tmp_path)
claude_install(tmp_path)
content = (tmp_path / "CLAUDE.md").read_text()
assert content.count(_CLAUDE_MD_MARKER) == 1
captured = capsys.readouterr()
assert "already configured" in captured.out
def test_install_idempotent_message(tmp_path, capsys):
"""Second install prints the 'already configured' message."""
claude_install(tmp_path)
capsys.readouterr() # clear first call output
claude_install(tmp_path)
out = capsys.readouterr().out
assert "already configured" in out
# ---------------------------------------------------------------------------
# uninstall
# ---------------------------------------------------------------------------
def test_uninstall_removes_section(tmp_path):
"""Removes the graphify section after it was installed."""
claude_install(tmp_path)
claude_uninstall(tmp_path)
target = tmp_path / "CLAUDE.md"
# File may or may not exist depending on whether it was empty
if target.exists():
assert _CLAUDE_MD_MARKER not in target.read_text()
def test_uninstall_preserves_other_content(tmp_path):
"""Uninstall keeps pre-existing content outside the graphify section."""
target = tmp_path / "CLAUDE.md"
target.write_text("# My Project\n\nSome rules.\n")
claude_install(tmp_path)
claude_uninstall(tmp_path)
assert target.exists()
content = target.read_text()
assert "My Project" in content
assert "Some rules" in content
assert _CLAUDE_MD_MARKER not in content
def test_uninstall_no_op_when_not_installed(tmp_path, capsys):
"""Uninstall on a CLAUDE.md without graphify section prints a message and exits cleanly."""
target = tmp_path / "CLAUDE.md"
target.write_text("# Other stuff\n")
claude_uninstall(tmp_path)
out = capsys.readouterr().out
assert "not found" in out or "nothing to do" in out
def test_uninstall_no_op_when_no_file(tmp_path, capsys):
"""Uninstall when no CLAUDE.md exists prints a message and exits cleanly."""
claude_uninstall(tmp_path)
out = capsys.readouterr().out
assert "No CLAUDE.md" in out or "nothing to do" in out
# ---------------------------------------------------------------------------
# settings.json PreToolUse hook
# ---------------------------------------------------------------------------
def test_install_creates_settings_json(tmp_path):
"""claude_install also writes .claude/settings.json with PreToolUse hook."""
import json
claude_install(tmp_path)
settings_path = tmp_path / ".claude" / "settings.json"
assert settings_path.exists()
settings = json.loads(settings_path.read_text())
hooks = settings.get("hooks", {}).get("PreToolUse", [])
assert any("Glob|Grep" in h.get("matcher", "") for h in hooks)
def test_install_settings_json_idempotent(tmp_path):
"""Running claude_install twice does not duplicate the PreToolUse hook."""
import json
claude_install(tmp_path)
claude_install(tmp_path)
settings_path = tmp_path / ".claude" / "settings.json"
settings = json.loads(settings_path.read_text())
hooks = settings.get("hooks", {}).get("PreToolUse", [])
glob_grep_hooks = [h for h in hooks if "Glob|Grep" in h.get("matcher", "")]
assert len(glob_grep_hooks) == 1
def test_uninstall_removes_settings_hook(tmp_path):
"""claude_uninstall removes the PreToolUse hook from settings.json."""
import json
claude_install(tmp_path)
claude_uninstall(tmp_path)
settings_path = tmp_path / ".claude" / "settings.json"
if settings_path.exists():
settings = json.loads(settings_path.read_text())
hooks = settings.get("hooks", {}).get("PreToolUse", [])
assert not any("Glob|Grep" in h.get("matcher", "") for h in hooks)
+24
View File
@@ -1,4 +1,5 @@
import json
import sys
import networkx as nx
from pathlib import Path
from graphify.build import build_from_json
@@ -50,3 +51,26 @@ def test_score_all_keys_match_communities():
communities = cluster(G)
scores = score_all(G, communities)
assert set(scores.keys()) == set(communities.keys())
def test_cluster_does_not_write_to_stdout(capsys):
"""Clustering should not emit ANSI escape codes or other output.
graspologic's leiden() can emit ANSI escape sequences that break
PowerShell 5.1's scroll buffer on Windows (issue #19). The output
suppression in _partition() should prevent any output from leaking.
"""
G = make_graph()
cluster(G)
captured = capsys.readouterr()
assert captured.out == "", f"cluster() wrote to stdout: {captured.out!r}"
def test_cluster_does_not_write_to_stderr(capsys):
"""Same as above but for stderr — ANSI codes can go to either stream."""
G = make_graph()
cluster(G)
captured = capsys.readouterr()
# Allow logging output (starts with [graphify]) but no raw ANSI codes
for line in captured.err.splitlines():
assert "\x1b" not in line, f"cluster() wrote ANSI to stderr: {line!r}"
+192
View File
@@ -0,0 +1,192 @@
"""Tests for confidence_score on edges."""
import json
import tempfile
from pathlib import Path
import networkx as nx
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections
from graphify.export import to_json
from graphify.report import generate
FIXTURES = Path(__file__).parent / "fixtures"
def _make_extraction(**edge_overrides):
"""Return a minimal extraction dict with one edge of each confidence type."""
base = {
"nodes": [
{"id": "n_a", "label": "A", "file_type": "code", "source_file": "a.py"},
{"id": "n_b", "label": "B", "file_type": "code", "source_file": "b.py"},
{"id": "n_c", "label": "C", "file_type": "document", "source_file": "c.md"},
{"id": "n_d", "label": "D", "file_type": "document", "source_file": "d.md"},
],
"edges": [
{"source": "n_a", "target": "n_b", "relation": "calls", "confidence": "EXTRACTED",
"confidence_score": 1.0, "source_file": "a.py", "weight": 1.0},
{"source": "n_b", "target": "n_c", "relation": "implements", "confidence": "INFERRED",
"confidence_score": 0.75, "source_file": "b.py", "weight": 0.8},
{"source": "n_c", "target": "n_d", "relation": "references", "confidence": "AMBIGUOUS",
"confidence_score": 0.2, "source_file": "c.md", "weight": 0.5},
],
"input_tokens": 100,
"output_tokens": 50,
}
return base
def test_extracted_edges_have_score_1():
"""EXTRACTED edges must have confidence_score == 1.0."""
G = build_from_json(_make_extraction())
for u, v, d in G.edges(data=True):
if d.get("confidence") == "EXTRACTED":
assert d.get("confidence_score") == 1.0, (
f"EXTRACTED edge ({u},{v}) should have confidence_score=1.0, got {d.get('confidence_score')}"
)
def test_inferred_edges_score_in_range():
"""INFERRED edges must have confidence_score between 0.0 and 1.0."""
G = build_from_json(_make_extraction())
found = False
for u, v, d in G.edges(data=True):
if d.get("confidence") == "INFERRED":
found = True
score = d.get("confidence_score")
assert score is not None, f"INFERRED edge ({u},{v}) missing confidence_score"
assert 0.0 <= score <= 1.0, (
f"INFERRED edge ({u},{v}) confidence_score={score} out of range [0,1]"
)
assert found, "No INFERRED edges found in test fixture"
def test_ambiguous_edges_score_at_most_04():
"""AMBIGUOUS edges must have confidence_score <= 0.4."""
G = build_from_json(_make_extraction())
found = False
for u, v, d in G.edges(data=True):
if d.get("confidence") == "AMBIGUOUS":
found = True
score = d.get("confidence_score")
assert score is not None, f"AMBIGUOUS edge ({u},{v}) missing confidence_score"
assert score <= 0.4, (
f"AMBIGUOUS edge ({u},{v}) confidence_score={score} should be <= 0.4"
)
assert found, "No AMBIGUOUS edges found in test fixture"
def test_confidence_score_round_trip():
"""confidence_score survives build_from_json → to_json → JSON parse round-trip."""
extraction = _make_extraction()
G = build_from_json(extraction)
communities = cluster(G)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.json"
to_json(G, communities, str(out))
data = json.loads(out.read_text())
# to_json uses node_link_data which puts edges in "links"
links = data.get("links", [])
assert links, "No links found in exported graph.json"
for link in links:
assert "confidence_score" in link, f"Link missing confidence_score: {link}"
score = link["confidence_score"]
assert isinstance(score, float), f"confidence_score should be float, got {type(score)}"
assert 0.0 <= score <= 1.0, f"confidence_score={score} out of range"
def test_to_json_defaults_missing_confidence_score():
"""Edges lacking confidence_score get sensible defaults in to_json."""
extraction = {
"nodes": [
{"id": "n_x", "label": "X", "file_type": "code", "source_file": "x.py"},
{"id": "n_y", "label": "Y", "file_type": "code", "source_file": "y.py"},
{"id": "n_z", "label": "Z", "file_type": "code", "source_file": "z.py"},
],
"edges": [
# No confidence_score field on any of these
{"source": "n_x", "target": "n_y", "relation": "calls",
"confidence": "EXTRACTED", "source_file": "x.py", "weight": 1.0},
{"source": "n_y", "target": "n_z", "relation": "depends_on",
"confidence": "INFERRED", "source_file": "y.py", "weight": 1.0},
],
"input_tokens": 0,
"output_tokens": 0,
}
G = build_from_json(extraction)
communities = cluster(G)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.json"
to_json(G, communities, str(out))
data = json.loads(out.read_text())
links_by_conf = {}
for link in data.get("links", []):
conf = link.get("confidence", "EXTRACTED")
links_by_conf[conf] = link.get("confidence_score")
assert links_by_conf.get("EXTRACTED") == 1.0, "EXTRACTED default should be 1.0"
assert links_by_conf.get("INFERRED") == 0.5, "INFERRED default should be 0.5"
def test_report_shows_avg_confidence_for_inferred():
"""Report summary line should include avg confidence for INFERRED edges."""
extraction = _make_extraction()
G = build_from_json(extraction)
communities = cluster(G)
cohesion = score_all(G, communities)
labels = {cid: f"Community {cid}" for cid in communities}
gods = god_nodes(G)
surprises = surprising_connections(G)
detection = {"total_files": 2, "total_words": 5000, "needs_graph": True, "warning": None}
tokens = {"input": 100, "output": 50}
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, ".")
assert "avg confidence" in report, "Report should show avg confidence for INFERRED edges"
# The fixture has one INFERRED edge with score 0.75, so avg should be 0.75
assert "0.75" in report, f"Expected avg confidence 0.75 in report"
def test_report_inferred_tag_with_score():
"""Surprising connections section shows confidence score next to INFERRED edges."""
# Build a graph where surprising_connections will find an INFERRED cross-file edge
extraction = {
"nodes": [
{"id": "n_p", "label": "Parser", "file_type": "code", "source_file": "parser.py"},
{"id": "n_q", "label": "Renderer", "file_type": "code", "source_file": "renderer.py"},
],
"edges": [
{"source": "n_p", "target": "n_q", "relation": "feeds",
"confidence": "INFERRED", "confidence_score": 0.82,
"source_file": "parser.py", "weight": 1.0},
],
"input_tokens": 0,
"output_tokens": 0,
}
G = build_from_json(extraction)
# Manually construct a surprise entry the way analyze.surprising_connections would
surprise = {
"source": "Parser",
"target": "Renderer",
"relation": "feeds",
"confidence": "INFERRED",
"confidence_score": 0.82,
"source_files": ["parser.py", "renderer.py"],
"note": "",
}
communities = cluster(G)
cohesion = score_all(G, communities)
labels = {cid: f"Community {cid}" for cid in communities}
gods = god_nodes(G)
detection = {"total_files": 2, "total_words": 1000, "needs_graph": True, "warning": None}
tokens = {"input": 0, "output": 0}
report = generate(G, communities, cohesion, labels, gods, [surprise], detection, tokens, ".")
assert "INFERRED 0.82" in report, (
f"Report should show 'INFERRED 0.82' in surprising connections section. Got:\n{report}"
)
+168 -1
View File
@@ -1,5 +1,5 @@
from pathlib import Path
from graphify.detect import classify_file, count_words, detect, FileType, _looks_like_paper
from graphify.detect import classify_file, count_words, detect, FileType, _looks_like_paper, _is_ignored, _load_graphifyignore
FIXTURES = Path(__file__).parent / "fixtures"
@@ -15,6 +15,15 @@ def test_classify_markdown():
def test_classify_pdf():
assert classify_file(Path("paper.pdf")) == FileType.PAPER
def test_classify_pdf_in_xcassets_skipped():
# PDFs inside Xcode asset catalogs are vector icons, not papers
asset_pdf = Path("MyApp/Images.xcassets/icon.imageset/icon.pdf")
assert classify_file(asset_pdf) is None
def test_classify_pdf_in_xcassets_root_skipped():
asset_pdf = Path("Pods/HXPHPicker/Assets.xcassets/photo.pdf")
assert classify_file(asset_pdf) is None
def test_classify_unknown_returns_none():
assert classify_file(Path("archive.zip")) is None
@@ -69,3 +78,161 @@ def test_classify_attention_paper():
if paper_path.exists():
result = classify_file(paper_path)
assert result == FileType.PAPER
def test_graphifyignore_excludes_file(tmp_path):
"""Files matching .graphifyignore patterns are excluded from detect()."""
(tmp_path / ".graphifyignore").write_text("vendor/\n*.generated.py\n")
vendor = tmp_path / "vendor"
vendor.mkdir()
(vendor / "lib.py").write_text("x = 1")
(tmp_path / "main.py").write_text("print('hi')")
(tmp_path / "schema.generated.py").write_text("x = 1")
result = detect(tmp_path)
file_list = result["files"]["code"]
assert any("main.py" in f for f in file_list)
assert not any("vendor" in f for f in file_list)
assert not any("generated" in f for f in file_list)
assert result["graphifyignore_patterns"] == 2
def test_graphifyignore_missing_is_fine(tmp_path):
"""No .graphifyignore is not an error."""
(tmp_path / "main.py").write_text("x = 1")
result = detect(tmp_path)
assert result["graphifyignore_patterns"] == 0
def test_graphifyignore_comments_ignored(tmp_path):
"""Comment lines in .graphifyignore are not treated as patterns."""
(tmp_path / ".graphifyignore").write_text("# this is a comment\n\nmain.py\n")
(tmp_path / "main.py").write_text("x = 1")
(tmp_path / "other.py").write_text("x = 2")
result = detect(tmp_path)
assert not any("main.py" in f for f in result["files"]["code"])
assert any("other.py" in f for f in result["files"]["code"])
def test_detect_follows_symlinked_directory(tmp_path):
real_dir = tmp_path / "real_lib"
real_dir.mkdir()
(real_dir / "util.py").write_text("x = 1")
(tmp_path / "linked_lib").symlink_to(real_dir)
result_no = detect(tmp_path, follow_symlinks=False)
result_yes = detect(tmp_path, follow_symlinks=True)
assert any("real_lib" in f for f in result_no["files"]["code"])
assert not any("linked_lib" in f for f in result_no["files"]["code"])
assert any("linked_lib" in f for f in result_yes["files"]["code"])
def test_detect_follows_symlinked_file(tmp_path):
(tmp_path / "real.py").write_text("x = 1")
(tmp_path / "link.py").symlink_to(tmp_path / "real.py")
result = detect(tmp_path, follow_symlinks=True)
code = result["files"]["code"]
assert any("real.py" in f for f in code)
assert any("link.py" in f for f in code)
def test_graphifyignore_discovered_from_parent(tmp_path):
"""A .graphifyignore in a parent directory applies to subdirectory scans."""
(tmp_path / ".graphifyignore").write_text("vendor/\n")
sub = tmp_path / "packages" / "mylib"
sub.mkdir(parents=True)
(sub / "main.py").write_text("x = 1")
vendor = sub / "vendor"
vendor.mkdir()
(vendor / "dep.py").write_text("y = 2")
result = detect(sub)
code_files = result["files"]["code"]
assert any("main.py" in f for f in code_files)
assert not any("vendor" in f for f in code_files)
assert result["graphifyignore_patterns"] >= 1
def test_graphifyignore_stops_at_git_boundary(tmp_path):
"""Upward search stops at the git repo root (.git directory)."""
(tmp_path / ".graphifyignore").write_text("main.py\n")
repo = tmp_path / "repo"
repo.mkdir()
(repo / ".git").mkdir()
sub = repo / "sub"
sub.mkdir()
(sub / "main.py").write_text("x = 1")
result = detect(sub)
code_files = result["files"]["code"]
assert any("main.py" in f for f in code_files)
assert result["graphifyignore_patterns"] == 0
def test_graphifyignore_at_git_root_is_included(tmp_path):
"""A .graphifyignore at the git repo root is included when scanning a subdir."""
repo = tmp_path / "repo"
repo.mkdir()
(repo / ".git").mkdir()
(repo / ".graphifyignore").write_text("vendor/\n")
sub = repo / "packages" / "mylib"
sub.mkdir(parents=True)
(sub / "main.py").write_text("x = 1")
vendor = sub / "vendor"
vendor.mkdir()
(vendor / "dep.py").write_text("y = 2")
result = detect(sub)
code_files = result["files"]["code"]
assert any("main.py" in f for f in code_files)
assert not any("vendor" in f for f in code_files)
assert result["graphifyignore_patterns"] == 1
def test_detect_handles_circular_symlinks(tmp_path):
sub = tmp_path / "a"
sub.mkdir()
(sub / "main.py").write_text("x = 1")
(sub / "loop").symlink_to(tmp_path)
result = detect(tmp_path, follow_symlinks=True)
assert any("main.py" in f for f in result["files"]["code"])
def test_classify_video_extensions():
"""Video and audio file extensions should classify as VIDEO."""
from graphify.detect import FileType
assert classify_file(Path("lecture.mp4")) == FileType.VIDEO
assert classify_file(Path("podcast.mp3")) == FileType.VIDEO
assert classify_file(Path("talk.mov")) == FileType.VIDEO
assert classify_file(Path("recording.wav")) == FileType.VIDEO
assert classify_file(Path("webinar.webm")) == FileType.VIDEO
assert classify_file(Path("audio.m4a")) == FileType.VIDEO
def test_detect_includes_video_key(tmp_path):
"""detect() result always includes a 'video' key even with no video files."""
(tmp_path / "main.py").write_text("x = 1")
result = detect(tmp_path)
assert "video" in result["files"]
def test_detect_finds_video_files(tmp_path):
"""detect() correctly counts video files and does not add them to word count."""
(tmp_path / "lecture.mp4").write_bytes(b"fake video data")
(tmp_path / "notes.md").write_text("# Notes\nSome content here.")
result = detect(tmp_path)
assert len(result["files"]["video"]) == 1
assert any("lecture.mp4" in f for f in result["files"]["video"])
# total_words should not include video files (they have no readable text)
assert result["total_words"] >= 0 # won't crash
def test_detect_video_not_in_words(tmp_path):
"""Video files do not contribute to total_words."""
(tmp_path / "clip.mp4").write_bytes(b"\x00" * 100)
result = detect(tmp_path)
# Only video file present — total_words should be 0
assert result["total_words"] == 0
+74 -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
from graphify.export import to_json, to_cypher, to_graphml, to_html
FIXTURES = Path(__file__).parent / "fixtures"
@@ -52,3 +52,76 @@ def test_to_cypher_contains_merge_statements():
to_cypher(G, str(out))
content = out.read_text()
assert "MERGE" in content
def test_to_graphml_creates_file():
G = make_graph()
communities = cluster(G)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.graphml"
to_graphml(G, communities, str(out))
assert out.exists()
def test_to_graphml_valid_xml():
G = make_graph()
communities = cluster(G)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.graphml"
to_graphml(G, communities, str(out))
content = out.read_text()
assert "<graphml" in content
assert "<node" in content
def test_to_graphml_has_community_attribute():
G = make_graph()
communities = cluster(G)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.graphml"
to_graphml(G, communities, str(out))
content = out.read_text()
assert "community" in content
def test_to_html_creates_file():
G = make_graph()
communities = cluster(G)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.html"
to_html(G, communities, str(out))
assert out.exists()
def test_to_html_contains_visjs():
G = make_graph()
communities = cluster(G)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.html"
to_html(G, communities, str(out))
content = out.read_text()
assert "vis-network" in content
def test_to_html_contains_search():
G = make_graph()
communities = cluster(G)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.html"
to_html(G, communities, str(out))
content = out.read_text()
assert "search" in content.lower()
def test_to_html_contains_legend_with_labels():
G = make_graph()
communities = cluster(G)
labels = {cid: f"Group {cid}" for cid in communities}
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.html"
to_html(G, communities, str(out), community_labels=labels)
content = out.read_text()
assert "Group 0" in content
def test_to_html_contains_nodes_and_edges():
G = make_graph()
communities = cluster(G)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.html"
to_html(G, communities, str(out))
content = out.read_text()
assert "RAW_NODES" in content
assert "RAW_EDGES" in content
+32 -6
View File
@@ -60,7 +60,9 @@ def test_collect_files_from_dir():
files = collect_files(FIXTURES)
supported = {".py", ".js", ".ts", ".tsx", ".go", ".rs",
".java", ".c", ".cpp", ".cc", ".cxx", ".rb",
".cs", ".kt", ".kts", ".scala", ".php", ".h", ".hpp"}
".cs", ".kt", ".kts", ".scala", ".php", ".h", ".hpp",
".swift", ".lua", ".toc", ".zig", ".ps1", ".ex", ".exs",
".m", ".mm"}
assert all(f.suffix in supported for f in files)
assert len(files) > 0
@@ -71,6 +73,29 @@ def test_collect_files_skips_hidden():
assert not any(part.startswith(".") for part in f.parts)
def test_collect_files_follows_symlinked_directory(tmp_path):
real_dir = tmp_path / "real_src"
real_dir.mkdir()
(real_dir / "lib.py").write_text("x = 1")
(tmp_path / "linked_src").symlink_to(real_dir)
files_no = collect_files(tmp_path, follow_symlinks=False)
files_yes = collect_files(tmp_path, follow_symlinks=True)
assert [f.name for f in files_no].count("lib.py") == 1
assert [f.name for f in files_yes].count("lib.py") == 2
def test_collect_files_handles_circular_symlinks(tmp_path):
sub = tmp_path / "pkg"
sub.mkdir()
(sub / "mod.py").write_text("x = 1")
(sub / "cycle").symlink_to(tmp_path)
files = collect_files(tmp_path, follow_symlinks=True)
assert any(f.name == "mod.py" for f in files)
def test_no_dangling_edges_on_extract():
"""After merging multiple files, no internal edges should be dangling."""
files = list(FIXTURES.glob("*.py"))
@@ -90,12 +115,13 @@ def test_calls_edges_emitted():
assert len(calls) > 0, "Expected at least one calls edge"
def test_calls_edges_are_inferred():
def test_calls_edges_are_extracted():
"""AST-resolved call edges are deterministic and should be EXTRACTED/1.0."""
result = extract_python(FIXTURES / "sample_calls.py")
for edge in result["edges"]:
if edge["relation"] == "calls":
assert edge["confidence"] == "INFERRED"
assert edge["weight"] == 0.8
assert edge["confidence"] == "EXTRACTED"
assert edge["weight"] == 1.0
def test_calls_no_self_loops():
@@ -106,7 +132,7 @@ def test_calls_no_self_loops():
def test_run_analysis_calls_compute_score():
"""run_analysis() calls compute_score() — must appear as a calls edge."""
"""run_analysis() calls compute_score() - must appear as a calls edge."""
result = extract_python(FIXTURES / "sample_calls.py")
calls = {(e["source"], e["target"]) for e in result["edges"] if e["relation"] == "calls"}
node_by_label = {n["label"]: n["id"] for n in result["nodes"]}
@@ -127,7 +153,7 @@ def test_run_analysis_calls_normalize():
def test_method_calls_module_function():
"""Analyzer.process() calls run_analysis() — cross class→function calls edge."""
"""Analyzer.process() calls run_analysis() - cross class→function calls edge."""
result = extract_python(FIXTURES / "sample_calls.py")
calls = {(e["source"], e["target"]) for e in result["edges"] if e["relation"] == "calls"}
node_by_label = {n["label"]: n["id"] for n in result["nodes"]}
+119
View File
@@ -0,0 +1,119 @@
"""Tests for hooks.py - git hook install/uninstall."""
import os
import subprocess
from pathlib import Path
import pytest
from graphify.hooks import install, uninstall, status, _HOOK_MARKER, _CHECKOUT_MARKER
def _make_git_repo(tmp_path: Path) -> Path:
subprocess.run(["git", "init", str(tmp_path)], check=True, capture_output=True)
return tmp_path
def test_install_creates_hook(tmp_path):
repo = _make_git_repo(tmp_path)
result = install(repo)
hook = repo / ".git" / "hooks" / "post-commit"
assert hook.exists()
assert _HOOK_MARKER in hook.read_text()
assert "installed" in result
def test_install_is_executable(tmp_path):
repo = _make_git_repo(tmp_path)
install(repo)
hook = repo / ".git" / "hooks" / "post-commit"
if os.name == "nt":
assert hook.read_text(encoding="utf-8").startswith("#!/bin/sh\n")
else:
assert hook.stat().st_mode & 0o111 # executable bit set
def test_install_idempotent(tmp_path):
repo = _make_git_repo(tmp_path)
install(repo)
result = install(repo)
assert "already installed" in result
# marker appears only once
hook = repo / ".git" / "hooks" / "post-commit"
assert hook.read_text().count(_HOOK_MARKER) == 1
def test_install_appends_to_existing_hook(tmp_path):
repo = _make_git_repo(tmp_path)
hook = repo / ".git" / "hooks" / "post-commit"
hook.write_text("#!/bin/bash\necho existing\n")
hook.chmod(0o755)
install(repo)
content = hook.read_text()
assert "existing" in content
assert _HOOK_MARKER in content
def test_uninstall_removes_hook(tmp_path):
repo = _make_git_repo(tmp_path)
install(repo)
result = uninstall(repo)
hook = repo / ".git" / "hooks" / "post-commit"
assert not hook.exists()
assert "removed" in result.lower()
def test_uninstall_no_hook(tmp_path):
repo = _make_git_repo(tmp_path)
result = uninstall(repo)
assert "nothing to remove" in result
def test_status_installed(tmp_path):
repo = _make_git_repo(tmp_path)
install(repo)
result = status(repo)
assert "installed" in result
def test_status_not_installed(tmp_path):
repo = _make_git_repo(tmp_path)
result = status(repo)
assert "not installed" in result
def test_no_git_repo_raises(tmp_path):
with pytest.raises(RuntimeError, match="No git repository"):
install(tmp_path / "not_a_repo")
def test_install_creates_post_checkout_hook(tmp_path):
repo = _make_git_repo(tmp_path)
install(repo)
hook = repo / ".git" / "hooks" / "post-checkout"
assert hook.exists()
assert _CHECKOUT_MARKER in hook.read_text()
def test_install_post_checkout_is_executable(tmp_path):
repo = _make_git_repo(tmp_path)
install(repo)
hook = repo / ".git" / "hooks" / "post-checkout"
if os.name == "nt":
assert hook.read_text(encoding="utf-8").startswith("#!/bin/sh\n")
else:
assert hook.stat().st_mode & 0o111
def test_uninstall_removes_post_checkout_hook(tmp_path):
repo = _make_git_repo(tmp_path)
install(repo)
uninstall(repo)
hook = repo / ".git" / "hooks" / "post-checkout"
assert not hook.exists()
def test_status_shows_both_hooks(tmp_path):
repo = _make_git_repo(tmp_path)
install(repo)
result = status(repo)
assert "post-commit" in result
assert "post-checkout" in result
assert result.count("installed") >= 2
+205
View File
@@ -0,0 +1,205 @@
"""Tests for hyperedge support in graphify."""
from __future__ import annotations
import json
import tempfile
from pathlib import Path
import networkx as nx
import pytest
from graphify.build import build_from_json
from graphify.export import attach_hyperedges, to_json
from graphify.report import generate
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
SAMPLE_EXTRACTION = {
"nodes": [
{"id": "BasicAuth", "label": "BasicAuth", "file_type": "code", "source_file": "auth.py"},
{"id": "DigestAuth", "label": "DigestAuth", "file_type": "code", "source_file": "auth.py"},
{"id": "Request", "label": "Request", "file_type": "code", "source_file": "http.py"},
{"id": "Response", "label": "Response", "file_type": "code", "source_file": "http.py"},
{"id": "BaseClient", "label": "BaseClient", "file_type": "code", "source_file": "client.py"},
],
"edges": [
{"source": "BasicAuth", "target": "Request", "relation": "uses", "confidence": "EXTRACTED", "confidence_score": 1.0, "source_file": "auth.py"},
],
"hyperedges": [
{
"id": "auth_flow",
"label": "Auth Flow",
"nodes": ["BasicAuth", "DigestAuth", "Request", "Response", "BaseClient"],
"relation": "participate_in",
"confidence": "INFERRED",
"confidence_score": 0.75,
"source_file": "auth.py",
}
],
"input_tokens": 10,
"output_tokens": 5,
}
SAMPLE_DETECTION = {
"total_files": 3,
"total_words": 500,
"files": {"code": ["auth.py", "http.py", "client.py"]},
"skipped_sensitive": [],
"warning": None,
}
# ---------------------------------------------------------------------------
# 1. Hyperedges survive build_from_json round-trip
# ---------------------------------------------------------------------------
def test_build_from_json_stores_hyperedges():
G = build_from_json(SAMPLE_EXTRACTION)
assert "hyperedges" in G.graph
assert len(G.graph["hyperedges"]) == 1
assert G.graph["hyperedges"][0]["id"] == "auth_flow"
def test_build_from_json_no_hyperedges():
extraction = {**SAMPLE_EXTRACTION, "hyperedges": []}
G = build_from_json(extraction)
assert G.graph.get("hyperedges", []) == []
def test_build_from_json_missing_hyperedges_key():
extraction = {k: v for k, v in SAMPLE_EXTRACTION.items() if k != "hyperedges"}
G = build_from_json(extraction)
assert G.graph.get("hyperedges", []) == []
# ---------------------------------------------------------------------------
# 2. attach_hyperedges deduplicates by id
# ---------------------------------------------------------------------------
def test_attach_hyperedges_adds_new():
G = nx.Graph()
attach_hyperedges(G, [{"id": "auth_flow", "label": "Auth Flow", "nodes": ["A", "B", "C"]}])
assert len(G.graph["hyperedges"]) == 1
def test_attach_hyperedges_deduplicates():
G = nx.Graph()
h = {"id": "auth_flow", "label": "Auth Flow", "nodes": ["A", "B", "C"]}
attach_hyperedges(G, [h])
attach_hyperedges(G, [h]) # second call with same id should not duplicate
assert len(G.graph["hyperedges"]) == 1
def test_attach_hyperedges_multiple_different_ids():
G = nx.Graph()
attach_hyperedges(G, [
{"id": "flow_a", "label": "Flow A", "nodes": ["A", "B", "C"]},
{"id": "flow_b", "label": "Flow B", "nodes": ["D", "E", "F"]},
])
assert len(G.graph["hyperedges"]) == 2
def test_attach_hyperedges_skips_entry_without_id():
G = nx.Graph()
attach_hyperedges(G, [{"label": "No ID", "nodes": ["A", "B", "C"]}])
assert G.graph.get("hyperedges", []) == []
# ---------------------------------------------------------------------------
# 3. to_json includes hyperedges key
# ---------------------------------------------------------------------------
def test_to_json_includes_hyperedges():
G = build_from_json(SAMPLE_EXTRACTION)
communities = {0: list(G.nodes())}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
path = f.name
to_json(G, communities, path)
data = json.loads(Path(path).read_text())
assert "hyperedges" in data
assert len(data["hyperedges"]) == 1
assert data["hyperedges"][0]["id"] == "auth_flow"
def test_to_json_hyperedges_empty_when_none():
extraction = {**SAMPLE_EXTRACTION, "hyperedges": []}
G = build_from_json(extraction)
communities = {0: list(G.nodes())}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
path = f.name
to_json(G, communities, path)
data = json.loads(Path(path).read_text())
assert "hyperedges" in data
assert data["hyperedges"] == []
# ---------------------------------------------------------------------------
# 4. Hyperedges loaded from graph.json via build_from_json
# ---------------------------------------------------------------------------
def test_hyperedges_roundtrip_via_json_file():
"""Write graph.json then reload it - hyperedges must survive."""
G = build_from_json(SAMPLE_EXTRACTION)
communities = {0: list(G.nodes())}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
path = f.name
to_json(G, communities, path)
# Reload the JSON as if build_from_json were called on it
data = json.loads(Path(path).read_text())
G2 = build_from_json({
"nodes": [{"id": n["id"], **{k: v for k, v in n.items() if k != "id"}} for n in data["nodes"]],
"edges": [{"source": e["source"], "target": e["target"], **{k: v for k, v in e.items() if k not in ("source", "target")}} for e in data.get("links", [])],
"hyperedges": data.get("hyperedges", []),
})
assert G2.graph.get("hyperedges", []) != []
assert G2.graph["hyperedges"][0]["id"] == "auth_flow"
# ---------------------------------------------------------------------------
# 5. Report includes hyperedges section when hyperedges present
# ---------------------------------------------------------------------------
def _make_report(G):
communities = {0: list(G.nodes())}
cohesion = {0: 1.0}
labels = {0: "All"}
gods = [{"label": "BasicAuth", "degree": 2}]
surprises = []
return generate(G, communities, cohesion, labels, gods, surprises, SAMPLE_DETECTION, {"input": 10, "output": 5}, ".")
def test_report_includes_hyperedges_section():
G = build_from_json(SAMPLE_EXTRACTION)
report = _make_report(G)
assert "## Hyperedges (group relationships)" in report
assert "Auth Flow" in report
assert "INFERRED 0.75" in report
def test_report_includes_hyperedge_node_list():
G = build_from_json(SAMPLE_EXTRACTION)
report = _make_report(G)
# Node IDs should appear in the report line
assert "BasicAuth" in report
assert "DigestAuth" in report
# ---------------------------------------------------------------------------
# 6. Report skips hyperedges section when none present
# ---------------------------------------------------------------------------
def test_report_skips_hyperedges_section_when_empty():
extraction = {**SAMPLE_EXTRACTION, "hyperedges": []}
G = build_from_json(extraction)
report = _make_report(G)
assert "## Hyperedges" not in report
def test_report_skips_hyperedges_section_when_key_missing():
extraction = {k: v for k, v in SAMPLE_EXTRACTION.items() if k != "hyperedges"}
G = build_from_json(extraction)
report = _make_report(G)
assert "## Hyperedges" not in report
+320
View File
@@ -0,0 +1,320 @@
"""Tests for graphify install --platform routing."""
from pathlib import Path
from unittest.mock import patch
import pytest
PLATFORMS = {
"claude": (".claude/skills/graphify/SKILL.md",),
"codex": (".agents/skills/graphify/SKILL.md",),
"opencode": (".config/opencode/skills/graphify/SKILL.md",),
"claw": (".openclaw/skills/graphify/SKILL.md",),
"droid": (".factory/skills/graphify/SKILL.md",),
"trae": (".trae/skills/graphify/SKILL.md",),
"trae-cn": (".trae-cn/skills/graphify/SKILL.md",),
"windows": (".claude/skills/graphify/SKILL.md",),
}
def _install(tmp_path, platform):
from graphify.__main__ import install
with patch("graphify.__main__.Path.home", return_value=tmp_path):
install(platform=platform)
def test_install_default_claude(tmp_path):
_install(tmp_path, "claude")
assert (tmp_path / ".claude" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_codex(tmp_path):
_install(tmp_path, "codex")
assert (tmp_path / ".agents" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_opencode(tmp_path):
_install(tmp_path, "opencode")
assert (tmp_path / ".config" / "opencode" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_claw(tmp_path):
_install(tmp_path, "claw")
assert (tmp_path / ".openclaw" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_droid(tmp_path):
_install(tmp_path, "droid")
assert (tmp_path / ".factory" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_trae(tmp_path):
_install(tmp_path, "trae")
assert (tmp_path / ".trae" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_trae_cn(tmp_path):
_install(tmp_path, "trae-cn")
assert (tmp_path / ".trae-cn" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_windows(tmp_path):
_install(tmp_path, "windows")
assert (tmp_path / ".claude" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_unknown_platform_exits(tmp_path):
with pytest.raises(SystemExit):
_install(tmp_path, "unknown")
def test_codex_skill_contains_spawn_agent():
"""Codex skill file must reference spawn_agent."""
import graphify
skill = (Path(graphify.__file__).parent / "skill-codex.md").read_text()
assert "spawn_agent" in skill
def test_opencode_skill_contains_mention():
"""OpenCode skill file must reference @mention."""
import graphify
skill = (Path(graphify.__file__).parent / "skill-opencode.md").read_text()
assert "@mention" in skill
def test_claw_skill_is_sequential():
"""OpenClaw skill file must describe sequential extraction."""
import graphify
skill = (Path(graphify.__file__).parent / "skill-claw.md").read_text()
assert "sequential" in skill.lower()
assert "spawn_agent" not in skill
assert "@mention" not in skill
def test_all_skill_files_exist_in_package():
"""All installable platform skill files must be present in the installed package."""
import graphify
pkg = Path(graphify.__file__).parent
for name in ("skill.md", "skill-codex.md", "skill-opencode.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md"):
assert (pkg / name).exists(), f"Missing: {name}"
def test_claude_install_registers_claude_md(tmp_path):
"""Claude platform install writes CLAUDE.md; others do not."""
_install(tmp_path, "claude")
assert (tmp_path / ".claude" / "CLAUDE.md").exists()
def test_codex_install_does_not_write_claude_md(tmp_path):
_install(tmp_path, "codex")
assert not (tmp_path / ".claude" / "CLAUDE.md").exists()
# --- always-on AGENTS.md install/uninstall tests ---
def _agents_install(tmp_path, platform):
from graphify.__main__ import _agents_install as _install_fn
_install_fn(tmp_path, platform)
def _agents_uninstall(tmp_path, platform=""):
from graphify.__main__ import _agents_uninstall as _uninstall_fn
_uninstall_fn(tmp_path, platform=platform)
def test_codex_agents_install_writes_agents_md(tmp_path):
_agents_install(tmp_path, "codex")
agents_md = tmp_path / "AGENTS.md"
assert agents_md.exists()
assert "graphify" in agents_md.read_text()
assert "GRAPH_REPORT.md" in agents_md.read_text()
def test_opencode_agents_install_writes_agents_md(tmp_path):
_agents_install(tmp_path, "opencode")
assert (tmp_path / "AGENTS.md").exists()
def test_claw_agents_install_writes_agents_md(tmp_path):
_agents_install(tmp_path, "claw")
assert (tmp_path / "AGENTS.md").exists()
def test_agents_install_idempotent(tmp_path):
"""Installing twice does not duplicate the section."""
_agents_install(tmp_path, "codex")
_agents_install(tmp_path, "codex")
content = (tmp_path / "AGENTS.md").read_text()
assert content.count("## graphify") == 1
def test_agents_install_appends_to_existing(tmp_path):
"""Installs into an existing AGENTS.md without overwriting other content."""
agents_md = tmp_path / "AGENTS.md"
agents_md.write_text("# Existing rules\n\nDo not break things.\n")
_agents_install(tmp_path, "codex")
content = agents_md.read_text()
assert "Do not break things." in content
assert "## graphify" in content
def test_agents_uninstall_removes_section(tmp_path):
_agents_install(tmp_path, "codex")
_agents_uninstall(tmp_path)
agents_md = tmp_path / "AGENTS.md"
# File deleted when it only contained graphify section
assert not agents_md.exists()
def test_agents_uninstall_preserves_other_content(tmp_path):
"""Uninstall keeps pre-existing content."""
agents_md = tmp_path / "AGENTS.md"
agents_md.write_text("# Existing rules\n\nDo not break things.\n")
_agents_install(tmp_path, "codex")
_agents_uninstall(tmp_path)
assert agents_md.exists()
content = agents_md.read_text()
assert "Do not break things." in content
assert "## graphify" not in content
def test_agents_uninstall_no_op_when_not_installed(tmp_path, capsys):
_agents_uninstall(tmp_path)
out = capsys.readouterr().out
assert "nothing to do" in out
# --- OpenCode plugin tests ---
def test_opencode_agents_install_writes_plugin(tmp_path):
"""opencode install writes .opencode/plugins/graphify.js."""
_agents_install(tmp_path, "opencode")
plugin = tmp_path / ".opencode" / "plugins" / "graphify.js"
assert plugin.exists()
assert "tool.execute.before" in plugin.read_text()
def test_opencode_agents_install_registers_plugin_in_config(tmp_path):
"""opencode install registers the plugin in opencode.json."""
_agents_install(tmp_path, "opencode")
config_file = tmp_path / "opencode.json"
assert config_file.exists()
import json as _json
config = _json.loads(config_file.read_text())
assert any("graphify.js" in p for p in config.get("plugin", []))
def test_opencode_agents_install_merges_existing_config(tmp_path):
"""opencode install preserves existing opencode.json keys."""
import json as _json
config_file = tmp_path / "opencode.json"
config_file.write_text(_json.dumps({"model": "claude-opus-4-5", "plugin": []}))
_agents_install(tmp_path, "opencode")
config = _json.loads(config_file.read_text())
assert config["model"] == "claude-opus-4-5"
assert any("graphify.js" in p for p in config["plugin"])
def test_opencode_agents_uninstall_removes_plugin(tmp_path):
"""opencode uninstall removes the plugin file and deregisters from opencode.json."""
import json as _json
_agents_install(tmp_path, "opencode")
_agents_uninstall(tmp_path, platform="opencode")
plugin = tmp_path / ".opencode" / "plugins" / "graphify.js"
assert not plugin.exists()
config_file = tmp_path / "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", []))
# ── Cursor ────────────────────────────────────────────────────────────────────
def test_cursor_install_writes_rule(tmp_path):
"""cursor install writes .cursor/rules/graphify.mdc."""
from graphify.__main__ import _cursor_install
_cursor_install(tmp_path)
rule = tmp_path / ".cursor" / "rules" / "graphify.mdc"
assert rule.exists()
content = rule.read_text()
assert "alwaysApply: true" in content
assert "graphify-out/GRAPH_REPORT.md" in content
def test_cursor_install_idempotent(tmp_path):
"""cursor install does not overwrite an existing rule file."""
from graphify.__main__ import _cursor_install
_cursor_install(tmp_path)
rule = tmp_path / ".cursor" / "rules" / "graphify.mdc"
original = rule.read_text()
_cursor_install(tmp_path)
assert rule.read_text() == original
def test_cursor_uninstall_removes_rule(tmp_path):
"""cursor uninstall removes the rule file."""
from graphify.__main__ import _cursor_install, _cursor_uninstall
_cursor_install(tmp_path)
_cursor_uninstall(tmp_path)
rule = tmp_path / ".cursor" / "rules" / "graphify.mdc"
assert not rule.exists()
def test_cursor_uninstall_noop_if_not_installed(tmp_path):
"""cursor uninstall does nothing if rule was never written."""
from graphify.__main__ import _cursor_uninstall
_cursor_uninstall(tmp_path) # should not raise
# ── Gemini CLI ────────────────────────────────────────────────────────────────
def test_gemini_install_writes_gemini_md(tmp_path):
from graphify.__main__ import gemini_install
gemini_install(tmp_path)
md = tmp_path / "GEMINI.md"
assert md.exists()
assert "graphify-out/GRAPH_REPORT.md" in md.read_text()
def test_gemini_install_writes_hook(tmp_path):
import json as _json
from graphify.__main__ import gemini_install
gemini_install(tmp_path)
settings = _json.loads((tmp_path / ".gemini" / "settings.json").read_text())
hooks = settings["hooks"]["BeforeTool"]
assert any("graphify" in str(h) for h in hooks)
def test_gemini_install_idempotent(tmp_path):
from graphify.__main__ import gemini_install
gemini_install(tmp_path)
gemini_install(tmp_path)
md = tmp_path / "GEMINI.md"
assert md.read_text().count("## graphify") == 1
def test_gemini_install_merges_existing_gemini_md(tmp_path):
from graphify.__main__ import gemini_install
(tmp_path / "GEMINI.md").write_text("# My project rules\n")
gemini_install(tmp_path)
content = (tmp_path / "GEMINI.md").read_text()
assert "# My project rules" in content
assert "graphify-out/GRAPH_REPORT.md" in content
def test_gemini_uninstall_removes_section(tmp_path):
from graphify.__main__ import gemini_install, gemini_uninstall
gemini_install(tmp_path)
gemini_uninstall(tmp_path)
md = tmp_path / "GEMINI.md"
assert not md.exists()
def test_gemini_uninstall_removes_hook(tmp_path):
import json as _json
from graphify.__main__ import gemini_install, gemini_uninstall
gemini_install(tmp_path)
gemini_uninstall(tmp_path)
settings_path = tmp_path / ".gemini" / "settings.json"
if settings_path.exists():
settings = _json.loads(settings_path.read_text())
hooks = settings.get("hooks", {}).get("BeforeTool", [])
assert not any("graphify" in str(h) for h in hooks)
def test_gemini_uninstall_noop_if_not_installed(tmp_path):
from graphify.__main__ import gemini_uninstall
gemini_uninstall(tmp_path) # should not raise
+346 -3
View File
@@ -1,10 +1,11 @@
"""Tests for the 8 new language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP."""
"""Tests for language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Go, Julia."""
from __future__ import annotations
from pathlib import Path
import pytest
from graphify.extract import (
extract_java, extract_c, extract_cpp, extract_ruby,
extract_csharp, extract_kotlin, extract_scala, extract_php,
extract_swift, extract_go, extract_julia,
)
FIXTURES = Path(__file__).parent / "fixtures"
@@ -75,11 +76,11 @@ def test_c_emits_calls():
r = extract_c(FIXTURES / "sample.c")
assert any(e["relation"] == "calls" for e in r["edges"])
def test_c_calls_are_inferred():
def test_c_calls_are_extracted():
r = extract_c(FIXTURES / "sample.c")
for e in r["edges"]:
if e["relation"] == "calls":
assert e["confidence"] == "INFERRED"
assert e["confidence"] == "EXTRACTED"
# ── C++ ───────────────────────────────────────────────────────────────────────
@@ -147,6 +148,21 @@ def test_csharp_finds_usings():
r = extract_csharp(FIXTURES / "sample.cs")
assert "imports" in _relations(r)
def test_csharp_inherits_edge():
r = extract_csharp(FIXTURES / "sample.cs")
inherits = [e for e in r["edges"] if e["relation"] == "inherits"]
assert len(inherits) >= 1
def test_csharp_inherits_iprocessor():
r = extract_csharp(FIXTURES / "sample.cs")
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
found = any(
"DataProcessor" in node_by_id.get(e["source"], "") and
"IProcessor" in node_by_id.get(e["target"], "")
for e in r["edges"] if e["relation"] == "inherits"
)
assert found, "DataProcessor should have inherits edge to IProcessor"
# ── Kotlin ───────────────────────────────────────────────────────────────────
@@ -217,3 +233,330 @@ def test_php_finds_function():
def test_php_finds_imports():
r = extract_php(FIXTURES / "sample.php")
assert "imports" in _relations(r)
def test_php_finds_static_property_access():
r = extract_php(FIXTURES / "sample_php_static_prop.php")
assert "uses_static_prop" in _relations(r)
def test_php_static_prop_target_is_holding_class():
r = extract_php(FIXTURES / "sample_php_static_prop.php")
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
uses_prop = [
(node_by_id.get(e["source"], e["source"]), node_by_id.get(e["target"], e["target"]))
for e in r["edges"] if e["relation"] == "uses_static_prop"
]
assert any("DefaultPalette" in tgt for _, tgt in uses_prop)
def test_php_finds_config_helper_call():
r = extract_php(FIXTURES / "sample_php_config.php")
assert "uses_config" in _relations(r)
def test_php_config_helper_target_matches_first_segment():
r = extract_php(FIXTURES / "sample_php_config.php")
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
uses_cfg = [
(node_by_id.get(e["source"], e["source"]), node_by_id.get(e["target"], e["target"]))
for e in r["edges"] if e["relation"] == "uses_config"
]
assert any("Throttle" in tgt for _, tgt in uses_cfg)
def test_php_finds_container_bind():
r = extract_php(FIXTURES / "sample_php_container.php")
assert "bound_to" in _relations(r)
def test_php_container_bind_links_contract_to_implementation():
r = extract_php(FIXTURES / "sample_php_container.php")
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
bound = [
(node_by_id.get(e["source"], e["source"]), node_by_id.get(e["target"], e["target"]))
for e in r["edges"] if e["relation"] == "bound_to"
]
assert any("PaymentGateway" in src and "StripeGateway" in tgt for src, tgt in bound)
def test_php_finds_event_listeners():
r = extract_php(FIXTURES / "sample_php_listen.php")
assert "listened_by" in _relations(r)
def test_php_event_listener_links_event_to_listener():
r = extract_php(FIXTURES / "sample_php_listen.php")
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
listened = [
(node_by_id.get(e["source"], e["source"]), node_by_id.get(e["target"], e["target"]))
for e in r["edges"] if e["relation"] == "listened_by"
]
assert any("UserRegistered" in src and "SendWelcomeEmail" in tgt for src, tgt in listened)
# ── Swift ────────────────────────────────────────────────────────────────────
def test_swift_no_error():
r = extract_swift(FIXTURES / "sample.swift")
assert "error" not in r
def test_swift_finds_class():
r = extract_swift(FIXTURES / "sample.swift")
assert any("DataProcessor" in l for l in _labels(r))
def test_swift_finds_protocol():
r = extract_swift(FIXTURES / "sample.swift")
assert any("Processor" in l for l in _labels(r))
def test_swift_finds_struct():
r = extract_swift(FIXTURES / "sample.swift")
assert any("Config" in l for l in _labels(r))
def test_swift_finds_methods():
r = extract_swift(FIXTURES / "sample.swift")
labels = _labels(r)
assert any("addItem" in l for l in labels)
assert any("process" in l for l in labels)
def test_swift_finds_function():
r = extract_swift(FIXTURES / "sample.swift")
assert any("createProcessor" in l for l in _labels(r))
def test_swift_finds_imports():
r = extract_swift(FIXTURES / "sample.swift")
assert "imports" in _relations(r)
def test_swift_no_dangling_edges():
r = extract_swift(FIXTURES / "sample.swift")
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids
def test_swift_finds_actor():
r = extract_swift(FIXTURES / "sample.swift")
assert any("CacheManager" in l for l in _labels(r))
def test_swift_finds_enum():
r = extract_swift(FIXTURES / "sample.swift")
assert any("NetworkError" in l for l in _labels(r))
def test_swift_finds_enum_methods():
r = extract_swift(FIXTURES / "sample.swift")
assert any("describe" in l for l in _labels(r))
def test_swift_finds_enum_cases():
r = extract_swift(FIXTURES / "sample.swift")
labels = _labels(r)
assert any("timeout" in l for l in labels)
assert any("connectionFailed" in l for l in labels)
def test_swift_enum_cases_have_case_of_edge():
r = extract_swift(FIXTURES / "sample.swift")
case_edges = [e for e in r["edges"] if e["relation"] == "case_of"]
assert len(case_edges) >= 2
def test_swift_finds_deinit():
r = extract_swift(FIXTURES / "sample.swift")
assert any("deinit" in l for l in _labels(r))
def test_swift_finds_subscript():
r = extract_swift(FIXTURES / "sample.swift")
assert any("subscript" in l for l in _labels(r))
def test_swift_extension_methods_attach_to_type():
r = extract_swift(FIXTURES / "sample.swift")
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
method_edges = [e for e in r["edges"] if e["relation"] == "method"]
found = False
for e in method_edges:
src_label = node_by_id.get(e["source"], "")
tgt_label = node_by_id.get(e["target"], "")
if "Config" in src_label and "isValid" in tgt_label:
found = True
break
assert found, "extension method isValid should attach to Config"
def test_swift_extension_does_not_duplicate_type_node():
r = extract_swift(FIXTURES / "sample.swift")
config_nodes = [n for n in r["nodes"] if n["label"] == "Config"]
assert len(config_nodes) == 1, f"Config should appear once, got {len(config_nodes)}"
def test_swift_conformance_edge():
r = extract_swift(FIXTURES / "sample.swift")
inherits_edges = [e for e in r["edges"] if e["relation"] == "inherits"]
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
found = False
for e in inherits_edges:
src_label = node_by_id.get(e["source"], "")
tgt_label = node_by_id.get(e["target"], "")
if "DataProcessor" in src_label and "Processor" in tgt_label:
found = True
break
assert found, "DataProcessor should have inherits edge to Processor"
def test_swift_extension_conformance_edge():
r = extract_swift(FIXTURES / "sample.swift")
inherits_edges = [e for e in r["edges"] if e["relation"] == "inherits"]
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
found = False
for e in inherits_edges:
src_label = node_by_id.get(e["source"], "")
tgt_label = node_by_id.get(e["target"], "")
if "DataProcessor" in src_label and "Loggable" in tgt_label:
found = True
break
assert found, "extension should add conformance edge DataProcessor -> Loggable"
def test_swift_emits_calls():
r = extract_swift(FIXTURES / "sample.swift")
calls = _calls(r)
assert any("process" in src and "validate" in tgt for src, tgt in calls)
# ── Elixir ────────────────────────────────────────────────────────────────────
from graphify.extract import extract_elixir
def test_elixir_finds_module():
r = extract_elixir(FIXTURES / "sample.ex")
assert "error" not in r
labels = [n["label"] for n in r["nodes"]]
assert any("MyApp.Accounts.User" in l for l in labels)
def test_elixir_finds_functions():
r = extract_elixir(FIXTURES / "sample.ex")
labels = [n["label"] for n in r["nodes"]]
assert any("create" in l for l in labels)
assert any("find" in l for l in labels)
assert any("validate" in l for l in labels)
def test_elixir_finds_imports():
r = extract_elixir(FIXTURES / "sample.ex")
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
assert len(import_edges) >= 2
def test_elixir_finds_calls():
r = extract_elixir(FIXTURES / "sample.ex")
calls = {(e["source"], e["target"]) for e in r["edges"] if e["relation"] == "calls"}
labels = {n["id"]: n["label"] for n in r["nodes"]}
assert any("create" in labels.get(src, "") and "validate" in labels.get(tgt, "") for src, tgt in calls)
def test_elixir_method_edges():
r = extract_elixir(FIXTURES / "sample.ex")
methods = [e for e in r["edges"] if e["relation"] == "method"]
assert len(methods) >= 3
# ── Objective-C ──────────────────────────────────────────────────────────────
from graphify.extract import extract_objc
def test_objc_finds_interface():
r = extract_objc(FIXTURES / "sample.m")
labels = [n["label"] for n in r["nodes"]]
assert "Animal" in labels
def test_objc_finds_subclass():
r = extract_objc(FIXTURES / "sample.m")
labels = [n["label"] for n in r["nodes"]]
assert "Dog" in labels
def test_objc_finds_methods():
r = extract_objc(FIXTURES / "sample.m")
labels = [n["label"] for n in r["nodes"]]
assert any("speak" in l or "fetch" in l or "initWithName" in l for l in labels)
def test_objc_finds_imports():
r = extract_objc(FIXTURES / "sample.m")
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
assert len(import_edges) >= 1
def test_objc_inherits_edge():
r = extract_objc(FIXTURES / "sample.m")
inherits = [e for e in r["edges"] if e["relation"] == "inherits"]
assert len(inherits) >= 1
def test_objc_no_dangling_edges():
r = extract_objc(FIXTURES / "sample.m")
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids, f"Dangling source: {e}"
# ---------------------------------------------------------------------------
# Go
# ---------------------------------------------------------------------------
def test_go_receiver_methods_share_type_node():
"""Methods on the same receiver type must share one canonical type node."""
r = extract_go(FIXTURES / "sample.go")
server_nodes = [n for n in r["nodes"] if n["label"] == "Server"]
# Both Start() and Stop() are on *Server — should produce exactly one Server node
assert len(server_nodes) == 1
def test_go_receiver_uses_pkg_scope():
"""Type node id should be scoped to directory, not file stem."""
r = extract_go(FIXTURES / "sample.go")
server_nodes = [n for n in r["nodes"] if n["label"] == "Server"]
assert server_nodes
# Should NOT contain the file stem "sample" in the type node id
assert "sample" not in server_nodes[0]["id"].split(":")[0]
# ---------------------------------------------------------------------------
# Julia
# ---------------------------------------------------------------------------
def test_julia_finds_module():
r = extract_julia(FIXTURES / "sample.jl")
labels = [n["label"] for n in r["nodes"]]
assert "Geometry" in labels
def test_julia_finds_structs():
r = extract_julia(FIXTURES / "sample.jl")
labels = [n["label"] for n in r["nodes"]]
assert "Point" in labels
assert "Circle" in labels
def test_julia_finds_abstract_type():
r = extract_julia(FIXTURES / "sample.jl")
labels = [n["label"] for n in r["nodes"]]
assert "Shape" in labels
def test_julia_finds_functions():
r = extract_julia(FIXTURES / "sample.jl")
labels = [n["label"] for n in r["nodes"]]
assert any("area" in l for l in labels)
assert any("distance" in l for l in labels)
def test_julia_finds_short_function():
r = extract_julia(FIXTURES / "sample.jl")
labels = [n["label"] for n in r["nodes"]]
assert any("perimeter" in l for l in labels)
def test_julia_finds_imports():
r = extract_julia(FIXTURES / "sample.jl")
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
assert len(import_edges) >= 1
def test_julia_finds_inherits():
r = extract_julia(FIXTURES / "sample.jl")
inherits = [e for e in r["edges"] if e["relation"] == "inherits"]
assert len(inherits) >= 1
def test_julia_finds_calls():
r = extract_julia(FIXTURES / "sample.jl")
call_edges = [e for e in r["edges"] if e["relation"] == "calls"]
assert len(call_edges) >= 1
def test_julia_no_dangling_edges():
r = extract_julia(FIXTURES / "sample.jl")
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids, f"Dangling source: {e}"
+6 -6
View File
@@ -47,11 +47,11 @@ def test_ts_emits_calls():
# .post() calls .get()
assert any("post" in src and "get" in tgt for src, tgt in calls)
def test_ts_calls_are_inferred():
def test_ts_calls_are_extracted():
r = extract_js(FIXTURES / "sample.ts")
for e in r["edges"]:
if e["relation"] == "calls":
assert e["confidence"] == "INFERRED"
assert e["confidence"] == "EXTRACTED"
def test_ts_no_dangling_edges():
r = extract_js(FIXTURES / "sample.ts")
@@ -83,9 +83,9 @@ def test_go_emits_calls():
# main() calls NewServer and Start
assert len(_call_pairs(r)) > 0
def test_go_has_inferred_calls():
def test_go_has_extracted_calls():
r = extract_go(FIXTURES / "sample.go")
assert "INFERRED" in _confidences(r)
assert "EXTRACTED" in _confidences(r)
def test_go_no_dangling_edges():
r = extract_go(FIXTURES / "sample.go")
@@ -117,11 +117,11 @@ def test_rust_emits_calls():
calls = _call_pairs(r)
assert any("build_graph" in src for src, _ in calls)
def test_rust_calls_are_inferred():
def test_rust_calls_are_extracted():
r = extract_rust(FIXTURES / "sample.rs")
for e in r["edges"]:
if e["relation"] == "calls":
assert e["confidence"] == "INFERRED"
assert e["confidence"] == "EXTRACTED"
def test_rust_no_dangling_edges():
r = extract_rust(FIXTURES / "sample.rs")
+158
View File
@@ -0,0 +1,158 @@
"""
End-to-end pipeline test: detect → extract → build → cluster → analyze → report → export.
Uses the existing test fixtures (code + markdown). No LLM calls - AST extraction only.
Catches regressions in how modules connect, not just individual module behaviour.
"""
import json
import tempfile
from pathlib import Path
import pytest
from graphify.detect import detect
from graphify.extract import collect_files, extract
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json, to_html, to_obsidian
FIXTURES = Path(__file__).parent / "fixtures"
def run_pipeline(tmp_path: Path) -> dict:
"""Run the full pipeline on the fixtures directory. Returns a dict of outputs."""
# Step 1: detect
detection = detect(FIXTURES)
assert detection["total_files"] > 0
# fixtures corpus is intentionally small (< 5k words), so needs_graph may be False
assert "files" in detection
# Step 2: extract (AST only - no LLM)
code_files = [Path(f) for f in detection["files"].get("code", [])]
assert len(code_files) > 0
extraction = extract(code_files)
assert len(extraction["nodes"]) > 0
assert len(extraction["edges"]) > 0
# Step 3: build
G = build_from_json(extraction)
assert G.number_of_nodes() > 0
assert G.number_of_edges() > 0
# Step 4: cluster
communities = cluster(G)
assert len(communities) > 0
cohesion = score_all(G, communities)
assert len(cohesion) == len(communities)
for score in cohesion.values():
assert 0.0 <= score <= 1.0
# Step 5: analyze
gods = god_nodes(G)
assert len(gods) > 0
assert all("id" in g and "degree" in g for g in gods)
surprises = surprising_connections(G, communities)
assert isinstance(surprises, list)
labels = {cid: f"Group {cid}" for cid in communities}
questions = suggest_questions(G, communities, labels)
assert isinstance(questions, list)
# Step 6: report
tokens = {"input": 0, "output": 0}
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, str(FIXTURES), suggested_questions=questions)
assert "God Nodes" in report
assert "Communities" in report
assert len(report) > 100
# Step 7: export - JSON
json_path = tmp_path / "graph.json"
to_json(G, communities, str(json_path))
assert json_path.exists()
data = json.loads(json_path.read_text())
assert "nodes" in data and "links" in data
assert all("community" in n for n in data["nodes"])
# Step 8: export - HTML
html_path = tmp_path / "graph.html"
to_html(G, communities, str(html_path), community_labels=labels)
assert html_path.exists()
html = html_path.read_text()
assert "vis-network" in html
assert "RAW_NODES" in html
# Step 9: export - Obsidian vault
vault_path = tmp_path / "obsidian"
n_notes = to_obsidian(G, communities, str(vault_path), community_labels=labels, cohesion=cohesion)
assert n_notes > 0
assert (vault_path / ".obsidian" / "graph.json").exists()
md_files = list(vault_path.glob("*.md"))
assert len(md_files) > 0
return {
"detection": detection,
"extraction": extraction,
"graph": G,
"communities": communities,
"cohesion": cohesion,
"gods": gods,
"surprises": surprises,
"questions": questions,
"report": report,
}
def test_pipeline_runs_end_to_end(tmp_path):
result = run_pipeline(tmp_path)
assert result["graph"].number_of_nodes() > 0
def test_pipeline_graph_has_edges(tmp_path):
result = run_pipeline(tmp_path)
assert result["graph"].number_of_edges() > 0
def test_pipeline_all_nodes_have_community(tmp_path):
result = run_pipeline(tmp_path)
G = result["graph"]
communities = result["communities"]
all_community_nodes = {n for nodes in communities.values() for n in nodes}
for node in G.nodes():
assert node in all_community_nodes, f"Node {node!r} has no community"
def test_pipeline_report_mentions_top_god_node(tmp_path):
result = run_pipeline(tmp_path)
top_god = result["gods"][0]["label"]
assert top_god in result["report"]
def test_pipeline_detection_finds_code_and_docs(tmp_path):
result = run_pipeline(tmp_path)
assert len(result["detection"]["files"].get("code", [])) > 0
assert len(result["detection"]["files"].get("document", [])) > 0
def test_pipeline_incremental_update(tmp_path):
"""Second run on unchanged corpus should produce identical node/edge counts."""
result1 = run_pipeline(tmp_path)
result2 = run_pipeline(tmp_path)
assert result1["graph"].number_of_nodes() == result2["graph"].number_of_nodes()
assert result1["graph"].number_of_edges() == result2["graph"].number_of_edges()
def test_pipeline_extraction_confidence_labels(tmp_path):
result = run_pipeline(tmp_path)
extraction = result["extraction"]
valid = {"EXTRACTED", "INFERRED", "AMBIGUOUS"}
for edge in extraction["edges"]:
assert edge["confidence"] in valid, f"Invalid confidence: {edge['confidence']}"
def test_pipeline_no_self_loops(tmp_path):
result = run_pipeline(tmp_path)
G = result["graph"]
for u, v in G.edges():
assert u != v, f"Self-loop found on node {u!r}"
+89
View File
@@ -0,0 +1,89 @@
"""Tests for rationale/docstring extraction in extract.py."""
import textwrap
from pathlib import Path
import pytest
from graphify.extract import extract_python
def _write_py(tmp_path: Path, code: str) -> Path:
p = tmp_path / "sample.py"
p.write_text(textwrap.dedent(code))
return p
def test_module_docstring_extracted(tmp_path):
path = _write_py(tmp_path, '''
"""This module handles authentication because legacy sessions were insecure."""
def login(): pass
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
assert len(rationale) >= 1
assert any("authentication" in n["label"] for n in rationale)
def test_function_docstring_extracted(tmp_path):
path = _write_py(tmp_path, '''
def process():
"""We use chunked processing here because the full dataset exceeds RAM."""
pass
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
assert any("chunked" in n["label"] for n in rationale)
def test_class_docstring_extracted(tmp_path):
path = _write_py(tmp_path, '''
class Cache:
"""Chosen over Redis because we need zero external dependencies in the test env."""
pass
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
assert any("Redis" in n["label"] for n in rationale)
def test_rationale_comment_extracted(tmp_path):
path = _write_py(tmp_path, '''
def build():
# NOTE: must run before compile() or linker will fail
pass
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
assert any("NOTE" in n["label"] for n in rationale)
def test_rationale_for_edges_present(tmp_path):
path = _write_py(tmp_path, '''
"""Module docstring explaining the why."""
def foo():
"""Function docstring with rationale."""
pass
''')
result = extract_python(path)
rationale_edges = [e for e in result["edges"] if e.get("relation") == "rationale_for"]
assert len(rationale_edges) >= 1
def test_short_docstring_ignored(tmp_path):
"""Trivial docstrings under 20 chars should not become rationale nodes."""
path = _write_py(tmp_path, '''
def foo():
"""Constructor."""
pass
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
assert len(rationale) == 0
def test_rationale_confidence_is_extracted(tmp_path):
path = _write_py(tmp_path, '''
"""This module exists because we needed a standalone parser."""
def parse(): pass
''')
result = extract_python(path)
rationale_edges = [e for e in result["edges"] if e.get("relation") == "rationale_for"]
assert all(e.get("confidence") == "EXTRACTED" for e in rationale_edges)
+12 -10
View File
@@ -1,4 +1,4 @@
"""Tests for graphify/security.py — URL validation, safe fetch, path guards, label sanitisation."""
"""Tests for graphify/security.py - URL validation, safe fetch, path guards, label sanitisation."""
from __future__ import annotations
import json
@@ -47,7 +47,7 @@ def test_validate_url_rejects_empty_scheme():
# ---------------------------------------------------------------------------
# safe_fetch — scheme and redirect guards (mocked network)
# safe_fetch - scheme and redirect guards (mocked network)
# ---------------------------------------------------------------------------
def _make_mock_response(content: bytes, status: int = 200):
@@ -138,7 +138,7 @@ def test_safe_fetch_text_replaces_bad_bytes():
# ---------------------------------------------------------------------------
def test_validate_graph_path_allows_inside_base(tmp_path):
base = tmp_path / ".graphify"
base = tmp_path / "graphify-out"
base.mkdir()
graph = base / "graph.json"
graph.write_text("{}")
@@ -146,19 +146,19 @@ def test_validate_graph_path_allows_inside_base(tmp_path):
assert result == graph.resolve()
def test_validate_graph_path_blocks_traversal(tmp_path):
base = tmp_path / ".graphify"
base = tmp_path / "graphify-out"
base.mkdir()
evil = tmp_path / ".graphify" / ".." / "etc_passwd"
evil = tmp_path / "graphify-out" / ".." / "etc_passwd"
with pytest.raises(ValueError, match="escapes"):
validate_graph_path(str(evil), base=base)
def test_validate_graph_path_requires_base_exists(tmp_path):
base = tmp_path / ".graphify" # not created
base = tmp_path / "graphify-out" # not created
with pytest.raises(ValueError, match="does not exist"):
validate_graph_path(str(base / "graph.json"), base=base)
def test_validate_graph_path_raises_if_file_missing(tmp_path):
base = tmp_path / ".graphify"
base = tmp_path / "graphify-out"
base.mkdir()
with pytest.raises(FileNotFoundError):
validate_graph_path(str(base / "missing.json"), base=base)
@@ -168,9 +168,11 @@ def test_validate_graph_path_raises_if_file_missing(tmp_path):
# sanitize_label
# ---------------------------------------------------------------------------
def test_sanitize_label_escapes_html():
assert "&lt;script&gt;" in sanitize_label("<script>")
assert "&amp;" in sanitize_label("foo & bar")
def test_sanitize_label_passthrough_html_chars():
# sanitize_label does NOT HTML-escape — callers that inject into HTML must
# wrap with html.escape() themselves (e.g. the title in to_html())
assert sanitize_label("<script>") == "<script>"
assert sanitize_label("foo & bar") == "foo & bar"
def test_sanitize_label_strips_control_chars():
result = sanitize_label("hello\x00\x1fworld")
+194
View File
@@ -0,0 +1,194 @@
"""Tests for semantically_similar_to edge support."""
import networkx as nx
import pytest
from graphify.build import build_from_json
from graphify.analyze import surprising_connections, _surprise_score
from graphify.report import generate
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_extraction_with_semantic_edge():
"""Two nodes in separate files connected by a semantically_similar_to edge."""
return {
"nodes": [
{"id": "a_validate_input", "label": "validate_input", "file_type": "code",
"source_file": "auth/validators.py", "source_location": "L5"},
{"id": "b_check_input", "label": "check_input", "file_type": "code",
"source_file": "api/checks.py", "source_location": "L12"},
],
"edges": [
{
"source": "a_validate_input",
"target": "b_check_input",
"relation": "semantically_similar_to",
"confidence": "INFERRED",
"confidence_score": 0.82,
"source_file": "auth/validators.py",
"source_location": None,
"weight": 0.82,
}
],
"input_tokens": 100,
"output_tokens": 50,
}
def _make_graph_with_semantic_edge():
return build_from_json(_make_extraction_with_semantic_edge())
def _make_two_edge_graph():
"""Graph with one semantically_similar_to edge and one references edge, both cross-file."""
G = nx.Graph()
for nid, label, src in [
("a", "ValidateInput", "auth/validators.py"),
("b", "CheckInput", "api/checks.py"),
("c", "LoadConfig", "config/loader.py"),
("d", "ReadConfig", "utils/reader.py"),
]:
G.add_node(nid, label=label, source_file=src, file_type="code")
# semantically_similar_to edge
G.add_edge("a", "b", relation="semantically_similar_to", confidence="INFERRED",
confidence_score=0.82, source_file="auth/validators.py", weight=0.82,
_src="a", _tgt="b")
# plain references edge (same confidence tier)
G.add_edge("c", "d", relation="references", confidence="INFERRED",
confidence_score=0.7, source_file="config/loader.py", weight=0.7,
_src="c", _tgt="d")
return G
# ---------------------------------------------------------------------------
# Test 1: semantically_similar_to passes through build_from_json without being dropped
# ---------------------------------------------------------------------------
def test_semantic_edge_survives_build_from_json():
G = _make_graph_with_semantic_edge()
assert G.number_of_edges() == 1
u, v, data = next(iter(G.edges(data=True)))
assert data["relation"] == "semantically_similar_to"
def test_semantic_edge_nodes_present():
G = _make_graph_with_semantic_edge()
assert "a_validate_input" in G.nodes
assert "b_check_input" in G.nodes
# ---------------------------------------------------------------------------
# Test 2: confidence_score is preserved for semantically_similar_to edges
# ---------------------------------------------------------------------------
def test_semantic_edge_confidence_score_preserved():
G = _make_graph_with_semantic_edge()
u, v, data = next(iter(G.edges(data=True)))
assert data.get("confidence_score") == pytest.approx(0.82)
assert data.get("confidence") == "INFERRED"
# ---------------------------------------------------------------------------
# Test 3: surprising_connections scores semantically_similar_to edges higher
# than references edges with the same community membership
# ---------------------------------------------------------------------------
def test_semantic_edge_scores_higher_than_references():
G = _make_two_edge_graph()
communities = {0: ["a", "b"], 1: ["c", "d"]}
node_community = {"a": 0, "b": 0, "c": 1, "d": 1}
score_sem, reasons_sem = _surprise_score(
G, "a", "b", G.edges["a", "b"], node_community,
"auth/validators.py", "api/checks.py"
)
score_ref, _ = _surprise_score(
G, "c", "d", G.edges["c", "d"], node_community,
"config/loader.py", "utils/reader.py"
)
assert score_sem > score_ref
def test_semantic_edge_reason_mentions_similarity():
G = _make_two_edge_graph()
communities = {0: ["a", "b"], 1: ["c", "d"]}
node_community = {"a": 0, "b": 0, "c": 1, "d": 1}
_, reasons = _surprise_score(
G, "a", "b", G.edges["a", "b"], node_community,
"auth/validators.py", "api/checks.py"
)
assert any("similar" in r for r in reasons)
# ---------------------------------------------------------------------------
# Test 4: report renders [semantically similar] tag for these edges
# ---------------------------------------------------------------------------
def _make_report_with_semantic_surprise():
G = _make_graph_with_semantic_edge()
communities = {0: ["a_validate_input", "b_check_input"]}
cohesion = {0: 0.5}
labels = {0: "Validators"}
gods = []
surprises = [
{
"source": "validate_input",
"target": "check_input",
"relation": "semantically_similar_to",
"confidence": "INFERRED",
"confidence_score": 0.82,
"source_files": ["auth/validators.py", "api/checks.py"],
"why": "semantically similar concepts with no structural link",
}
]
detection = {"total_files": 2, "total_words": 500, "needs_graph": True, "warning": None}
tokens = {"input": 100, "output": 50}
return generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, "./project")
def test_report_renders_semantically_similar_tag():
report = _make_report_with_semantic_surprise()
assert "[semantically similar]" in report
def test_report_semantic_tag_on_correct_line():
report = _make_report_with_semantic_surprise()
for line in report.splitlines():
if "semantically_similar_to" in line:
assert "[semantically similar]" in line
break
else:
pytest.fail("No line with semantically_similar_to found in report")
def test_report_no_semantic_tag_for_other_relations():
"""Non-semantic edges must not get the [semantically similar] tag."""
G = nx.Graph()
for nid, label, src in [
("x", "Alpha", "repo1/a.py"),
("y", "Beta", "repo2/b.py"),
]:
G.add_node(nid, label=label, source_file=src, file_type="code")
G.add_edge("x", "y", relation="references", confidence="EXTRACTED",
confidence_score=1.0, source_file="repo1/a.py", weight=1.0)
communities = {0: ["x", "y"]}
cohesion = {0: 0.5}
labels = {0: "Misc"}
gods = []
surprises = [
{
"source": "Alpha",
"target": "Beta",
"relation": "references",
"confidence": "EXTRACTED",
"source_files": ["repo1/a.py", "repo2/b.py"],
"why": "cross-file connection",
}
]
detection = {"total_files": 2, "total_words": 200, "needs_graph": True, "warning": None}
tokens = {"input": 50, "output": 25}
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, "./project")
assert "[semantically similar]" not in report
+4 -7
View File
@@ -1,4 +1,4 @@
"""Tests for serve.py — MCP graph query helpers (no mcp package required)."""
"""Tests for serve.py - MCP graph query helpers (no mcp package required)."""
import json
import pytest
import networkx as nx
@@ -67,7 +67,7 @@ def test_score_nodes_no_match():
def test_score_nodes_source_file_partial():
G = _make_graph()
# "cluster.py" contains "cluster" — should score 0.5 for source match
# "cluster.py" contains "cluster" - should score 0.5 for source match
scored = _score_nodes(G, ["cluster"])
nids = [nid for _, nid in scored]
assert "n2" in nids
@@ -138,19 +138,16 @@ def test_subgraph_to_text_edge_included():
# --- _load_graph ---
def test_load_graph_roundtrip(tmp_path):
from unittest.mock import patch
G = _make_graph()
data = json_graph.node_link_data(G, edges="links")
p = tmp_path / "graph.json"
p.write_text(json.dumps(data))
# validate_graph_path is tested separately; here we test parse correctness
with patch("graphify.serve.validate_graph_path", return_value=p):
G2 = _load_graph(str(p))
G2 = _load_graph(str(p))
assert G2.number_of_nodes() == G.number_of_nodes()
assert G2.number_of_edges() == G.number_of_edges()
def test_load_graph_missing_file(tmp_path):
graphify_dir = tmp_path / ".graphify"
graphify_dir = tmp_path / "graphify-out"
graphify_dir.mkdir()
with pytest.raises(SystemExit):
_load_graph(str(graphify_dir / "nonexistent.json"))
+147
View File
@@ -0,0 +1,147 @@
"""Tests for graphify.transcribe — video/audio transcription support."""
from __future__ import annotations
import os
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from graphify.transcribe import (
VIDEO_EXTENSIONS,
build_whisper_prompt,
transcribe,
transcribe_all,
)
# ---------------------------------------------------------------------------
# VIDEO_EXTENSIONS
# ---------------------------------------------------------------------------
def test_video_extensions_set():
assert ".mp4" in VIDEO_EXTENSIONS
assert ".mp3" in VIDEO_EXTENSIONS
assert ".wav" in VIDEO_EXTENSIONS
assert ".mov" in VIDEO_EXTENSIONS
assert ".py" not in VIDEO_EXTENSIONS
# ---------------------------------------------------------------------------
# build_whisper_prompt
# ---------------------------------------------------------------------------
def test_build_whisper_prompt_no_nodes():
"""Empty god_nodes returns fallback prompt."""
prompt = build_whisper_prompt([])
assert "punctuation" in prompt.lower() or len(prompt) > 0
def test_build_whisper_prompt_env_override(monkeypatch):
"""GRAPHIFY_WHISPER_PROMPT env var short-circuits LLM call."""
monkeypatch.setenv("GRAPHIFY_WHISPER_PROMPT", "Custom domain hint.")
prompt = build_whisper_prompt([{"label": "Python"}, {"label": "FastAPI"}])
assert prompt == "Custom domain hint."
def test_build_whisper_prompt_returns_topic_string():
"""Returns a topic-based prompt from god node labels — no LLM call."""
god_nodes = [{"label": "neural networks"}, {"label": "transformers"}, {"label": "attention"}]
with patch.dict(os.environ, {}, clear=False):
os.environ.pop("GRAPHIFY_WHISPER_PROMPT", None)
prompt = build_whisper_prompt(god_nodes)
assert "neural networks" in prompt.lower() or "transformers" in prompt.lower()
assert "punctuation" in prompt.lower()
def test_build_whisper_prompt_nodes_without_labels():
"""Nodes missing 'label' keys are safely skipped."""
god_nodes = [{"id": "1"}, {"id": "2", "label": ""}]
prompt = build_whisper_prompt(god_nodes)
assert len(prompt) > 0
# ---------------------------------------------------------------------------
# transcribe
# ---------------------------------------------------------------------------
def test_transcribe_uses_cache(tmp_path):
"""If transcript already exists, transcribe() returns cached path without running Whisper."""
video = tmp_path / "lecture.mp4"
video.write_bytes(b"fake")
out_dir = tmp_path / "transcripts"
out_dir.mkdir()
cached = out_dir / "lecture.txt"
cached.write_text("Cached transcript content.")
result = transcribe(video, output_dir=out_dir)
assert result == cached
def test_transcribe_force_reruns(tmp_path):
"""force=True re-transcribes even when cache exists."""
video = tmp_path / "talk.mp4"
video.write_bytes(b"fake")
out_dir = tmp_path / "transcripts"
out_dir.mkdir()
(out_dir / "talk.txt").write_text("Old transcript.")
fake_segment = MagicMock()
fake_segment.text = "New transcript segment."
fake_info = MagicMock()
fake_info.language = "en"
fake_model = MagicMock()
fake_model.transcribe.return_value = ([fake_segment], fake_info)
with patch("graphify.transcribe._get_whisper", return_value=lambda *a, **kw: fake_model):
result = transcribe(video, output_dir=out_dir, force=True)
assert result.read_text() == "New transcript segment."
def test_transcribe_missing_faster_whisper(tmp_path):
"""ImportError propagates when faster_whisper is not installed."""
video = tmp_path / "clip.mp4"
video.write_bytes(b"fake")
with patch("graphify.transcribe._get_whisper", side_effect=ImportError("faster-whisper not installed")):
with pytest.raises(ImportError):
transcribe(video, output_dir=tmp_path / "out")
# ---------------------------------------------------------------------------
# transcribe_all
# ---------------------------------------------------------------------------
def test_transcribe_all_empty():
"""Empty input returns empty list without error."""
assert transcribe_all([]) == []
def test_transcribe_all_uses_cache(tmp_path):
"""transcribe_all() returns cached paths for already-transcribed files."""
video = tmp_path / "lecture.mp4"
video.write_bytes(b"fake")
out_dir = tmp_path / "transcripts"
out_dir.mkdir()
cached = out_dir / "lecture.txt"
cached.write_text("Cached.")
results = transcribe_all([str(video)], output_dir=out_dir)
assert len(results) == 1
assert str(cached) in results[0]
def test_transcribe_all_skips_failed(tmp_path):
"""transcribe_all() warns and skips files that fail to transcribe."""
video = tmp_path / "broken.mp4"
video.write_bytes(b"fake")
def raise_import(*args, **kwargs):
raise ImportError("faster_whisper not installed")
with patch("graphify.transcribe.transcribe", side_effect=RuntimeError("boom")):
results = transcribe_all([str(video)], output_dir=tmp_path / "out")
assert results == []
+15 -15
View File
@@ -1,29 +1,29 @@
"""Tests for watch.py — file watcher helpers (no watchdog required)."""
"""Tests for watch.py - file watcher helpers (no watchdog required)."""
import time
from pathlib import Path
import pytest
from graphify.watch import _run_update, _WATCHED_EXTENSIONS
from graphify.watch import _notify_only, _WATCHED_EXTENSIONS
# --- _run_update ---
# --- _notify_only ---
def test_run_update_creates_flag(tmp_path):
_run_update(tmp_path)
flag = tmp_path / ".graphify" / "needs_update"
def test_notify_only_creates_flag(tmp_path):
_notify_only(tmp_path)
flag = tmp_path / "graphify-out" / "needs_update"
assert flag.exists()
assert flag.read_text() == "1"
def test_run_update_creates_flag_dir(tmp_path):
# .graphify dir does not exist yet
assert not (tmp_path / ".graphify").exists()
_run_update(tmp_path)
assert (tmp_path / ".graphify").is_dir()
def test_notify_only_creates_flag_dir(tmp_path):
# graphify-out dir does not exist yet
assert not (tmp_path / "graphify-out").exists()
_notify_only(tmp_path)
assert (tmp_path / "graphify-out").is_dir()
def test_run_update_idempotent(tmp_path):
_run_update(tmp_path)
_run_update(tmp_path)
flag = tmp_path / ".graphify" / "needs_update"
def test_notify_only_idempotent(tmp_path):
_notify_only(tmp_path)
_notify_only(tmp_path)
flag = tmp_path / "graphify-out" / "needs_update"
assert flag.read_text() == "1"
+139
View File
@@ -0,0 +1,139 @@
"""Tests for graphify.wiki — Wikipedia-style article generation."""
import pytest
from pathlib import Path
import networkx as nx
from graphify.wiki import to_wiki, _index_md, _community_article, _god_node_article
def _make_graph():
G = nx.Graph()
G.add_node("n1", label="parse", file_type="code", source_file="parser.py", community=0)
G.add_node("n2", label="validate", file_type="code", source_file="parser.py", community=0)
G.add_node("n3", label="render", file_type="code", source_file="renderer.py", community=1)
G.add_node("n4", label="stream", file_type="code", source_file="renderer.py", community=1)
G.add_edge("n1", "n2", relation="calls", confidence="EXTRACTED", weight=1.0)
G.add_edge("n1", "n3", relation="references", confidence="INFERRED", weight=1.0)
G.add_edge("n3", "n4", relation="calls", confidence="EXTRACTED", weight=1.0)
return G
COMMUNITIES = {0: ["n1", "n2"], 1: ["n3", "n4"]}
LABELS = {0: "Parsing Layer", 1: "Rendering Layer"}
COHESION = {0: 0.85, 1: 0.72}
GOD_NODES = [{"id": "n1", "label": "parse", "degree": 2}]
def test_to_wiki_writes_index(tmp_path):
G = _make_graph()
n = to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, cohesion=COHESION, god_nodes_data=GOD_NODES)
assert (tmp_path / "index.md").exists()
def test_to_wiki_returns_article_count(tmp_path):
G = _make_graph()
# 2 communities + 1 god node = 3
n = to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, cohesion=COHESION, god_nodes_data=GOD_NODES)
assert n == 3
def test_to_wiki_community_articles_created(tmp_path):
G = _make_graph()
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS)
assert (tmp_path / "Parsing_Layer.md").exists()
assert (tmp_path / "Rendering_Layer.md").exists()
def test_to_wiki_god_node_article_created(tmp_path):
G = _make_graph()
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, god_nodes_data=GOD_NODES)
assert (tmp_path / "parse.md").exists()
def test_index_links_all_communities(tmp_path):
G = _make_graph()
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS)
index = (tmp_path / "index.md").read_text()
assert "[[Parsing Layer]]" in index
assert "[[Rendering Layer]]" in index
def test_index_lists_god_nodes(tmp_path):
G = _make_graph()
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, god_nodes_data=GOD_NODES)
index = (tmp_path / "index.md").read_text()
assert "[[parse]]" in index
assert "2 connections" in index
def test_community_article_has_cross_links(tmp_path):
G = _make_graph()
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS)
parsing = (tmp_path / "Parsing_Layer.md").read_text()
# n1 (parsing) references n3 (rendering) → cross-community link
assert "[[Rendering Layer]]" in parsing
def test_community_article_shows_cohesion(tmp_path):
G = _make_graph()
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, cohesion=COHESION)
parsing = (tmp_path / "Parsing_Layer.md").read_text()
assert "cohesion 0.85" in parsing
def test_community_article_has_audit_trail(tmp_path):
G = _make_graph()
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS)
parsing = (tmp_path / "Parsing_Layer.md").read_text()
assert "EXTRACTED" in parsing
assert "INFERRED" in parsing
def test_god_node_article_has_connections(tmp_path):
G = _make_graph()
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, god_nodes_data=GOD_NODES)
article = (tmp_path / "parse.md").read_text()
assert "[[validate]]" in article or "[[render]]" in article
def test_god_node_article_links_community(tmp_path):
G = _make_graph()
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, god_nodes_data=GOD_NODES)
article = (tmp_path / "parse.md").read_text()
assert "[[Parsing Layer]]" in article
def test_to_wiki_skips_missing_god_node_ids(tmp_path):
"""God node with bad ID should not crash."""
G = _make_graph()
bad_gods = [{"id": "nonexistent", "label": "ghost", "degree": 99}]
n = to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS, god_nodes_data=bad_gods)
# 2 communities + 0 god nodes (nonexistent skipped) = 2
assert n == 2
def test_to_wiki_no_labels_uses_fallback(tmp_path):
G = _make_graph()
to_wiki(G, COMMUNITIES, tmp_path) # no labels
assert (tmp_path / "Community_0.md").exists()
assert (tmp_path / "Community_1.md").exists()
def test_article_navigation_footer(tmp_path):
G = _make_graph()
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS)
article = (tmp_path / "Parsing_Layer.md").read_text()
assert "[[index]]" in article
def test_community_article_truncation_notice(tmp_path):
"""Communities with more than 25 nodes show a truncation notice."""
G = nx.Graph()
nodes = [f"n{i}" for i in range(30)]
for nid in nodes:
G.add_node(nid, label=f"concept_{nid}", file_type="code", source_file="a.py", community=0)
for i in range(len(nodes) - 1):
G.add_edge(nodes[i], nodes[i + 1], relation="calls", confidence="EXTRACTED", weight=1.0)
communities = {0: nodes}
to_wiki(G, communities, tmp_path, community_labels={0: "Big Community"})
article = (tmp_path / "Big_Community.md").read_text()
assert "and 5 more nodes" in article
+56
View File
@@ -0,0 +1,56 @@
# Reproducible Example
A small document pipeline — parser, validator, processor, storage, API — with architecture notes and research notes. Seven files, two languages, clear call relationships between modules.
Run graphify on it and you get a knowledge graph showing how the modules connect, which functions call which, and how the architecture notes relate to the code.
## Input files
```
raw/
├── parser.py — reads files, detects format, kicks off the pipeline
├── validator.py — schema checks, calls processor for text normalization
├── processor.py — keyword extraction, cross-reference detection
├── storage.py — persists everything, maintains the index
├── api.py — HTTP handlers that orchestrate the above four modules
├── architecture.md — design decisions and module responsibilities
└── notes.md — open questions and tradeoffs
```
## How to run
```bash
pip install graphifyy
graphify install # Claude Code
graphify install --platform codex # Codex
graphify install --platform opencode # OpenCode
graphify install --platform claw # OpenClaw
```
Then open your AI coding assistant in this directory and type:
```
/graphify ./raw
```
No PDF or image extraction — runs entirely on AST and markdown with no token cost for semantic extraction.
## What to expect
- `api.py` as a hub node connected to all four modules
- `storage.py` as the highest-degree god node (everything reads and writes through it)
- `parser.py` calling `validator.py` and `storage.py`
- `architecture.md` and `notes.md` linked to the code modules they discuss
- 2 communities: the four Python modules together, the two markdown files together (or api.py in its own cluster given high connectivity)
## After it runs
Ask questions from your AI coding assistant:
- "what calls storage directly?"
- "what is the shortest path between parser and processor?"
- "which module has the most connections?"
- "what does the architecture doc say about the storage design?"
The graph lives in `graphify-out/` and persists across sessions.
+78
View File
@@ -0,0 +1,78 @@
"""
API module - exposes the document pipeline over HTTP.
Thin layer over parser, validator, processor, and storage.
"""
from parser import batch_parse, parse_file
from validator import validate_document, ValidationError
from processor import process_and_save, enrich_document
from storage import load_record, delete_record, list_records, load_index
def handle_upload(paths: list) -> dict:
"""
Accept a list of file paths, run the full pipeline on each,
and return a summary of what succeeded and what failed.
"""
results = batch_parse(paths)
succeeded = [r for r in results if r["ok"]]
failed = [r for r in results if not r["ok"]]
return {
"uploaded": len(succeeded),
"failed": len(failed),
"ids": [r["id"] for r in succeeded],
"errors": failed,
}
def handle_get(record_id: str) -> dict:
"""Fetch a document by ID and return it."""
try:
return load_record(record_id)
except KeyError:
return {"error": f"Record {record_id} not found"}
def handle_delete(record_id: str) -> dict:
"""Delete a document by ID."""
deleted = delete_record(record_id)
if deleted:
return {"deleted": record_id}
return {"error": f"Record {record_id} not found"}
def handle_list() -> dict:
"""List all document IDs in storage."""
return {"records": list_records()}
def handle_search(query: str) -> dict:
"""
Simple keyword search over the index.
Returns documents whose keyword list overlaps with the query terms.
"""
terms = set(query.lower().split())
index = load_index()
matches = []
for record_id, entry in index.items():
keywords = set(entry.get("keywords", []))
if terms & keywords:
matches.append({
"id": record_id,
"title": entry.get("title", ""),
"matched_keywords": list(terms & keywords),
})
return {"query": query, "results": matches}
def handle_enrich(record_id: str) -> dict:
"""Re-enrich a document to pick up new cross-references."""
try:
doc = load_record(record_id)
except KeyError:
return {"error": f"Record {record_id} not found"}
try:
validated = validate_document(doc)
except ValidationError as e:
return {"error": str(e)}
enriched_id = process_and_save(validated)
return {"enriched": enriched_id}
+37
View File
@@ -0,0 +1,37 @@
# Document Pipeline Architecture
This is a small document ingestion and search system. Files come in, get parsed and validated, keywords get extracted, cross-references get built, and everything ends up queryable via a simple API.
## How data flows
Raw files on disk go through four stages before they are searchable.
**Parsing** reads the file, detects the format (markdown, JSON, plaintext), and converts it into a structured dict. The parser handles each format differently. Markdown gets title, sections, and links extracted. JSON gets loaded directly. Plaintext gets split into paragraphs.
**Validation** checks that the parsed document has the required fields and a known format. It also normalizes text fields (lowercase, trim whitespace, strip control characters) using the processor before the document moves forward.
**Processing** enriches the validated document with a keyword index and cross-references. Cross-references are built by comparing the document's keywords against every other document already in the index. If they share three or more keywords they get linked.
**Storage** persists everything to disk as JSON files and maintains a flat index that maps record IDs to metadata. All other modules read and write through the storage interface so there is one source of truth.
## Module responsibilities
- parser.py: reads files, detects format, calls validate_document and save_parsed
- validator.py: enforces schema, normalizes fields, calls normalize_text from processor
- processor.py: extract_keywords, find_cross_references, calls load_index and save_processed
- storage.py: load_index, save_parsed, save_processed, load_record, delete_record, list_records
- api.py: HTTP handlers that orchestrate the above modules
## Design decisions
The pipeline is intentionally linear. Each stage has one job and calls the next stage explicitly. There is no event bus or dependency injection. This makes the call graph easy to follow and easy to test.
Storage is intentionally simple. A flat JSON index plus one file per document is enough at small scale. If the corpus grows past a few thousand documents this becomes the bottleneck and should be replaced with SQLite or a proper document store.
Cross-reference detection is intentionally naive. Keyword overlap of three is a reasonable threshold for short documents but will produce too many false positives on long ones. A real system would use TF-IDF or embedding similarity instead.
## Extending the pipeline
To add a new file format, add a branch in parser.py's parse_file function and a new parse_* function. The rest of the pipeline does not need to change.
To add a new enrichment step, add a function in processor.py and call it from enrich_document. Store the result in the document dict and add the field to the index in save_processed if you want it searchable.
+39
View File
@@ -0,0 +1,39 @@
# Research Notes
Thoughts and open questions while building the document pipeline. Not polished, just a running log.
## On keyword extraction
The current approach strips stopwords and returns unique tokens. Simple and fast. The problem is it treats all keywords equally. "database" appearing once in a title carries more weight than "database" buried in a paragraph but the code doesn't know that.
TF-IDF would fix this. Term frequency times inverse document frequency gives higher scores to words that are distinctive to a document rather than common across the corpus. Worth switching once the index is big enough for IDF to be meaningful (probably 50+ documents).
Embedding-based similarity is the other option. Run each document through a sentence transformer, store the vector, do nearest-neighbor search at query time. Much better recall but adds a dependency and makes the index opaque. The keyword approach is at least debuggable.
## On cross-reference detection
Three shared keywords is arbitrary. Tuned it by hand on a small test set. On short documents (under 500 words) it produces reasonable results. On long documents everything shares keywords with everything else and the cross-reference graph becomes noise.
A per-document threshold based on document length would be better. Or weight by keyword specificity so rare keywords count more than common ones.
## On storage
Flat files work fine for now. The index fits in memory. Load times are under 10ms for a few hundred documents.
SQLite becomes worth it when you need range queries or you want to update individual fields without rewriting the whole record. The current save_processed rewrites the entire JSON file on every update which is wasteful.
One thing flat files do well: they are easy to inspect. Open the store directory and you can read every document directly. No tooling required. This matters for debugging.
## On the API layer
The API is a thin wrapper. Every handler does one thing: call the right combination of parser, validator, processor, storage. No business logic lives in api.py.
The risk is that this breaks down when you need transactions. Right now parse_and_save in parser.py calls validate_document and save_parsed in sequence. If save_parsed fails after validate_document succeeds you have a partially written record. Not a problem at small scale, becomes a problem under load.
## Open questions
Should validation happen in the parser or as a separate step? Currently it's separate which means the parser can return invalid documents. That feels wrong but keeping them separate makes each module easier to test.
Should cross-references be stored on the document or computed at query time? Storing them is fast to read but goes stale. Computing at query time is always fresh but slow for large indexes.
Is the storage interface the right abstraction? Right now parser, validator, and processor all import from storage directly. A repository pattern would centralize access but adds indirection. Probably not worth it until the storage backend needs to change.
+79
View File
@@ -0,0 +1,79 @@
"""
Parser module - reads raw input documents and converts them into
a structured format the rest of the pipeline can work with.
"""
from validator import validate_document
from storage import save_parsed
SUPPORTED_FORMATS = ["markdown", "plaintext", "json"]
def parse_file(path: str) -> dict:
"""Read a file from disk and return a structured document."""
with open(path, "r") as f:
raw = f.read()
ext = path.rsplit(".", 1)[-1].lower()
if ext == "md":
doc = parse_markdown(raw)
elif ext == "json":
doc = parse_json(raw)
else:
doc = parse_plaintext(raw)
doc["source"] = path
return doc
def parse_markdown(text: str) -> dict:
"""Extract title, sections, and links from markdown."""
lines = text.splitlines()
title = ""
sections = []
links = []
for line in lines:
if line.startswith("# ") and not title:
title = line[2:].strip()
elif line.startswith("## "):
sections.append(line[3:].strip())
elif "](http" in line:
start = line.index("](") + 2
end = line.index(")", start)
links.append(line[start:end])
return {"title": title, "sections": sections, "links": links, "format": "markdown"}
def parse_json(text: str) -> dict:
"""Parse a JSON document into a structured dict."""
import json
data = json.loads(text)
return {"data": data, "format": "json"}
def parse_plaintext(text: str) -> dict:
"""Split plaintext into paragraphs."""
paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
return {"paragraphs": paragraphs, "format": "plaintext"}
def parse_and_save(path: str) -> str:
"""Full pipeline: parse, validate, save. Returns the saved record ID."""
doc = parse_file(path)
validated = validate_document(doc)
record_id = save_parsed(validated)
return record_id
def batch_parse(paths: list) -> list:
"""Parse a list of files and return their record IDs."""
results = []
for path in paths:
try:
rid = parse_and_save(path)
results.append({"path": path, "id": rid, "ok": True})
except Exception as e:
results.append({"path": path, "error": str(e), "ok": False})
return results
+71
View File
@@ -0,0 +1,71 @@
"""
Processor module - transforms validated documents into enriched records
ready for storage and retrieval.
"""
import re
from storage import load_index, save_processed
STOPWORDS = {"the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "for", "of", "with"}
def normalize_text(text: str) -> str:
"""Lowercase, strip extra whitespace, remove control characters."""
text = text.lower().strip()
text = re.sub(r"\s+", " ", text)
text = re.sub(r"[^\x20-\x7e]", "", text)
return text
def extract_keywords(text: str) -> list:
"""Pull non-stopword tokens from text, deduplicated."""
tokens = re.findall(r"\b[a-z]{3,}\b", normalize_text(text))
seen = set()
keywords = []
for t in tokens:
if t not in STOPWORDS and t not in seen:
seen.add(t)
keywords.append(t)
return keywords
def enrich_document(doc: dict) -> dict:
"""Add keyword index and cross-references to a validated document."""
text_blob = " ".join([
doc.get("title", ""),
" ".join(doc.get("sections", [])),
" ".join(doc.get("paragraphs", [])),
])
doc["keywords"] = extract_keywords(text_blob)
doc["cross_refs"] = find_cross_references(doc)
return doc
def find_cross_references(doc: dict) -> list:
"""Look up the index and return IDs of related documents by keyword overlap."""
index = load_index()
keywords = set(doc.get("keywords", []))
refs = []
for record_id, entry in index.items():
other_keywords = set(entry.get("keywords", []))
overlap = keywords & other_keywords
if len(overlap) >= 3:
refs.append({"id": record_id, "shared_keywords": list(overlap)})
return refs
def process_and_save(doc: dict) -> str:
"""Enrich a validated document and persist it. Returns the record ID."""
enriched = enrich_document(doc)
record_id = save_processed(enriched)
return record_id
def reprocess_all() -> int:
"""Re-enrich all records in the index. Returns count of records updated."""
index = load_index()
count = 0
for record_id, doc in index.items():
process_and_save(doc)
count += 1
return count
+89
View File
@@ -0,0 +1,89 @@
"""
Storage module - persists documents to disk and maintains the search index.
All other modules read and write through this interface.
"""
import json
import uuid
from pathlib import Path
STORAGE_DIR = Path(".graphify_store")
INDEX_FILE = STORAGE_DIR / "index.json"
def _ensure_storage() -> None:
STORAGE_DIR.mkdir(exist_ok=True)
if not INDEX_FILE.exists():
INDEX_FILE.write_text(json.dumps({}))
def load_index() -> dict:
"""Load the full document index from disk."""
_ensure_storage()
return json.loads(INDEX_FILE.read_text())
def save_index(index: dict) -> None:
"""Persist the index to disk."""
_ensure_storage()
INDEX_FILE.write_text(json.dumps(index, indent=2))
def save_parsed(doc: dict) -> str:
"""Write a parsed document to storage. Returns the assigned record ID."""
_ensure_storage()
record_id = str(uuid.uuid4())[:8]
path = STORAGE_DIR / f"{record_id}.json"
path.write_text(json.dumps(doc, indent=2))
index = load_index()
index[record_id] = {
"source": doc.get("source", ""),
"format": doc.get("format", ""),
"title": doc.get("title", ""),
}
save_index(index)
return record_id
def save_processed(doc: dict) -> str:
"""Write an enriched document to storage, updating the index with keywords."""
_ensure_storage()
record_id = doc.get("id") or str(uuid.uuid4())[:8]
path = STORAGE_DIR / f"{record_id}_processed.json"
path.write_text(json.dumps(doc, indent=2))
index = load_index()
if record_id not in index:
index[record_id] = {}
index[record_id]["keywords"] = doc.get("keywords", [])
index[record_id]["cross_refs"] = [r["id"] for r in doc.get("cross_refs", [])]
save_index(index)
return record_id
def load_record(record_id: str) -> dict:
"""Fetch a single document by ID."""
_ensure_storage()
path = STORAGE_DIR / f"{record_id}.json"
if not path.exists():
raise KeyError(f"No record found for ID: {record_id}")
return json.loads(path.read_text())
def delete_record(record_id: str) -> bool:
"""Remove a document and its index entry. Returns True if it existed."""
_ensure_storage()
path = STORAGE_DIR / f"{record_id}.json"
if not path.exists():
return False
path.unlink()
index = load_index()
index.pop(record_id, None)
save_index(index)
return True
def list_records() -> list:
"""Return all record IDs currently in storage."""
return list(load_index().keys())
+61
View File
@@ -0,0 +1,61 @@
"""
Validator module - checks that parsed documents meet schema requirements
before they are allowed into storage.
"""
from processor import normalize_text
REQUIRED_FIELDS = {"source", "format"}
MAX_TITLE_LENGTH = 200
ALLOWED_FORMATS = {"markdown", "plaintext", "json"}
class ValidationError(Exception):
pass
def validate_document(doc: dict) -> dict:
"""Run all validation checks on a parsed document. Raises ValidationError on failure."""
check_required_fields(doc)
check_format(doc)
doc = normalize_fields(doc)
return doc
def check_required_fields(doc: dict) -> None:
"""Raise if any required field is missing."""
missing = REQUIRED_FIELDS - doc.keys()
if missing:
raise ValidationError(f"Missing required fields: {missing}")
def check_format(doc: dict) -> None:
"""Raise if the format is not in the allowed list."""
fmt = doc.get("format", "")
if fmt not in ALLOWED_FORMATS:
raise ValidationError(f"Unknown format: {fmt}. Allowed: {ALLOWED_FORMATS}")
def normalize_fields(doc: dict) -> dict:
"""Clean up text fields using the processor."""
if "title" in doc:
doc["title"] = normalize_text(doc["title"])
if len(doc["title"]) > MAX_TITLE_LENGTH:
doc["title"] = doc["title"][:MAX_TITLE_LENGTH]
if "paragraphs" in doc:
doc["paragraphs"] = [normalize_text(p) for p in doc["paragraphs"]]
if "sections" in doc:
doc["sections"] = [normalize_text(s) for s in doc["sections"]]
return doc
def validate_batch(docs: list) -> tuple:
"""Validate a list of documents. Returns (valid_docs, errors)."""
valid = []
errors = []
for doc in docs:
try:
valid.append(validate_document(doc))
except ValidationError as e:
errors.append({"doc": doc.get("source", "unknown"), "error": str(e)})
return valid, errors
+78
View File
@@ -0,0 +1,78 @@
# Graph Report - worked/httpx/raw (2026-04-05)
## Corpus Check
- 6 files · ~2,047 words
- Verdict: corpus is large enough that graph structure adds value.
## Summary
- 144 nodes · 330 edges · 6 communities detected
- Extraction: 53% EXTRACTED · 47% INFERRED · 0% AMBIGUOUS
- Token cost: 0 input · 0 output
## God Nodes (most connected - your core abstractions)
1. `Client` - 26 edges
2. `AsyncClient` - 25 edges
3. `Response` - 24 edges
4. `Request` - 21 edges
5. `BaseClient` - 18 edges
6. `HTTPTransport` - 17 edges
7. `BaseTransport` - 16 edges
8. `AsyncHTTPTransport` - 15 edges
9. `Headers` - 15 edges
10. `Timeout` - 14 edges
## Surprising Connections (you probably didn't know these)
- `Timeout` --uses--> `URL` [INFERRED]
worked/httpx/raw/client.py → worked/httpx/raw/models.py
- `Timeout` --uses--> `Headers` [INFERRED]
worked/httpx/raw/client.py → worked/httpx/raw/models.py
- `Timeout` --uses--> `Cookies` [INFERRED]
worked/httpx/raw/client.py → worked/httpx/raw/models.py
- `Timeout` --uses--> `BaseTransport` [INFERRED]
worked/httpx/raw/client.py → worked/httpx/raw/transport.py
- `Timeout` --uses--> `HTTPTransport` [INFERRED]
worked/httpx/raw/client.py → worked/httpx/raw/transport.py
## Communities
### Community 0 - "Community 0"
Cohesion: 0.11
Nodes (8): ConnectError, AsyncBaseTransport, AsyncHTTPTransport, BaseTransport, ConnectionPool, HTTPTransport, MockTransport, ProxyTransport
### Community 1 - "Community 1"
Cohesion: 0.13
Nodes (9): Auth, BasicAuth, BearerAuth, DigestAuth, NetRCAuth, Limits, Timeout, Request (+1 more)
### Community 2 - "Community 2"
Cohesion: 0.12
Nodes (3): AsyncClient, BaseClient, Client
### Community 3 - "Community 3"
Cohesion: 0.11
Nodes (3): Cookies, Headers, URL
### Community 4 - "Community 4"
Cohesion: 0.16
Nodes (20): Exception, CloseError, ConnectTimeout, CookieConflict, DecodingError, HTTPError, HTTPStatusError, InvalidURL (+12 more)
### Community 5 - "Community 5"
Cohesion: 0.28
Nodes (3): build_url_with_params(), flatten_queryparams(), primitive_value_to_str()
## Suggested Questions
_Questions this graph is uniquely positioned to answer:_
- **Why does `Client` connect `Community 2` to `Community 0`, `Community 1`, `Community 3`, `Community 4`?**
_High betweenness centrality (0.177) - this node is a cross-community bridge._
- **Why does `Response` connect `Community 1` to `Community 0`, `Community 2`, `Community 3`, `Community 4`?**
_High betweenness centrality (0.168) - this node is a cross-community bridge._
- **Why does `AsyncClient` connect `Community 2` to `Community 0`, `Community 1`, `Community 3`, `Community 4`?**
_High betweenness centrality (0.165) - this node is a cross-community bridge._
- **Are the 12 inferred relationships involving `Client` (e.g. with `Request` and `Response`) actually correct?**
_`Client` has 12 INFERRED edges - model-reasoned connections that need verification._
- **Are the 12 inferred relationships involving `AsyncClient` (e.g. with `Request` and `Response`) actually correct?**
_`AsyncClient` has 12 INFERRED edges - model-reasoned connections that need verification._
- **Are the 18 inferred relationships involving `Response` (e.g. with `Timeout` and `Limits`) actually correct?**
_`Response` has 18 INFERRED edges - model-reasoned connections that need verification._
- **Are the 18 inferred relationships involving `Request` (e.g. with `Timeout` and `Limits`) actually correct?**
_`Request` has 18 INFERRED edges - model-reasoned connections that need verification._
+43
View File
@@ -0,0 +1,43 @@
# httpx Corpus Benchmark
A synthetic 6-file Python codebase modeled after httpx's architecture. Tests graphify on a realistic library with clean layering: exceptions → models → auth/transport → client.
## Corpus (6 files)
```
raw/
├── exceptions.py — HTTPError hierarchy
├── models.py — URL, Headers, Cookies, Request, Response
├── auth.py — BasicAuth, BearerAuth, DigestAuth, NetRCAuth
├── utils.py — header normalization, query params, content-type parsing
├── transport.py — ConnectionPool, HTTPTransport, AsyncHTTPTransport, MockTransport
└── client.py — Timeout, Limits, BaseClient, Client, AsyncClient
```
## How to run
```bash
pip install graphifyy
graphify install # Claude Code
graphify install --platform codex # Codex
graphify install --platform opencode # OpenCode
graphify install --platform claw # OpenClaw
```
Then open your AI coding assistant in this directory and type:
```
/graphify ./raw
```
## What to expect
- 144 nodes, 330 edges, 6 communities
- God nodes: `Client`, `AsyncClient`, `Response`, `Request`, `BaseClient`, `HTTPTransport`
- Surprising connection: `DigestAuth` linked to `Response` — auth.py reads Response to parse WWW-Authenticate headers
- Token reduction: ~1x — 6 files fits in a context window, so there is no compression win here
The graph value on a small corpus is structural, not compressive: you can see the full dependency graph, identify god nodes, and understand architecture at a glance. Token reduction scales with corpus size — at 52 files (Karpathy benchmark) graphify achieves 71.5x.
Run `graphify benchmark worked/httpx/graph.json` to verify the numbers. Actual output is in this folder: `GRAPH_REPORT.md` and `graph.json`. Full eval: `review.md`.
File diff suppressed because it is too large. Load diff
+114
View File
@@ -0,0 +1,114 @@
"""
Authentication handlers.
Auth objects are callables that modify a request before it is sent.
DigestAuth is the most interesting: it participates in a full request/response cycle,
reading the 401 response to build the challenge before re-sending.
"""
import hashlib
import time
from models import Request, Response
class Auth:
"""Base class for all authentication handlers."""
def auth_flow(self, request: Request):
"""Modify the request. May yield to inspect the response."""
raise NotImplementedError
class BasicAuth(Auth):
"""HTTP Basic Authentication."""
def __init__(self, username: str, password: str):
self.username = username
self.password = password
def auth_flow(self, request: Request):
import base64
credentials = f"{self.username}:{self.password}".encode()
encoded = base64.b64encode(credentials).decode()
request.headers["Authorization"] = f"Basic {encoded}"
yield request
class BearerAuth(Auth):
"""Bearer token authentication."""
def __init__(self, token: str):
self.token = token
def auth_flow(self, request: Request):
request.headers["Authorization"] = f"Bearer {self.token}"
yield request
class DigestAuth(Auth):
"""
HTTP Digest Authentication.
Requires a full request/response cycle: sends the initial request,
reads the 401 WWW-Authenticate header, then re-sends with credentials.
This is the only auth handler that reads from Response.
"""
def __init__(self, username: str, password: str):
self.username = username
self.password = password
self._nonce_count = 0
def auth_flow(self, request: Request):
yield request # first attempt, no credentials
# This handler must inspect the Response to continue
response = yield
if response.status_code == 401:
challenge = self._parse_challenge(response)
credentials = self._build_credentials(request, challenge)
request.headers["Authorization"] = credentials
yield request
def _parse_challenge(self, response: Response) -> dict:
"""Extract digest parameters from the WWW-Authenticate header."""
header = response.headers.get("www-authenticate", "")
params = {}
for part in header.replace("Digest ", "").split(","):
if "=" in part:
key, _, value = part.strip().partition("=")
params[key.strip()] = value.strip().strip('"')
return params
def _build_credentials(self, request: Request, challenge: dict) -> str:
"""Compute the Authorization header value for a digest challenge."""
self._nonce_count += 1
nc = f"{self._nonce_count:08x}"
cnonce = hashlib.md5(str(time.time()).encode()).hexdigest()[:8]
realm = challenge.get("realm", "")
nonce = challenge.get("nonce", "")
ha1 = hashlib.md5(f"{self.username}:{realm}:{self.password}".encode()).hexdigest()
ha2 = hashlib.md5(f"{request.method}:{request.url.path}".encode()).hexdigest()
response_hash = hashlib.md5(f"{ha1}:{nonce}:{nc}:{cnonce}:auth:{ha2}".encode()).hexdigest()
return (
f'Digest username="{self.username}", realm="{realm}", '
f'nonce="{nonce}", uri="{request.url.path}", '
f'nc={nc}, cnonce="{cnonce}", response="{response_hash}"'
)
class NetRCAuth(Auth):
"""Load credentials from ~/.netrc based on the request host."""
def auth_flow(self, request: Request):
import netrc
try:
credentials = netrc.netrc().authenticators(request.url.host)
if credentials:
username, _, password = credentials
basic = BasicAuth(username, password)
yield from basic.auth_flow(request)
return
except Exception:
pass
yield request
+161
View File
@@ -0,0 +1,161 @@
"""
The main Client and AsyncClient classes.
BaseClient holds all shared logic. Client and AsyncClient extend it for sync/async.
This is the integration hub of the library - it imports from every other module.
"""
from models import Request, Response, URL, Headers, Cookies
from auth import Auth, BasicAuth
from transport import BaseTransport, HTTPTransport, AsyncHTTPTransport
from exceptions import TooManyRedirects, InvalidURL
from utils import build_url_with_params, obfuscate_sensitive_headers
DEFAULT_MAX_REDIRECTS = 20
class Timeout:
def __init__(self, timeout=5.0, *, connect=None, read=None, write=None, pool=None):
self.connect = connect or timeout
self.read = read or timeout
self.write = write or timeout
self.pool = pool or timeout
class Limits:
def __init__(self, max_connections=100, max_keepalive_connections=20, keepalive_expiry=5.0):
self.max_connections = max_connections
self.max_keepalive_connections = max_keepalive_connections
self.keepalive_expiry = keepalive_expiry
class BaseClient:
"""
Shared implementation for Client and AsyncClient.
Handles auth, redirects, cookies, and header defaults.
"""
def __init__(
self,
*,
auth=None,
headers=None,
cookies=None,
timeout=Timeout(),
max_redirects=DEFAULT_MAX_REDIRECTS,
base_url="",
):
self._auth = auth
self._headers = Headers(headers or {})
self._cookies = Cookies(cookies or {})
self._timeout = timeout
self._max_redirects = max_redirects
self._base_url = URL(base_url) if base_url else None
def _build_request(self, method: str, url: str, **kwargs) -> Request:
if self._base_url:
url = self._base_url.raw.rstrip("/") + "/" + url.lstrip("/")
if kwargs.get("params"):
url = build_url_with_params(url, kwargs.pop("params"))
headers = Headers(kwargs.get("headers", {}))
for k, v in self._headers.items():
if k not in headers:
headers[k] = v
return Request(method, url, headers=headers, content=kwargs.get("content"), cookies=self._cookies)
def _merge_cookies(self, response: Response) -> None:
for name, value in response.cookies.items():
self._cookies.set(name, value)
class Client(BaseClient):
"""Synchronous HTTP client."""
def __init__(self, *, transport: BaseTransport = None, **kwargs):
super().__init__(**kwargs)
self._transport = transport or HTTPTransport()
def request(self, method: str, url: str, **kwargs) -> Response:
request = self._build_request(method, url, **kwargs)
auth = kwargs.get("auth") or self._auth
if auth:
flow = auth.auth_flow(request)
request = next(flow)
response = self._transport.handle_request(request)
self._merge_cookies(response)
if auth:
try:
flow.send(response)
except StopIteration:
pass
return response
def get(self, url: str, **kwargs) -> Response:
return self.request("GET", url, **kwargs)
def post(self, url: str, **kwargs) -> Response:
return self.request("POST", url, **kwargs)
def put(self, url: str, **kwargs) -> Response:
return self.request("PUT", url, **kwargs)
def patch(self, url: str, **kwargs) -> Response:
return self.request("PATCH", url, **kwargs)
def delete(self, url: str, **kwargs) -> Response:
return self.request("DELETE", url, **kwargs)
def head(self, url: str, **kwargs) -> Response:
return self.request("HEAD", url, **kwargs)
def send(self, request: Request) -> Response:
return self._transport.handle_request(request)
def close(self) -> None:
self._transport.close()
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
class AsyncClient(BaseClient):
"""Asynchronous HTTP client."""
def __init__(self, *, transport=None, **kwargs):
super().__init__(**kwargs)
self._transport = transport or AsyncHTTPTransport()
async def request(self, method: str, url: str, **kwargs) -> Response:
request = self._build_request(method, url, **kwargs)
response = await self._transport.handle_async_request(request)
self._merge_cookies(response)
return response
async def get(self, url: str, **kwargs) -> Response:
return await self.request("GET", url, **kwargs)
async def post(self, url: str, **kwargs) -> Response:
return await self.request("POST", url, **kwargs)
async def put(self, url: str, **kwargs) -> Response:
return await self.request("PUT", url, **kwargs)
async def patch(self, url: str, **kwargs) -> Response:
return await self.request("PATCH", url, **kwargs)
async def delete(self, url: str, **kwargs) -> Response:
return await self.request("DELETE", url, **kwargs)
async def send(self, request: Request) -> Response:
return await self._transport.handle_async_request(request)
async def aclose(self) -> None:
await self._transport.aclose()
async def __aenter__(self):
return self
async def __aexit__(self, *args):
await self.aclose()
+90
View File
@@ -0,0 +1,90 @@
"""
httpx-like exception hierarchy.
All exceptions inherit from HTTPError at the top.
"""
class HTTPError(Exception):
"""Base class for all httpx exceptions."""
def __init__(self, message, *, request=None):
self.request = request
super().__init__(message)
class RequestError(HTTPError):
"""An error occurred while issuing a request."""
class TransportError(RequestError):
"""An error occurred at the transport layer."""
class TimeoutException(TransportError):
"""A timeout occurred."""
class ConnectTimeout(TimeoutException):
"""Timed out while connecting to the host."""
class ReadTimeout(TimeoutException):
"""Timed out while receiving data from the host."""
class WriteTimeout(TimeoutException):
"""Timed out while sending data to the host."""
class PoolTimeout(TimeoutException):
"""Timed out waiting to acquire a connection from the pool."""
class NetworkError(TransportError):
"""A network error occurred."""
class ConnectError(NetworkError):
"""Failed to establish a connection."""
class ReadError(NetworkError):
"""Failed to receive data from the network."""
class WriteError(NetworkError):
"""Failed to send data through the network."""
class CloseError(NetworkError):
"""Failed to close a connection."""
class ProxyError(TransportError):
"""An error occurred while establishing a proxy connection."""
class ProtocolError(TransportError):
"""A protocol was violated."""
class DecodingError(RequestError):
"""Decoding of the response failed."""
class TooManyRedirects(RequestError):
"""Too many redirects."""
class HTTPStatusError(HTTPError):
"""A 4xx or 5xx response was received."""
def __init__(self, message, *, request, response):
self.response = response
super().__init__(message, request=request)
class InvalidURL(Exception):
"""URL is improperly formed or cannot be parsed."""
class CookieConflict(Exception):
"""Attempted to look up a cookie by name but multiple cookies exist."""
+120
View File
@@ -0,0 +1,120 @@
"""
Core data models: URL, Headers, Cookies, Request, Response.
These are the central data types that everything else in the library references.
"""
import json as _json
from exceptions import HTTPStatusError
class URL:
def __init__(self, url: str):
self.raw = url
self.scheme, _, rest = url.partition("://")
self.host, _, self.path = rest.partition("/")
self.path = "/" + self.path
def copy_with(self, **kwargs) -> "URL":
return URL(kwargs.get("url", self.raw))
def __str__(self):
return self.raw
def __repr__(self):
return f"URL({self.raw!r})"
class Headers:
def __init__(self, headers=None):
self._store = {}
for k, v in (headers or {}).items():
self._store[k.lower()] = v
def get(self, key: str, default=None):
return self._store.get(key.lower(), default)
def items(self):
return self._store.items()
def __setitem__(self, key, value):
self._store[key.lower()] = value
def __getitem__(self, key):
return self._store[key.lower()]
def __contains__(self, key):
return key.lower() in self._store
class Cookies:
def __init__(self, cookies=None):
self._jar = dict(cookies or {})
def set(self, name: str, value: str, domain: str = "") -> None:
self._jar[name] = value
def get(self, name: str, default=None):
return self._jar.get(name, default)
def delete(self, name: str) -> None:
self._jar.pop(name, None)
def clear(self) -> None:
self._jar.clear()
def items(self):
return self._jar.items()
class Request:
def __init__(self, method: str, url, *, headers=None, content=None, cookies=None):
self.method = method.upper()
self.url = URL(url) if isinstance(url, str) else url
self.headers = Headers(headers)
self.content = content or b""
self.cookies = Cookies(cookies)
def __repr__(self):
return f"<Request [{self.method}]>"
class Response:
def __init__(self, status_code: int, *, headers=None, content=None, request=None):
self.status_code = status_code
self.headers = Headers(headers)
self.content = content or b""
self.request = request
@property
def text(self) -> str:
return self.content.decode("utf-8", errors="replace")
def json(self):
return _json.loads(self.content)
def read(self) -> bytes:
return self.content
@property
def is_success(self) -> bool:
return 200 <= self.status_code < 300
@property
def is_error(self) -> bool:
return self.status_code >= 400
def raise_for_status(self) -> None:
if self.is_error:
message = f"{self.status_code} Error"
raise HTTPStatusError(message, request=self.request, response=self)
@property
def cookies(self) -> Cookies:
jar = Cookies()
for header in self.headers.get("set-cookie", "").split(","):
if "=" in header:
name, _, value = header.strip().partition("=")
jar.set(name.strip(), value.split(";")[0].strip())
return jar
def __repr__(self):
return f"<Response [{self.status_code}]>"
+135
View File
@@ -0,0 +1,135 @@
"""
Transport layer: connection management and low-level HTTP sending.
HTTPTransport wraps a connection pool. ProxyTransport sits in front of it.
MockTransport is used in tests.
"""
from models import Request, Response
from exceptions import TransportError, ConnectError, TimeoutException
class BaseTransport:
"""Sync transport interface."""
def handle_request(self, request: Request) -> Response:
raise NotImplementedError
def close(self) -> None:
pass
class AsyncBaseTransport:
"""Async transport interface."""
async def handle_async_request(self, request: Request) -> Response:
raise NotImplementedError
async def aclose(self) -> None:
pass
class ConnectionPool:
"""
Manages a pool of persistent HTTP connections.
Keys connections by (scheme, host, port).
"""
def __init__(self, max_connections=100, max_keepalive_connections=20):
self.max_connections = max_connections
self.max_keepalive_connections = max_keepalive_connections
self._pool = {}
def _get_connection_key(self, request: Request) -> tuple:
url = request.url
port = 443 if url.scheme == "https" else 80
return (url.scheme, url.host, port)
def get_connection(self, request: Request):
key = self._get_connection_key(request)
return self._pool.get(key)
def return_connection(self, request: Request, conn) -> None:
key = self._get_connection_key(request)
if len(self._pool) < self.max_keepalive_connections:
self._pool[key] = conn
def close(self) -> None:
self._pool.clear()
class HTTPTransport(BaseTransport):
"""
The main sync HTTP transport.
Uses a ConnectionPool for connection reuse.
"""
def __init__(self, verify=True, cert=None, limits=None):
self.verify = verify
self.cert = cert
self._pool = ConnectionPool()
def handle_request(self, request: Request) -> Response:
conn = self._pool.get_connection(request)
try:
response = self._send(request, conn)
self._pool.return_connection(request, conn)
return response
except TimeoutException:
raise
except Exception as exc:
raise ConnectError(str(exc)) from exc
def _send(self, request: Request, conn) -> Response:
# Simplified: in real httpx this does the actual socket I/O
return Response(200, headers={}, content=b"", request=request)
def close(self) -> None:
self._pool.close()
class AsyncHTTPTransport(AsyncBaseTransport):
"""The async variant of HTTPTransport."""
def __init__(self, verify=True, cert=None):
self.verify = verify
self.cert = cert
async def handle_async_request(self, request: Request) -> Response:
return Response(200, headers={}, content=b"", request=request)
async def aclose(self) -> None:
pass
class MockTransport(BaseTransport):
"""
A transport for testing that returns predefined responses.
Pass a handler function that receives a Request and returns a Response.
"""
def __init__(self, handler):
self.handler = handler
def handle_request(self, request: Request) -> Response:
return self.handler(request)
class ProxyTransport(BaseTransport):
"""
Routes requests through an HTTP/HTTPS proxy.
Wraps an inner transport and prepends proxy connection handling.
"""
def __init__(self, proxy_url: str, *, inner: BaseTransport = None):
self.proxy_url = proxy_url
self._inner = inner or HTTPTransport()
def handle_request(self, request: Request) -> Response:
try:
return self._inner.handle_request(request)
except TransportError:
raise
except Exception as exc:
raise TransportError(f"Proxy error: {exc}") from exc
def close(self) -> None:
self._inner.close()
+85
View File
@@ -0,0 +1,85 @@
"""
Utility functions shared across the library.
Small helpers that don't belong in any one module.
"""
import re
from models import Cookies
SENSITIVE_HEADERS = {"authorization", "cookie", "set-cookie", "proxy-authorization"}
def primitive_value_to_str(value) -> str:
"""Convert a primitive value to its string representation."""
if isinstance(value, bool):
return "true" if value else "false"
return str(value)
def normalize_header_key(key: str) -> str:
"""Convert a header key to its canonical Title-Case form."""
return "-".join(word.capitalize() for word in key.split("-"))
def flatten_queryparams(params: dict) -> list:
"""
Expand a params dict into a flat list of (key, value) pairs.
List values become multiple pairs with the same key.
"""
result = []
for key, value in params.items():
if isinstance(value, list):
for item in value:
result.append((key, primitive_value_to_str(item)))
else:
result.append((key, primitive_value_to_str(value)))
return result
def parse_content_type(content_type: str) -> tuple:
"""
Parse a Content-Type header value.
Returns (media_type, params_dict).
Example: 'application/json; charset=utf-8' -> ('application/json', {'charset': 'utf-8'})
"""
parts = [p.strip() for p in content_type.split(";")]
media_type = parts[0]
params = {}
for part in parts[1:]:
if "=" in part:
key, _, value = part.partition("=")
params[key.strip()] = value.strip()
return media_type, params
def obfuscate_sensitive_headers(headers: dict) -> dict:
"""Return a copy of headers with sensitive values replaced by [obfuscated]."""
return {
k: "[obfuscated]" if k.lower() in SENSITIVE_HEADERS else v
for k, v in headers.items()
}
def unset_all_cookies(cookies: Cookies) -> None:
"""Clear all cookies from a cookie jar in place."""
cookies.clear()
def is_known_encoding(encoding: str) -> bool:
"""Check if a character encoding label is recognized by Python's codec system."""
import codecs
try:
codecs.lookup(encoding)
return True
except LookupError:
return False
def build_url_with_params(base_url: str, params: dict) -> str:
"""Append query parameters to a URL string."""
if not params:
return base_url
pairs = flatten_queryparams(params)
query = "&".join(f"{k}={v}" for k, v in pairs)
separator = "&" if "?" in base_url else "?"
return f"{base_url}{separator}{query}"
+59 -59
View File
@@ -1,6 +1,6 @@
# Graphify Evaluation — httpx Corpus (2026-04-03)
# Graphify Evaluation - httpx Corpus (2026-04-03)
**Evaluator:** Claude Sonnet 4.6 (analytical simulation — Bash execution unavailable)
**Evaluator:** Claude Sonnet 4.6 (analytical simulation - Bash execution unavailable)
**Corpus:** 6-file synthetic httpx-like Python codebase (~2,800 words)
**Pipeline:** graphify AST extractor + graph_builder + Leiden clusterer + analyzer + reporter
**Method:** Full deterministic code tracing of every graphify source module against
@@ -12,7 +12,7 @@ exact Leiden partition is non-deterministic but the structural analysis is sound
## Full GRAPH_REPORT.md Content
```markdown
# Graph Report — /home/safi/graphify_test/httpx (2026-04-03)
# Graph Report - /home/safi/graphify_test/httpx (2026-04-03)
## Corpus Check
- 6 files · ~2,800 words
@@ -23,17 +23,17 @@ exact Leiden partition is non-deterministic but the structural analysis is sound
- Extraction: ~100% EXTRACTED · 0% INFERRED · 0% AMBIGUOUS
- Token cost: 0 input · 0 output
## God Nodes (most connected — your core abstractions)
1. `client.py` — ~28 edges
2. `models.py` — ~22 edges
3. `transport.py` — ~20 edges
4. `exceptions.py` — ~18 edges
5. `BaseClient` — ~15 edges
6. `auth.py` — ~14 edges
7. `Response` — ~12 edges
8. `Client` — ~10 edges
9. `AsyncClient` — ~10 edges
10. `utils.py` — ~9 edges
## God Nodes (most connected - your core abstractions)
1. `client.py` - ~28 edges
2. `models.py` - ~22 edges
3. `transport.py` - ~20 edges
4. `exceptions.py` - ~18 edges
5. `BaseClient` - ~15 edges
6. `auth.py` - ~14 edges
7. `Response` - ~12 edges
8. `Client` - ~10 edges
9. `AsyncClient` - ~10 edges
10. `utils.py` - ~9 edges
## Surprising Connections
- `BaseClient` ↔ `.auth_flow()` [EXTRACTED]
@@ -49,19 +49,19 @@ exact Leiden partition is non-deterministic but the structural analysis is sound
## Communities
### Community 0 — "Core HTTP Client"
### Community 0 - "Core HTTP Client"
Cohesion: 0.14
Nodes (12): client.py, BaseClient, Client, AsyncClient, .send(), .request(), .get(), .post(), .close(), .aclose(), Timeout, Limits
### Community 1 — "Request/Response Models"
### Community 1 - "Request/Response Models"
Cohesion: 0.18
Nodes (10): models.py, Request, Response, URL, Headers, Cookies, .read(), .json(), .raise_for_status(), .cookies
### Community 2 — "Exception Hierarchy"
### Community 2 - "Exception Hierarchy"
Cohesion: 0.10
Nodes (20): exceptions.py, HTTPStatusError, RequestError, TransportError, TimeoutException, ...
### Community 3 — "Transport & Auth"
### Community 3 - "Transport & Auth"
Cohesion: 0.08
Nodes (18): transport.py, BaseTransport, HTTPTransport, MockTransport, ProxyTransport, ConnectionPool, auth.py, Auth, BasicAuth, DigestAuth, BearerAuth, NetRCAuth, ...
```
@@ -70,7 +70,7 @@ Nodes (18): transport.py, BaseTransport, HTTPTransport, MockTransport, ProxyTran
## Evaluation Scores
### 1. Node/Edge Quality — Score: 6/10
### 1. Node/Edge Quality - Score: 6/10
**What's captured well:**
- File-level nodes for all 6 files (exceptions, models, auth, utils, client, transport) ✓
@@ -78,42 +78,42 @@ Nodes (18): transport.py, BaseTransport, HTTPTransport, MockTransport, ProxyTran
subclasses; URL, Headers, Cookies, Request, Response; Auth, BasicAuth, DigestAuth,
BearerAuth, NetRCAuth; BaseClient, Client, AsyncClient; Timeout, Limits; BaseTransport,
AsyncBaseTransport, HTTPTransport, AsyncHTTPTransport, MockTransport, ProxyTransport,
ConnectionPool — all captured ✓
ConnectionPool - all captured ✓
- Module-level functions from utils.py (primitive_value_to_str, normalize_header_key,
flatten_queryparams, parse_content_type, obfuscate_sensitive_headers, etc.) ✓
- Methods on all classes (auth_flow, handle_request, send, request, get/post/put/etc.) ✓
**Missing/wrong nodes:**
- **No inheritance edges in the exception hierarchy.** The extractor builds inheritance edges
as `_make_id(stem, base_name)` — e.g. `RequestError` inheriting `Exception` produces target
as `_make_id(stem, base_name)` - e.g. `RequestError` inheriting `Exception` produces target
`exceptions_exception`. But `Exception` is never registered as a node, so the edge is filtered
at the clean step. All 14 inheritance edges in exceptions.py are silently dropped. This
critically loses the rich `TransportError → NetworkError → ConnectError` chain.
- **No inheritance across files.** `BaseClient` inherits nothing in the graph. `Client(BaseClient)`
produces `_make_id("client", "BaseClient")` = `"client_baseclient"`, but `BaseClient`'s node
ID is `_make_id("client", "BaseClient")` = `"client_baseclient"` — this actually SHOULD work
ID is `_make_id("client", "BaseClient")` = `"client_baseclient"` - this actually SHOULD work
because both the class definition and the inheritance reference use the same stem ("client").
**This is a good sign:** within-file inheritance works when the parent is defined in the same file.
- **Cross-file inheritance is not captured.** `HTTPTransport(BaseTransport)` — `BaseTransport`
- **Cross-file inheritance is not captured.** `HTTPTransport(BaseTransport)` - `BaseTransport`
is defined in `transport.py`, so `_make_id("transport", "BaseTransport")` = `"transport_basetransport"`.
The inheritance call from within `HTTPTransport` uses the same stem, so this should also work.
- **Property methods lose their property decorator context.** `url`, `content`, `cookies`,
`is_success`, `is_error`, etc. are extracted as ordinary methods — no semantic distinction.
- **`build_auth_header` utility function in auth.py** — captured as a module-level function ✓
`is_success`, `is_error`, etc. are extracted as ordinary methods - no semantic distinction.
- **`build_auth_header` utility function in auth.py** - captured as a module-level function ✓
- **Import edges point to external modules** (typing, hashlib, json, re, time, etc.) that are
never registered as nodes. Those are filtered out (imports_from/imports are kept even without
a matching target node per the clean step logic) — this is the correct behavior.
a matching target node per the clean step logic) - this is the correct behavior.
**Summary:** ~85% of meaningful code entities are captured. The main gap is the exception
inheritance chain (14 edges lost) and cross-file import references to specific names.
---
### 2. Edge Accuracy — Score: 5/10
### 2. Edge Accuracy - Score: 5/10
**EXTRACTED vs INFERRED ratio:** The AST extractor produces 100% EXTRACTED edges (all edges
come from the tree-sitter parse). There are 0 INFERRED edges. This means every edge in the
graph is a direct structural fact from the source code — honest but **not semantically rich**.
graph is a direct structural fact from the source code - honest but **not semantically rich**.
**What's right:**
- `contains` edges from file nodes to their class/function children ✓
@@ -124,19 +124,19 @@ graph is a direct structural fact from the source code — honest but **not sema
**What's wrong or missing:**
- **0% INFERRED edges.** The AST extractor only does structural extraction. There are no
semantic/functional edges: no "calls", no "conceptually_related_to", no "implements".
For example, `DigestAuth.auth_flow` calls `Response.status_code` — this relationship is
For example, `DigestAuth.auth_flow` calls `Response.status_code` - this relationship is
invisible. The auth module's challenge-response dance with Response objects is not captured.
- **Inheritance chain edges dropped (14 edges).** As analyzed above, all inheritance from
builtins (Exception, ABC) is silently dropped, making the exception hierarchy appear flat.
- **Import edges are present but low-signal.** `client.py imports_from models` is correct but
doesn't say WHICH classes — so the graph can't distinguish that `Client` specifically uses
doesn't say WHICH classes - so the graph can't distinguish that `Client` specifically uses
`Request` and `Response`, not just the whole models module.
- **No "calls" relationships.** `Response.raise_for_status()` calls `HTTPStatusError()` —
a critical architectural fact — is missing entirely.
- **No "calls" relationships.** `Response.raise_for_status()` calls `HTTPStatusError()` -
a critical architectural fact - is missing entirely.
- **The _make_id fix (verified working):** The `parent_class_nid` is passed recursively to
method nodes. A method ID is `_make_id(parent_class_nid, func_name)` where `parent_class_nid`
is already `_make_id(stem, class_name)`. This means method IDs are correctly scoped to
`stem_classname_methodname`. Edge cleanup checks `src in valid_ids` — since method nodes ARE
`stem_classname_methodname`. Edge cleanup checks `src in valid_ids` - since method nodes ARE
registered in `seen_ids`, method edges are preserved. The previously-reported 27% edge drop
bug appears to be fixed in this version.
@@ -144,32 +144,32 @@ graph is a direct structural fact from the source code — honest but **not sema
- Correct, present: ~115 edges (88%)
- Silently dropped (inheritance from builtins): ~14 edges (11%)
- False positives: ~2 edges (import edges to nonexistent modules like "socket" kept via
imports exception in clean step — technically correct behavior)
imports exception in clean step - technically correct behavior)
- Missing (calls, conceptual): would require LLM or runtime analysis
---
### 3. Community Quality — Score: 6/10
### 3. Community Quality - Score: 6/10
**Communities make semantic sense?** Largely yes, with one significant problem.
**Community 0 — "Core HTTP Client"** (Client, AsyncClient, BaseClient + methods, Timeout, Limits)
**Community 0 - "Core HTTP Client"** (Client, AsyncClient, BaseClient + methods, Timeout, Limits)
- This is semantically tight: all the public API surface of httpx belongs here.
- Cohesion ~0.14: low but expected — client.py's class bodies generate many method nodes
- Cohesion ~0.14: low but expected - client.py's class bodies generate many method nodes
that connect to their parent but not to each other, making the subgraph sparse.
**Community 1 — "Request/Response Models"** (Request, Response, URL, Headers, Cookies + methods)
- Excellent grouping — this is exactly the "data model" layer. Cohesion ~0.18 is the highest
**Community 1 - "Request/Response Models"** (Request, Response, URL, Headers, Cookies + methods)
- Excellent grouping - this is exactly the "data model" layer. Cohesion ~0.18 is the highest
because methods connect within their parent classes.
**Community 2 — "Exception Hierarchy"** (all 15 exception classes)
**Community 2 - "Exception Hierarchy"** (all 15 exception classes)
- Good that exceptions are grouped together. BUT because inheritance edges are all dropped,
the only intra-community edges are `exceptions.py contains ExceptionClass`. This means
cohesion is near-zero (0.10 estimated) — the community is held together only by the file
cohesion is near-zero (0.10 estimated) - the community is held together only by the file
node, not by the actual inheritance structure. Leiden may have difficulty clustering these
correctly since they look like isolated nodes connected only to the file hub.
**Community 3 — "Transport & Auth"** (all transport + auth classes)
**Community 3 - "Transport & Auth"** (all transport + auth classes)
- This is the most problematic grouping. Transport (HTTPTransport, ConnectionPool, etc.) and
Auth (BasicAuth, DigestAuth, etc.) are bundled together simply because both modules import
from models.py and exceptions.py. They are architecturally distinct layers. A developer
@@ -182,7 +182,7 @@ real codebase with many cross-cutting concerns. The scores are not artificially
---
### 4. Surprising Connections — Score: 4/10
### 4. Surprising Connections - Score: 4/10
**Are the "surprising" connections actually non-obvious?**
@@ -190,13 +190,13 @@ The 5 reported connections are all EXTRACTED (cross-file import edges). Let's ev
1. `BaseClient ↔ .auth_flow()` (client.py ↔ auth.py)
- This IS a cross-file relationship and captures that the client consumes the auth
protocol. Moderately interesting — but "client uses auth" is not surprising.
protocol. Moderately interesting - but "client uses auth" is not surprising.
- Score: Somewhat interesting, but obvious to anyone who reads client.py line 1.
2. `ProxyTransport ↔ TransportError` (transport.py ↔ exceptions.py)
- This is within the same file (transport.py imports exceptions at the bottom:
`from .exceptions import TransportError`). This is a re-export, not a surprise.
- Score: False positive — this is a completely obvious import.
- Score: False positive - this is a completely obvious import.
3. `ConnectionPool ↔ Request` (transport.py ↔ models.py)
- transport.py imports from models. That `ConnectionPool` specifically uses `Request`
@@ -206,14 +206,14 @@ The 5 reported connections are all EXTRACTED (cross-file import edges). Let's ev
4. `DigestAuth ↔ Response` (auth.py ↔ models.py)
- This IS genuinely interesting! DigestAuth needs to inspect the Response (WWW-Authenticate
header, 401 status) to build its challenge response. The auth layer having a bidirectional
dependency on Response is a real architectural insight — auth is not a pure pre-request
dependency on Response is a real architectural insight - auth is not a pure pre-request
decorator but a request-response cycle participant.
- Score: Genuinely non-obvious and architecturally significant.
5. `utils.py ↔ Cookies` (utils.py ↔ models.py)
- `unset_all_cookies` in utils.py imports `Cookies` from models. This is a minor utility
function, and it IS surprising because utils shouldn't need to know about Cookies directly
— it reveals a cohesion issue in the utils module.
- it reveals a cohesion issue in the utils module.
- Score: Mildly interesting.
**Problems:**
@@ -227,18 +227,18 @@ The 5 reported connections are all EXTRACTED (cross-file import edges). Let's ev
---
### 5. God Nodes — Score: 7/10
### 5. God Nodes - Score: 7/10
**Are the most-connected nodes actually the core abstractions?**
**Very good:**
- `client.py` as #1 god node makes sense — it imports from 5 other modules and contains the
- `client.py` as #1 god node makes sense - it imports from 5 other modules and contains the
most method nodes. It is the integration hub of the library.
- `models.py` as #2 is correct — Request, Response, URL, Headers, Cookies are the central
- `models.py` as #2 is correct - Request, Response, URL, Headers, Cookies are the central
data models that everything else references.
- `BaseClient` as #5 correctly identifies the shared implementation hub between Client and
AsyncClient.
- `Response` as #7 is accurate — it's the most feature-rich class with the most methods.
- `Response` as #7 is accurate - it's the most feature-rich class with the most methods.
**Problematic:**
- File-level nodes (client.py, models.py, transport.py, exceptions.py, auth.py, utils.py)
@@ -254,13 +254,13 @@ The 5 reported connections are all EXTRACTED (cross-file import edges). Let's ev
---
### 6. Overall Usefulness — Score: 6/10
### 6. Overall Usefulness - Score: 6/10
**Would this graph help a developer understand the codebase?**
**Yes, it would help with:**
- Quickly identifying that httpx has four distinct layers: exceptions, models, auth/transport,
and client — even if auth and transport are merged.
and client - even if auth and transport are merged.
- Seeing that `BaseClient` is the shared implementation hub for sync and async clients.
- Identifying `Response` and `Request` as the central data types.
- Finding cross-module coupling (e.g., auth's dependency on Response).
@@ -270,7 +270,7 @@ The 5 reported connections are all EXTRACTED (cross-file import edges). Let's ev
- Understanding the exception hierarchy (all 14 inheritance edges are dropped).
- Understanding call flow (which methods call which).
- Understanding that DigestAuth participates in a request/response cycle, not just
pre-request decoration — this architectural insight is present but buried in boring
pre-request decoration - this architectural insight is present but buried in boring
EXTRACTED connection #4.
- Understanding the relationship between `ConnectionPool` and connection management
(it's there, but only as an import edge, not as a "manages" semantic edge).
@@ -332,11 +332,11 @@ Even simple name-based heuristics would add INFERRED edges for common patterns.
surprising connections. But many cross-file edges are mundane imports. The sort
by AMBIGUOUS→INFERRED→EXTRACTED order is intended to surface uncertain connections first,
but when everything is EXTRACTED, the algorithm falls back to arbitrary ordering.
**Fix:** Add a "distance" metric — prefer pairs where the source files have no direct
**Fix:** Add a "distance" metric - prefer pairs where the source files have no direct
import relationship. A `transport.py → exceptions.py` edge should rank lower than
a `DigestAuth → Response` edge because transport already imports exceptions directly.
### Issue 6: _make_id edge fix — CONFIRMED WORKING
### Issue 6: _make_id edge fix - CONFIRMED WORKING
**Location:** `ast_extractor.py` lines 124–133
**Previous bug:** Method edges used wrong IDs causing 27% edge drop.
**Current code:** Method node ID is `_make_id(parent_class_nid, func_name)` and the
@@ -345,7 +345,7 @@ same `parent_class_nid`. Both `parent_class_nid` and `func_nid` are in `seen_ids
**Status:** The _make_id fix is correctly implemented. Method edges are preserved.
No 27% drop for method edges. ✓
### Issue 7: Concept node filtering — CONFIRMED WORKING
### Issue 7: Concept node filtering - CONFIRMED WORKING
**Location:** `analyzer.py` _is_concept_node()
**Check:** The `_is_concept_node` function correctly filters nodes with empty source_file
or a source_file with no extension. The AST extractor always sets source_file to the
@@ -382,13 +382,13 @@ otherwise be dropped. The fix is confirmed working.
The graphify AST extractor is deterministic, fast, and accurate for what it extracts.
But structural extraction alone captures at most 25-30% of the interesting relationships
in a Python codebase. The skill.md design correctly envisions the Claude LLM doing a
richer extraction pass (Step 3) for document/paper corpora — but for code, the pipeline
richer extraction pass (Step 3) for document/paper corpora - but for code, the pipeline
currently relies entirely on tree-sitter, producing a structurally correct but
semantically thin graph.
### Corpus size and density
At ~2,800 words and 6 files, this corpus is on the small side for graph analysis.
The skill.md correctly warns "Corpus fits in a single context window — you may not need
The skill.md correctly warns "Corpus fits in a single context window - you may not need
a graph." A real httpx codebase has 30+ files. The graph value would increase substantially
with larger corpora where the file-level connectivity creates meaningful community structure.
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more