Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f81e3bc215 | ||
|
|
8e81720bc8 | ||
|
|
6df69dce6c | ||
|
|
f61bb27d9c | ||
|
|
de268a067c | ||
|
|
b11a8a7813 | ||
|
|
d753413409 | ||
|
|
f065933391 | ||
|
|
893acb19df | ||
|
|
96267ad0a8 | ||
|
|
cf7ce3a450 | ||
|
|
ba41258635 | ||
|
|
e48428296c | ||
|
|
d819827ea2 | ||
|
|
bd92ab67d6 | ||
|
|
0a99a46bfc | ||
|
|
1e848458f9 | ||
|
|
2ca3a5994b | ||
|
|
bfe18f0c83 | ||
|
|
28047b502f | ||
|
|
9881d7ca30 | ||
|
|
24808ef8e6 | ||
|
|
66e61c76b1 | ||
|
|
7237cd3290 | ||
|
|
d04e487877 | ||
|
|
996e82b3d9 | ||
|
|
9ab4f39020 | ||
|
|
58271fb5af | ||
|
|
893219d66f | ||
|
|
763a9359f5 | ||
|
|
5a342e385c | ||
|
|
47ca9228c3 | ||
|
|
36e894aa62 | ||
|
|
d40e1c0cef | ||
|
|
e02c7cc60c | ||
|
|
ca48092413 | ||
|
|
8e01d686f7 | ||
|
|
71423a1efb | ||
|
|
c3ddace690 | ||
|
|
a61b25ce5f | ||
|
|
8c9ee1818b | ||
|
|
a4149dffcd | ||
|
|
028f585356 | ||
|
|
c8969edd3c | ||
|
|
0fc2dc6ad3 | ||
|
|
af15e33f57 | ||
|
|
be83a8cc55 | ||
|
|
3fdae8f334 | ||
|
|
e73b6060b1 | ||
|
|
5dbbcf7dad | ||
|
|
2dc759a951 | ||
|
|
14fd14a284 | ||
|
|
7f336acfd9 | ||
|
|
8a6306f769 | ||
|
|
6b68de140c | ||
|
|
17fb524a91 | ||
|
|
ad1e11a035 | ||
|
|
7d604e8141 | ||
|
|
0999822364 | ||
|
|
47a994ad5b | ||
|
|
5aaa268650 | ||
|
|
2d13a17c3b | ||
|
|
cc5c54574d | ||
|
|
3755fdc885 | ||
|
|
4e871ad36c | ||
|
|
97099edc38 | ||
|
|
abb1450b24 | ||
|
|
4360f9644b | ||
|
|
f755aca58f | ||
|
|
a9946fb7a0 | ||
|
|
28b17d37f1 | ||
|
|
326c03e132 | ||
|
|
44fc32e3e2 | ||
|
|
744827166e | ||
|
|
c750582db4 | ||
|
|
71d1b394e9 | ||
|
|
a4ad901284 | ||
|
|
f9c344b546 | ||
|
|
59cbad3937 | ||
|
|
5904081d7a | ||
|
|
eceaaad61e | ||
|
|
dd86271312 | ||
|
|
7359cdace9 | ||
|
|
ee1df22b25 | ||
|
|
563ee80494 | ||
|
|
88e2b832f7 | ||
|
|
a1dc610079 | ||
|
|
a566bfb566 | ||
|
|
4563b043f2 | ||
|
|
6175e0a8ea | ||
|
|
a52350940a | ||
|
|
c3ba79f5aa | ||
|
|
770d7f54c4 | ||
|
|
3ff7188fbf | ||
|
|
8bed332ff4 | ||
|
|
df9b7ec54f | ||
|
|
2faeed99a2 | ||
|
|
2c49da24f0 | ||
|
|
5843ffc277 | ||
|
|
b326aa83c4 | ||
|
|
e915a877e2 | ||
|
|
64f38acf3e | ||
|
|
e4bdcc2487 | ||
|
|
8981f7c8ef | ||
|
|
4bc20527c3 | ||
|
|
85e713644e | ||
|
|
52ad45bd27 | ||
|
|
86d6d9317f | ||
|
|
d9b2928da1 | ||
|
|
f8fd8f8479 | ||
|
|
f938714df0 | ||
|
|
7cb639ae5d | ||
|
|
39bf0a3f80 | ||
|
|
e241ce96cf | ||
|
|
dbde78ca03 | ||
|
|
9c3d0fa517 | ||
|
|
69d4d7e9c3 | ||
|
|
2a35d7fd38 | ||
|
|
ed4f12ab82 | ||
|
|
de136676ef | ||
|
|
339d9783fb | ||
|
|
4738e88aaf | ||
|
|
81b6e7d7b4 | ||
|
|
f0ebd07fd5 | ||
|
|
2fd15115d9 | ||
|
|
0973af2be0 | ||
|
|
3bf096438f | ||
|
|
45643380d1 | ||
|
|
0f30cfb6ad | ||
|
|
cc53e00bcc | ||
|
|
3f5df2513b | ||
|
|
6892fd9309 | ||
|
|
9c2275ad82 | ||
|
|
d67436c065 | ||
|
|
f8a5328197 | ||
|
|
8171abf583 | ||
|
|
c24cde9d9e | ||
|
|
d0d8d80581 | ||
|
|
8666c6994c | ||
|
|
72d9779aaf | ||
|
|
1805813a56 | ||
|
|
a507c97822 | ||
|
|
826fd0ece1 | ||
|
|
bdfb917935 | ||
|
|
8a474eb1b3 | ||
|
|
022feee5fb | ||
|
|
2a4608cbb0 | ||
|
|
c8a9a6cdbc | ||
|
|
b2523fcdec | ||
|
|
429e46a665 | ||
|
|
7ec92ecc6d | ||
|
|
dc41eceb9e | ||
|
|
01fb51ba78 | ||
|
|
ac265ec495 | ||
|
|
b85184002c | ||
|
|
50afb69859 | ||
|
|
2993cce8b2 | ||
|
|
521487aa2e | ||
|
|
b00813bcb2 | ||
|
|
e737f5bf58 | ||
|
|
1fbcaf840f | ||
|
|
1dd4c41413 | ||
|
|
4210de270f | ||
|
|
f8c91a987f | ||
|
|
6724350665 | ||
|
|
5ab8eb34c5 | ||
|
|
8070909c04 | ||
|
|
d1808bab8c | ||
|
|
b23e5de5a1 | ||
|
|
457e2a1b1b | ||
|
|
8c17230586 | ||
|
|
1cb882a156 | ||
|
|
68abce8a04 | ||
|
|
cede5b6ca6 | ||
|
|
75c08a5b32 | ||
|
|
899bdd09e4 | ||
|
|
74cb9ce197 | ||
|
|
4b87e67ff3 | ||
|
|
1929495a99 | ||
|
|
2a7d2f4fdc | ||
|
|
db07e9f93a | ||
|
|
53d0ceb471 | ||
|
|
de6e341b07 | ||
|
|
cf5d721bee | ||
|
|
e3adc0417a | ||
|
|
4ff85debf1 | ||
|
|
2ea824533c | ||
|
|
6b6d90ac0f | ||
|
|
8b96d05da6 | ||
|
|
6d39432058 | ||
|
|
9c829d7a2e | ||
|
|
32986da448 | ||
|
|
16e36c7337 | ||
|
|
f18ea01530 | ||
|
|
efefd3960a | ||
|
|
244478bcee | ||
|
|
df26f85648 | ||
|
|
38381597d6 | ||
|
|
df77d5f8ce | ||
|
|
c99ac6c2df | ||
|
|
45e407db35 | ||
|
|
95f6c104d4 | ||
|
|
ca842472e5 | ||
|
|
bb2049cec1 | ||
|
|
036d904e31 | ||
|
|
e5760e6b03 | ||
|
|
2a550a3fe6 | ||
|
|
be2058d5d5 | ||
|
|
33482b0827 | ||
|
|
c3817d6144 | ||
|
|
91cbc74bb1 | ||
|
|
9cfaa3339b | ||
|
|
267f8d28c4 | ||
|
|
dbcb1253e8 | ||
|
|
7ff7bd2e8f | ||
|
|
1896379283 | ||
|
|
b4180a50dc | ||
|
|
a25f7629bd | ||
|
|
359ef86dd4 | ||
|
|
2b3accfe66 | ||
|
|
21a081b514 | ||
|
|
76bbb37c74 | ||
|
|
a87be4143a | ||
|
|
f937fc6ce1 | ||
|
|
22f79db72f | ||
|
|
ba7c395ce3 |
No files matched your search
@@ -2,9 +2,9 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["v1", "v2", "v3", "main"]
|
||||
branches: ["v1", "v2", "v3", "v4", "main"]
|
||||
pull_request:
|
||||
branches: ["v1", "v2", "v3", "main"]
|
||||
branches: ["v1", "v2", "v3", "v4", "main"]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
|
||||
+6
-1
@@ -21,4 +21,9 @@ skills/
|
||||
docs/superpowers/
|
||||
.vscode/
|
||||
openspec/
|
||||
uv.lock
|
||||
uv.lock
|
||||
# Local benchmark scripts — never commit
|
||||
scripts/run_k2_*.py
|
||||
scripts/llm.py
|
||||
scripts/benchmark_kimi*.json
|
||||
scripts/benchmark_kimi*.py
|
||||
@@ -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)
|
||||
+299
@@ -2,6 +2,305 @@
|
||||
|
||||
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
|
||||
|
||||
## 0.6.9 (2026-05-03)
|
||||
|
||||
- Fix: `source_file` path separators normalized to forward slashes at graph ingestion — same physical file emitted with backslashes (Windows AST extractor) and forward slashes (semantic subagents) now merges into one node instead of splitting into two disconnected components (#683)
|
||||
- Fix: two-phase cohesion re-clustering — communities with cohesion < 0.05 and ≥ 50 nodes are re-split, preventing doc-hub nodes (e.g. `CLAUDE.md`) from merging unrelated subsystems into one giant community (#683)
|
||||
- Fix: VS Code Copilot instructions rewritten to be prescriptive — agent's first tool call must read `GRAPH_REPORT.md`, explicit trigger list, narrow allowlist for raw source reads (#688)
|
||||
- Feat: `GRAPHIFY_OUT` env var overrides the output directory — accepts a relative name or absolute path, wires through `cache.py`, `watch.py`, and the CLI; useful for sharing one graph across multiple git worktrees (#686)
|
||||
- Fix: `graphify antigravity install` now auto-updates stale rules and workflow files on re-run instead of silently skipping them (#652)
|
||||
- Docs: README simplified — less dense, plain language; technical pipeline details moved to `docs/how-it-works.md`
|
||||
|
||||
## 0.6.8 (2026-05-03)
|
||||
|
||||
- Fix: `.graphifyignore` negation patterns (`!src/**`) now work correctly — when any `!` pattern is present, directory pruning is deferred to per-file checks so negated files inside ignored directories are reached (#676)
|
||||
- Fix: Antigravity slash command `/graphify` now appears in the command dropdown — workflow file now includes YAML frontmatter with `name: graphify` required for Antigravity discovery (#678)
|
||||
- Fix: Gemini CLI BeforeTool hook replaced `[ -f ... ] && echo` (bash-only) with cross-platform `python -c` using `json.dumps` — fixes hook failure on Windows CMD and Git Bash (#681)
|
||||
- Fix: Codex hook-check exits silently — resolves `additionalContext` rejection on Codex Desktop PreToolUse (#651)
|
||||
- Fix: `graphify install --platform codex` now writes absolute path to `graphify` executable — fixes PATH resolution in VS Code extension on Windows (#651)
|
||||
- Fix: thin communities (fewer than 3 concept nodes) are now omitted from the Communities section in `GRAPH_REPORT.md` by default; report header shows `(N total, M thin omitted)` and Knowledge Gaps collapses thin communities to one summary line (#664)
|
||||
|
||||
## 0.6.7 (2026-05-02)
|
||||
|
||||
- Feat: `graphify tree` — self-contained D3 v7 collapsible-tree HTML view of `graph.json`; expand/collapse controls, depth-based colours, hover inspector; XSS-safe (#557)
|
||||
- Feat: token-aware chunking with split-and-retry on truncation (#625)
|
||||
- Feat: cross-language edge context filters in MCP `query_graph` tool (#573)
|
||||
- Feat: dynamic `import()` extraction for JS/TS (#579)
|
||||
- Fix: `save_semantic_cache` crashed with `IsADirectoryError` when a node's `source_file` was a directory path — `p.exists()` → `p.is_file()` (#655)
|
||||
- Fix: `sanitize_label(None)` raised `TypeError` crashing `to_html` on graphs with null `source_file` rationale nodes — return `""` early (#656)
|
||||
- Fix: chunk-extraction prompt omitted `rationale` from valid `file_type` values — model hallucinated `concept` on every doc/paper run; explicit merge step added to all skill variants (#657)
|
||||
- Fix: `cost.json` always reported 0 tokens — chunk JSONs have placeholder zeros; orchestrator now globs and sums real token counts before merging (#658)
|
||||
## 0.6.6 (2026-05-02)
|
||||
|
||||
- Fix: `skill-windows.md` rewritten from PowerShell to bash — Claude Code on Windows uses git-bash so PowerShell syntax (`$null`, `$LASTEXITCODE`, `Select-Object`, `& (Get-Content ...)`, `Remove-Item`) caused exit code 49 failures; now mirrors `skill.md` structure with `python` added as fallback after `python3` for Windows Conda (#39)
|
||||
- Fix: wiki `to_wiki()` now clears stale articles before regenerating, preventing orphan .md accumulation (#558)
|
||||
- Fix: `_safe_filename()` in wiki.py now strips Windows-reserved characters (`< > : " / \ | ? *`) and caps length at 200 chars (#594)
|
||||
- Fix: rationale-node leakage in cross-file INFERRED call resolution — rationale nodes now excluded from name lookup; edge direction (`calls`, `rationale_for`) preserved correctly at JSON export (#576)
|
||||
- Feat: `.graphifyinclude` hidden path allowlist — opt specific hidden dirs into traversal (e.g. `.hermes/plans/**/*.md`) (#583)
|
||||
- Feat: `--no-viz` flag wired in `cluster-only`; `GRAPHIFY_VIZ_NODE_LIMIT` env var overrides 5000-node HTML threshold (#565)
|
||||
- Fix: stray colon SyntaxError in `skill-trae.md` `--cluster-only` block (#603)
|
||||
- Docs: skill INFERRED confidence score guidance changed to discrete rubric (0.55/0.65/0.75/0.85/0.95) backed by calibration data (#546)
|
||||
- Docs: skill `--update` prune output clarified — splits no-drift vs drift cases (#544)
|
||||
- Docs: skill `--update` merge step now calls `save_manifest` to prevent deleted files reappearing (#545)
|
||||
- Feat: `graphify tree` — self-contained D3 v7 collapsible-tree HTML view of `graph.json`; expand/collapse controls, depth-based colours, hover inspector; XSS-safe via `html.escape()` and `_js_safe()` (#557)
|
||||
|
||||
## 0.6.5 (2026-05-02)
|
||||
|
||||
- Fix: Kotlin call-walker now accepts both `simple_identifier` and `identifier` node types — PyPI's `tree_sitter_kotlin` grammar uses `identifier` while older forks use `simple_identifier`, causing zero `calls` edges to be emitted (#659)
|
||||
- Feat: community sidebar now uses checkbox-based multi-select instead of show/hide buttons — supports indeterminate "select all" state (#647)
|
||||
- Feat: `graphify update --force` and `GRAPHIFY_FORCE=1` env var — bypass the node-count safety check after refactors that legitimately shrink the graph (#639)
|
||||
- Fix: Codex PreToolUse hook on Windows — replaced `python3 -c "..."` inline command (fails on Conda where only `python` exists, and breaks PowerShell JSON parsing) with `graphify hook-check`, a new shell-agnostic subcommand. Re-run `graphify codex install` to regenerate the hook (#651, #522)
|
||||
|
||||
## 0.6.4 (2026-05-02)
|
||||
|
||||
- Fix: Codex PreToolUse hook failed on Windows — `[ -f ]` is bash-only and crashes on `cmd.exe`; replaced with a cross-platform Python one-liner (`pathlib.Path.exists()`) (#651)
|
||||
|
||||
## 0.6.3 (2026-05-02)
|
||||
|
||||
- Fix: incremental rebuild (`graphify update`, post-commit hook) dropped INFERRED/AMBIGUOUS semantic nodes extracted from code files — node preservation now filters by ID membership in the new AST output instead of `file_type`, so LLM-extracted call/data-flow edges survive code-only rebuilds (#653)
|
||||
- Fix: post-commit and post-checkout hooks blocked `git commit` for the full rebuild duration (hours on large repos) — rebuilds now detach via `nohup & disown`, git returns in ~100ms, log written to `~/.cache/graphify-rebuild.log` (#650)
|
||||
- Fix: cross-file INFERRED `calls` resolution used a last-write-wins name map, causing common short names (`log`, `execute`, `find`) to accumulate hundreds of spurious edges and dominate god_nodes ranking — resolution now skips any callee name that matches 2+ candidates (ambiguous, no import evidence to pick the right target) (#543)
|
||||
- Fix: `cluster-only` command crashed on graphs with >5000 nodes due to unguarded `to_html` call — now wrapped in try/except ValueError matching the watch/hook path (#541)
|
||||
|
||||
## 0.6.2 (2026-05-01)
|
||||
|
||||
- Fix: Kimi K2.6 reasoning mode consumed entire token budget leaving `content` empty — thinking now disabled on Moonshot calls so graphs actually populate (#623)
|
||||
- Fix: `graphify update` / `graphify watch` never persisted the manifest, so every subsequent `--update` re-extracted all files — manifest now saved after each rebuild (#621)
|
||||
- Fix: inline comments in `.graphifyignore` (e.g. `vendor/ # legacy`) now stripped correctly — whitespace + `#` suffix is treated as a comment, `path#hash.py` preserved (#605)
|
||||
- Fix: `graphify query "FunctionName"` now returns the exact matching node first instead of high-degree hub modules hijacking the output — 100-point exact-match bonus + seeds render before BFS expansion (#638)
|
||||
- Fix: concurrent AST extractors raced on a shared `.tmp` cache file — each writer now gets a unique tempfile via `mkstemp`, eliminating cache corruption under parallel extraction (#589)
|
||||
- Fix: `_clone_repo` branch names starting with `-` could be interpreted as git flags — validation added, `--` separator inserted before positional args (#589)
|
||||
- Fix: replaced `html2text` (GPL-3.0) with `markdownify` (MIT) — removes the only copyleft dependency from a MIT project (#586)
|
||||
- Fix: `--update` re-extracted files whose mtime was bumped by sync tools (Obsidian, Nextcloud) without content changes — manifest now stores content hash alongside mtime; mtime bump triggers an MD5 check before re-extraction (#593)
|
||||
- Feat: R language support — `.r` files classified as code and processed via LLM semantic extraction (#617)
|
||||
- Feat: extensionless shell scripts now detected via shebang (`#!/bin/bash`, `#!/usr/bin/env python3`, etc.) and included as code (#619)
|
||||
- Fix: cross-language INFERRED `calls` edges (e.g. Python→TypeScript name collision) no longer appear as top surprising connections in GRAPH_REPORT.md (#630)
|
||||
- Fix: `cluster-only` CLI silently flipped directed graphs to undirected — `directed` flag now read from graph.json and preserved through re-clustering (#590)
|
||||
- Fix: Windows UNC / extended-length paths (`\\?\C:\...`) now normalize to consistent cache keys (#629)
|
||||
- Fix: `.graphifyignore` negation patterns (`!src/lib/secrets.ts`) now work — full last-match-wins evaluation with `!` un-ignore support (#628)
|
||||
|
||||
## 0.6.1 (2026-05-01)
|
||||
|
||||
- Fix: `.graphifyignore` discovery now uses correct gitignore semantics — outer rules are loaded first so inner (closer) rules always win via last-match-wins, matching standard gitignore behavior (#643)
|
||||
- Fix: without a VCS root, `.graphifyignore` discovery is now hermetic to the scan folder — no leakage across sibling projects in a shared workspace (#643)
|
||||
- Fix: anchored patterns (leading `/`) in a parent `.graphifyignore` now correctly apply only relative to their own directory, not the scan root (#643)
|
||||
- Fix: trailing spaces in patterns are now handled per gitignore spec — unescaped trailing spaces are stripped, `vendor\ ` (escaped) is preserved (#643)
|
||||
|
||||
## 0.6.0 (2026-05-01)
|
||||
|
||||
- Feat: SQL AST extractor — `.sql` files now processed deterministically via tree-sitter. Extracts tables, views, functions/procedures, foreign key references, and FROM/JOIN reads_from edges. No LLM needed. Requires `pip install 'graphifyy[sql]'` (#349)
|
||||
- Feat: `xlsx_extract_structure()` utility — extracts sheet names, named tables, and column headers from .xlsx files as structural nodes
|
||||
|
||||
## 0.5.7 (2026-04-30)
|
||||
|
||||
- Feat: YAML/YML files now indexed for semantic extraction — Kubernetes, Kustomize, Helm, and any YAML corpus now picked up automatically (#633)
|
||||
|
||||
## 0.5.6 (2026-04-30)
|
||||
|
||||
- Fix: `NameError: name '_os' is not defined` crash after `graphify update` — this was fixed in v5 branch but not released to PyPI (#618, #612)
|
||||
|
||||
## 0.5.5 (2026-04-29)
|
||||
|
||||
- Feat: Kimi K2.6 backend — `pip install 'graphifyy[kimi]'` + `MOONSHOT_API_KEY` routes semantic extraction through Kimi K2.6. 3-6x richer relation extraction at ~3x lower cost. Claude remains default; Kimi is opt-in.
|
||||
- Fix: phantom god nodes (#598) — member-call callees (`this.logger.log()` → `log`) no longer cross-file resolved. Go package-qualified calls (`pkg.Func()`) correctly preserved. Affects JS/TS, Go, Rust, Swift, Kotlin, Scala, PHP, C++, C#, Zig, Elixir.
|
||||
- Fix: `concept` file_type no longer triggers validation warnings (#601)
|
||||
- Fix: `graphify update` remembers scan root via `graphify-out/.graphify_root` — no path argument needed on subsequent runs
|
||||
- Fix: Kimi K2.6 temperature 400 error — temperature param is now skipped for Kimi backends (model enforces its own fixed value) (#610)
|
||||
- Fix: community labels deleted in Step 9 cleanup — `.graphify_labels.json` is now preserved so wiki/obsidian/HTML retain human-readable names after re-cluster (#608)
|
||||
- Fix: `NameError: name '_os' is not defined` in `graphify update` Kimi tip (#612)
|
||||
- Fix: `SyntaxWarning` in `__main__.py` for shell glob pattern with backslash escapes
|
||||
- Fix: Python upper bound removed — `requires-python = ">=3.10"` now supports Python 3.14+ (#607)
|
||||
|
||||
## 0.5.4 (2026-04-28)
|
||||
|
||||
- Fix: SSRF DNS rebinding — `safe_fetch` now patches `socket.getaddrinfo` for the full request duration (#591)
|
||||
- Fix: yt-dlp SSRF bypass — `download_audio` now calls `validate_url` before handing URL to yt-dlp (#592)
|
||||
|
||||
## 0.5.3 (2026-04-27)
|
||||
|
||||
- Fix: cache namespace — AST and semantic entries now live in `cache/ast/` and `cache/semantic/` subdirectories; flat entries read as migration fallback
|
||||
|
||||
## 0.5.2 (2026-04-26)
|
||||
|
||||
- Fix: PreToolUse hook now matches on `Bash` instead of `Glob|Grep` for Claude Code v2.1.117+
|
||||
|
||||
## 0.5.1 (2026-04-25)
|
||||
|
||||
- Fix: node ID collision for same-named files in different directories
|
||||
- Fix: `source_file` paths relativized before return so `graph.json` is portable
|
||||
- Fix: desync guard — `to_json()` returns bool; report only written on successful JSON write
|
||||
- Feat: TypeScript `@/` path aliases resolved via `tsconfig.json`
|
||||
- Feat: Show All / Hide All buttons in HTML community panel
|
||||
|
||||
## 0.5.0 (2026-04-24)
|
||||
|
||||
- Feat: `graphify clone <github-url>` — clone and graph any public repo
|
||||
- Feat: `graphify merge-graphs` — combine multiple `graph.json` outputs into one cross-repo graph
|
||||
- Feat: `CLAUDE_CONFIG_DIR` support in `graphify install`
|
||||
- Feat: shrink guard — `to_json()` refuses to overwrite with a smaller graph
|
||||
- Feat: `build_merge()` for safe incremental updates
|
||||
- Feat: duplicate node deduplication via `deduplicate_by_label()`
|
||||
- Fix: `graphify-out/` excluded from source scanning
|
||||
|
||||
## 0.4.23 (2026-04-18)
|
||||
|
||||
- Fix: stale skill version warning persists after running `graphify install` when multiple platforms were previously installed — `graphify install` now refreshes `.graphify_version` in all other known skill directories so the warning clears across the board (#178)
|
||||
- Fix: `.html` files silently skipped during detection — added `.html` to `DOC_EXTENSIONS`; HTML pages, docs, and web project content now indexed correctly (#260)
|
||||
- Fix: `_rebuild_code` (watch/update/hook) fails entirely on graphs > 5000 nodes because `to_html` raises `ValueError` — wrapped in its own try/except so `graph.json` and `GRAPH_REPORT.md` always land; stale `graph.html` from a previous smaller run is removed (#432)
|
||||
- Fix: Go stdlib imports (e.g. `"context"`) produced `imports_from` edges pointing at local files of the same basename — Go import node IDs now prefixed `go_pkg_` using the full import path, eliminating false cycle-dependency pairs (#431)
|
||||
|
||||
## 0.4.22 (2026-04-18)
|
||||
|
||||
- Fix: AST cache written to `src/graphify-out/cache/` instead of project root when all code files share a common prefix like `src/` — `extract()` now called with explicit `cache_root=watch_path` in `_rebuild_code` and `cache_root=Path('.')` in the Codex skill AST step (#429)
|
||||
- Fix: `.mdx` files silently skipped during detection — added `.mdx` to `DOC_EXTENSIONS` in `detect.py`; MDX-based corpora (Next.js, Docusaurus, Astro) now indexed correctly (#428)
|
||||
|
||||
## 0.4.21 (2026-04-17)
|
||||
|
||||
- Fix: `graphify cluster-only` crashed with `KeyError: 'total_files'` in `report.py` — cluster-only skips detection so the stats dict was empty; now passes a `warning` key so the report skips the file-stats section (#422)
|
||||
- Fix: `/graphify --update` dropped all existing graph nodes — the merge block built a correct in-memory `G_existing` but never wrote it back to `.graphify_extract.json`, so Step 4 rebuilt from the new-extraction-only file; merged result is now serialized back before Step 4 runs (#423)
|
||||
|
||||
## 0.4.20 (2026-04-17)
|
||||
|
||||
- Fix: JS/MJS `imports_from` edges were silently dropped for files that use `../subdir/file.mjs` style imports — `Path.parent / raw` left `..` segments unnormalized, so the generated target ID didn't match the actual file node ID. Fixed with `os.path.normpath` (#414)
|
||||
- Fix: `graphify update .` and `graphify cluster-only` now generate `graph.html` alongside `graph.json` and `GRAPH_REPORT.md` — previously only the skill generated the interactive HTML (#418)
|
||||
|
||||
## 0.4.19 (2026-04-17)
|
||||
|
||||
- Fix: AST and semantic extraction no longer produce mismatched node IDs — `build_from_json` now normalises IDs before dropping edges, so edges survive when the LLM generates slightly different casing or punctuation than the AST extractor (#390)
|
||||
- Fix: cross-file call resolution extended to Go, Rust, Zig, PowerShell, and Elixir — unresolved callees are now saved as `raw_calls` and resolved globally in a post-pass, matching existing behaviour for Python, Swift, Java, C#, Kotlin, Scala, Ruby, and PHP (#298)
|
||||
- Fix: Windows `graphify-out/graphify-out` nesting bug — `cache_dir` and `_rebuild_code` in watch.py now call `.resolve()` on the root path, preventing a nested output directory when graphify is run from a subdirectory (#410)
|
||||
- Fix: `graphify hook install` now respects `core.hooksPath` git config (used by Husky and similar tools) — hooks are written to the configured path instead of always `.git/hooks` (#401)
|
||||
- Fix: Kiro skill YAML frontmatter — `description` value is now quoted and colons replaced with dashes, preventing a parse error in Kiro's YAML loader (#385)
|
||||
- Docs: added Windows PATH tip (`%APPDATA%\Python\PythonXY\Scripts`) and macOS pipx tip (`pipx ensurepath`) to the install section (#413)
|
||||
- Docs: added team workflow section — committing `graphify-out/`, `.graphifyignore` usage, and recommended `.gitignore` additions (#369)
|
||||
|
||||
## 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
|
||||
|
||||
@@ -1,90 +1,89 @@
|
||||
# graphify
|
||||
<p align="center">
|
||||
<a href="https://graphifylabs.ai"><img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/></a>
|
||||
</p>
|
||||
|
||||
[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja-JP.md) | [한국어](README.ko-KR.md)
|
||||
<p align="center">
|
||||
🇺🇸 <a href="README.md">English</a> | 🇨🇳 <a href="docs/translations/README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="docs/translations/README.ja-JP.md">日本語</a> | 🇰🇷 <a href="docs/translations/README.ko-KR.md">한국어</a> | 🇩🇪 <a href="docs/translations/README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="docs/translations/README.fr-FR.md">Français</a> | 🇪🇸 <a href="docs/translations/README.es-ES.md">Español</a> | 🇮🇳 <a href="docs/translations/README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="docs/translations/README.pt-BR.md">Português</a> | 🇷🇺 <a href="docs/translations/README.ru-RU.md">Русский</a> | 🇸🇦 <a href="docs/translations/README.ar-SA.md">العربية</a> | 🇮🇹 <a href="docs/translations/README.it-IT.md">Italiano</a> | 🇵🇱 <a href="docs/translations/README.pl-PL.md">Polski</a> | 🇳🇱 <a href="docs/translations/README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="docs/translations/README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="docs/translations/README.uk-UA.md">Українська</a> | 🇻🇳 <a href="docs/translations/README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="docs/translations/README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="docs/translations/README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="docs/translations/README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="docs/translations/README.ro-RO.md">Română</a> | 🇨🇿 <a href="docs/translations/README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="docs/translations/README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="docs/translations/README.da-DK.md">Dansk</a> | 🇳🇴 <a href="docs/translations/README.no-NO.md">Norsk</a> | 🇭🇺 <a href="docs/translations/README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="docs/translations/README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="docs/translations/README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://pypi.org/project/graphifyy/)
|
||||
[](https://pepy.tech/project/graphifyy)
|
||||
[](https://github.com/sponsors/safishamsi)
|
||||
<p align="center">
|
||||
<a href="https://safishamsi.gumroad.com/l/qetvlo"><img src="https://img.shields.io/badge/Book-The%20Memory%20Layer-2ea44f?style=flat&logo=gitbook&logoColor=white" alt="The Memory Layer"/></a>
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
</p>
|
||||
|
||||
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, Aider, OpenClaw, Factory Droid, or Trae - 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.
|
||||
<p align="center">
|
||||
<a href="https://star-history.com/#safishamsi/graphify&Date">
|
||||
<img src="https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date" alt="Star History Chart" width="600"/>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
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. 20 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).
|
||||
Type `/graphify` in your AI coding assistant and it maps your entire project — code, docs, PDFs, images, videos — into a knowledge graph you can query instead of grepping through files.
|
||||
|
||||
> 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.
|
||||
Works in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Pi, and Google Antigravity.
|
||||
|
||||
```
|
||||
/graphify . # works on any folder - your codebase, notes, papers, anything
|
||||
/graphify .
|
||||
```
|
||||
|
||||
That's it. You get three files:
|
||||
|
||||
```
|
||||
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
|
||||
├── graph.html open in any browser — click nodes, filter, search
|
||||
├── GRAPH_REPORT.md the highlights: key concepts, surprising connections, suggested questions
|
||||
└── graph.json the full graph — query it anytime without re-reading your files
|
||||
```
|
||||
|
||||
Add a `.graphifyignore` file to exclude folders you don't want in the graph:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
Same syntax as `.gitignore`. Patterns match against file paths relative to the folder you run graphify on.
|
||||
|
||||
## How it works
|
||||
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
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), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), or [Trae](https://trae.ai)
|
||||
**Requires Python 3.10+**
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
uv tool install graphifyy && graphify install
|
||||
# or: pipx install graphifyy && graphify install
|
||||
# or: pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **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`.
|
||||
> **Official package:** The PyPI package is `graphifyy` (double-y). Other `graphify*` packages on PyPI are not affiliated. The CLI command is still `graphify`.
|
||||
|
||||
### Platform support
|
||||
> **`graphify: command not found`?** Use `uv tool install graphifyy` or `pipx install graphifyy` — both put the CLI on PATH automatically. With plain `pip`, add `~/.local/bin` (Linux) or `~/Library/Python/3.x/bin` (Mac) to your PATH, or run `python -m graphify`.
|
||||
|
||||
### Pick your platform
|
||||
|
||||
| Platform | Install command |
|
||||
|----------|----------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (auto-detected) or `graphify install --platform windows` |
|
||||
| Claude Code (Windows) | `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` |
|
||||
| Pi coding agent | `graphify install --platform pi` |
|
||||
| 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 users: also add `multi_agent = true` under `[features]` in `~/.codex/config.toml`.
|
||||
> Codex uses `$graphify` instead of `/graphify`.
|
||||
|
||||
Then open your AI coding assistant and type:
|
||||
---
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
## Make your assistant always use the graph
|
||||
|
||||
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:
|
||||
Run this once in your project after building a graph:
|
||||
|
||||
| Platform | Command |
|
||||
|----------|---------|
|
||||
@@ -92,6 +91,7 @@ After building a graph, run this once in your project:
|
||||
| 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` |
|
||||
@@ -99,218 +99,214 @@ After building a graph, run this once in your project:
|
||||
| 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` |
|
||||
| Pi coding agent | `graphify pi 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.
|
||||
This writes a small config file that tells your assistant to read `GRAPH_REPORT.md` before answering questions about your codebase. On platforms that support hooks (Claude Code, Codex, Gemini CLI), a hook fires automatically before every file-read call — your assistant navigates by the graph instead of grepping through everything.
|
||||
|
||||
**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.
|
||||
Uninstall with the matching command (e.g. `graphify claude uninstall`).
|
||||
|
||||
**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.
|
||||
## What's in the report
|
||||
|
||||
**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.
|
||||
- **God nodes** — the most-connected concepts in your project. Everything flows through these.
|
||||
- **Surprising connections** — links between things that live in different files or modules. Ranked by how unexpected they are.
|
||||
- **The "why"** — inline comments (`# NOTE:`, `# WHY:`, `# HACK:`), docstrings, and design rationale from docs are extracted as separate nodes linked to the code they explain.
|
||||
- **Suggested questions** — 4–5 questions the graph is uniquely positioned to answer.
|
||||
- **Confidence tags** — every inferred relationship is marked `EXTRACTED`, `INFERRED`, or `AMBIGUOUS`. You always know what was found vs guessed.
|
||||
|
||||
**Aider and OpenClaw, Factory Droid, Trae** write the same rules to `AGENTS.md` in your project root. These platforms don't support tool hooks, so AGENTS.md is the always-on mechanism.
|
||||
---
|
||||
|
||||
**GitHub Copilot CLI** copies the skill to `~/.copilot/skills/graphify/SKILL.md`. Run `graphify copilot install` to set it up.
|
||||
## What files it handles
|
||||
|
||||
Uninstall with the matching uninstall command (e.g. `graphify claude uninstall`).
|
||||
| Type | Extensions |
|
||||
|------|-----------|
|
||||
| Code (25 languages) | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .jl .vue .svelte .sql` |
|
||||
| Docs | `.md .mdx .html .txt .rst .yaml .yml` |
|
||||
| Office | `.docx .xlsx` (requires `pip install graphifyy[office]`) |
|
||||
| PDFs | `.pdf` |
|
||||
| Images | `.png .jpg .webp .gif` |
|
||||
| Video / Audio | `.mp4 .mov .mp3 .wav` and more (requires `pip install graphifyy[video]`) |
|
||||
| YouTube / URLs | any video URL (requires `pip install graphifyy[video]`) |
|
||||
|
||||
**Always-on vs explicit trigger — what's the difference?**
|
||||
Code is extracted locally with no API calls (AST via tree-sitter). Everything else goes through your AI assistant's model API.
|
||||
|
||||
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:
|
||||
## Common commands
|
||||
|
||||
```bash
|
||||
graphify query "show the auth flow" --graph graphify-out/graph.json
|
||||
/graphify . # build graph for current folder
|
||||
/graphify ./docs --update # re-extract only changed files
|
||||
/graphify . --cluster-only # rerun clustering without re-extracting
|
||||
/graphify . --no-viz # skip the HTML, just the report + JSON
|
||||
/graphify . --wiki # build a markdown wiki from the graph
|
||||
|
||||
/graphify query "what connects auth to the database?"
|
||||
/graphify path "UserService" "DatabasePool"
|
||||
/graphify explain "RateLimiter"
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper and add it
|
||||
/graphify add <youtube-url> # transcribe and add a video
|
||||
|
||||
graphify hook install # auto-rebuild on git commit
|
||||
graphify merge-graphs a.json b.json # combine two graphs
|
||||
```
|
||||
|
||||
See the [full command reference](#full-command-reference) below.
|
||||
|
||||
---
|
||||
|
||||
## Ignoring files
|
||||
|
||||
Create a `.graphifyignore` in your project root — same syntax as `.gitignore`, including `!` negation:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
|
||||
# only index src/, ignore everything else
|
||||
*
|
||||
!src/
|
||||
!src/**
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Team setup
|
||||
|
||||
`graphify-out/` is meant to be committed to git so everyone on the team starts with a map.
|
||||
|
||||
**Recommended `.gitignore` additions:**
|
||||
```
|
||||
graphify-out/manifest.json # mtime-based, breaks after git clone
|
||||
graphify-out/cost.json # local only
|
||||
# graphify-out/cache/ # optional: commit for speed, skip to keep repo small
|
||||
```
|
||||
|
||||
**Workflow:**
|
||||
1. One person runs `/graphify .` and commits `graphify-out/`.
|
||||
2. Everyone pulls — their assistant reads the graph immediately.
|
||||
3. Run `graphify hook install` to auto-rebuild after each commit (AST only, no API cost).
|
||||
4. When docs or papers change, run `/graphify --update` to refresh those nodes.
|
||||
|
||||
---
|
||||
|
||||
## Using the graph directly
|
||||
|
||||
```bash
|
||||
# query the graph from the terminal
|
||||
graphify query "show the auth flow"
|
||||
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
|
||||
# expose the graph as an MCP server (for repeated tool-call access)
|
||||
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`.
|
||||
The MCP server gives your assistant structured access: `query_graph`, `get_node`, `get_neighbors`, `shortest_path`.
|
||||
|
||||
<details>
|
||||
<summary>Manual install (curl)</summary>
|
||||
> **WSL / Linux note:** Ubuntu ships `python3`, not `python`. Use a venv to avoid conflicts:
|
||||
> ```bash
|
||||
> python3 -m venv .venv && .venv/bin/pip install "graphifyy[mcp]"
|
||||
> ```
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/graphify
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
|
||||
> ~/.claude/skills/graphify/SKILL.md
|
||||
```
|
||||
---
|
||||
|
||||
Add to `~/.claude/CLAUDE.md`:
|
||||
## Privacy
|
||||
|
||||
```
|
||||
- **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.
|
||||
```
|
||||
- **Code files** — processed locally via tree-sitter. Nothing leaves your machine.
|
||||
- **Video / audio** — transcribed locally with faster-whisper. Nothing leaves your machine.
|
||||
- **Docs, PDFs, images** — sent to your AI assistant's model API (Anthropic, OpenAI, etc.) using your own API key.
|
||||
- No telemetry, no usage tracking, no analytics.
|
||||
|
||||
</details>
|
||||
---
|
||||
|
||||
## Usage
|
||||
## Full command reference
|
||||
|
||||
```
|
||||
/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 --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 ./raw --mode deep # more aggressive relationship extraction
|
||||
/graphify ./raw --update # re-extract only changed files
|
||||
/graphify ./raw --directed # preserve edge direction
|
||||
/graphify ./raw --cluster-only # rerun clustering on existing graph
|
||||
/graphify ./raw --no-viz # skip HTML visualization
|
||||
/graphify ./raw --obsidian # generate Obsidian vault
|
||||
/graphify ./raw --wiki # build agent-crawlable markdown wiki
|
||||
/graphify ./raw --svg # export graph.svg
|
||||
/graphify ./raw --graphml # export for Gephi / yEd
|
||||
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
|
||||
/graphify ./raw --neo4j-push bolt://localhost:7687
|
||||
/graphify ./raw --watch # auto-sync as files change
|
||||
/graphify ./raw --mcp # start MCP stdio server
|
||||
|
||||
/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 https://www.youtube.com/watch?v=... # 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 add https://arxiv.org/abs/1706.03762
|
||||
/graphify add <video-url>
|
||||
/graphify add https://... --author "Name" --contributor "Name"
|
||||
|
||||
/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 query "..." --dfs --budget 1500
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
/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
|
||||
|
||||
# git hooks - platform-agnostic, rebuild graph on commit and branch switch
|
||||
graphify hook install
|
||||
graphify hook install # post-commit + post-checkout hooks
|
||||
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 (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 claude install / uninstall
|
||||
graphify codex install / uninstall
|
||||
graphify opencode install
|
||||
graphify cursor install / uninstall
|
||||
graphify gemini install / uninstall
|
||||
graphify copilot install / uninstall
|
||||
graphify aider install / uninstall
|
||||
graphify claw install / uninstall
|
||||
graphify droid install / uninstall
|
||||
graphify trae install / uninstall
|
||||
graphify trae-cn install / uninstall
|
||||
graphify hermes install / uninstall
|
||||
graphify kiro install / uninstall
|
||||
graphify antigravity install / uninstall
|
||||
|
||||
# query 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 clone https://github.com/karpathy/nanoGPT
|
||||
graphify merge-graphs a.json b.json --out merged.json
|
||||
graphify watch ./src
|
||||
graphify check-update ./src
|
||||
graphify update ./src
|
||||
graphify cluster-only ./my-project
|
||||
```
|
||||
|
||||
Works with any mix of file types:
|
||||
---
|
||||
|
||||
| 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` | AST via tree-sitter + call-graph + 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` | 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]`) |
|
||||
## Learn more
|
||||
|
||||
## What you get
|
||||
- [How it works](docs/how-it-works.md) — the extraction pipeline, community detection, confidence scoring, benchmarks
|
||||
- [ARCHITECTURE.md](ARCHITECTURE.md) — module breakdown, how to add a language
|
||||
- [Optional integrations](docs/docker-mcp-sqlite.md) — Docker MCP Toolkit + SQLite
|
||||
|
||||
**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.
|
||||
## Built on graphify — Penpax
|
||||
|
||||
**Suggested questions** - 4-5 questions the graph is uniquely positioned to answer
|
||||
[**Penpax**](https://graphifylabs.ai) is the always-on layer built on top of graphify — it applies the same graph approach to your entire working life: meetings, browser history, emails, files, and code, updating continuously in the background.
|
||||
|
||||
**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.
|
||||
Built for people whose work lives across hundreds of conversations and documents they can never fully reconstruct. No cloud, fully on-device.
|
||||
|
||||
**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.
|
||||
**Free trial launching soon.** [Join the waitlist →](https://graphifylabs.ai)
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
**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 | 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/) |
|
||||
|
||||
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
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantic extraction via Claude (Claude Code), GPT-4 (Codex), or whichever model your platform runs. No Neo4j required, no server, runs entirely locally.
|
||||
|
||||
## What we are building next
|
||||
|
||||
graphify is the graph layer. We are building [Penpax](https://safishamsi.github.io/penpax.ai) 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
|
||||
|
||||
[](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.
|
||||
**Worked examples** are the most useful contribution. Run `/graphify` on a real corpus, save the output to `worked/{slug}/`, write an honest `review.md` covering what the graph got right and wrong, and open a PR.
|
||||
|
||||
**Extraction bugs** - open an issue with the input file, the cache entry (`graphify-out/cache/`), and what was missed or invented.
|
||||
**Extraction bugs** — open an issue with the input file, the cache entry (`graphify-out/cache/`), and what was missed or wrong.
|
||||
|
||||
See [ARCHITECTURE.md](ARCHITECTURE.md) for module responsibilities and how to add a language.
|
||||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# Docker MCP Toolkit + SQLite MCP server
|
||||
|
||||
A reproducible runbook for installing the **SQLite MCP server** into the
|
||||
[Docker MCP Toolkit](https://docs.docker.com/desktop/features/mcp/) so any
|
||||
connected MCP client (Claude Code, Claude Desktop, Cursor, VS Code, etc.) gains
|
||||
six SQLite tools: `read_query`, `write_query`, `create_table`, `list_tables`,
|
||||
`describe_table`, and `append_insight`.
|
||||
|
||||
This document is *not* required to use graphify — it lives here as a known-good
|
||||
recipe for users who want a lightweight, persistent SQL workspace exposed to
|
||||
their AI clients alongside graphify's knowledge-graph tools.
|
||||
|
||||
## Why SQLite (and not `sqlite-mcp-server`)
|
||||
At time of writing the catalog ships two SQLite MCP images:
|
||||
|
||||
| Catalog name | Image | Status |
|
||||
| ------------------- | ---------------------- | ------ |
|
||||
| `SQLite` | `mcp/sqlite` | Marked "Archived" in catalog metadata, but **boots and serves correctly** |
|
||||
| `sqlite-mcp-server` | `mcp/sqlite-mcp-server`| **Broken**: entrypoint `/app/.venv/bin/mcp-server-sqlite` does not exist in the published layer |
|
||||
|
||||
Use `SQLite` (`mcp/sqlite`) until the newer image is fixed upstream.
|
||||
|
||||
## Prerequisites
|
||||
- Docker Desktop running and healthy
|
||||
- `docker info` returns a `Server Version`
|
||||
- Public socket present at `/var/run/docker.sock` (or its symlink to
|
||||
`~/.docker/run/docker.sock`)
|
||||
- Docker MCP Toolkit CLI plugin (`docker mcp`)
|
||||
- Bundled with recent Docker Desktop releases; `docker mcp --version` should
|
||||
print a version string
|
||||
|
||||
## Install
|
||||
```bash
|
||||
# Add the working SQLite server to the default MCP profile
|
||||
docker mcp profile server add default \
|
||||
--server catalog://mcp/docker-mcp-catalog/SQLite
|
||||
|
||||
# Pre-pull the image so the first tool call is fast
|
||||
docker pull mcp/sqlite:latest
|
||||
```
|
||||
|
||||
Verify the profile now contains both `fetch` (built-in) and `SQLite`:
|
||||
```bash
|
||||
docker mcp profile show default | grep -E '^[[:space:]]+name:'
|
||||
```
|
||||
|
||||
Expected output:
|
||||
```
|
||||
name: fetch
|
||||
name: SQLite
|
||||
```
|
||||
|
||||
The Docker MCP gateway should now expose 6 additional tools:
|
||||
```bash
|
||||
docker mcp tools count
|
||||
# → 15 tools (was 9 before adding SQLite)
|
||||
```
|
||||
|
||||
## Smoke test
|
||||
The CLI can call MCP tools directly (each call boots a fresh gateway, ~5s
|
||||
overhead per call):
|
||||
```bash
|
||||
docker mcp tools call list_tables
|
||||
docker mcp tools call create_table \
|
||||
query='CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY AUTOINCREMENT, body TEXT NOT NULL, created_at TEXT DEFAULT CURRENT_TIMESTAMP)'
|
||||
docker mcp tools call write_query \
|
||||
query="INSERT INTO notes(body) VALUES ('first row'), ('second row')"
|
||||
docker mcp tools call read_query \
|
||||
query='SELECT * FROM notes ORDER BY id'
|
||||
docker mcp tools call describe_table table_name=notes
|
||||
docker mcp tools call append_insight insight='3 rows inserted; aggregates work.'
|
||||
```
|
||||
|
||||
`read_query` should return the inserted rows with timestamps.
|
||||
|
||||
## Storage layout
|
||||
Database file lives in a Docker named volume `mcp-sqlite`, mounted at `/mcp`
|
||||
inside containers:
|
||||
```
|
||||
mcp-sqlite (named volume) → /mcp/db.sqlite
|
||||
```
|
||||
|
||||
Inspect from the host:
|
||||
```bash
|
||||
docker volume inspect mcp-sqlite
|
||||
docker run --rm -v mcp-sqlite:/mcp:ro alpine ls -la /mcp
|
||||
docker run --rm -v mcp-sqlite:/mcp:ro keinos/sqlite3 \
|
||||
sqlite3 /mcp/db.sqlite '.schema'
|
||||
```
|
||||
|
||||
The volume persists across `docker run --rm` invocations of the SQLite MCP
|
||||
container, so writes from one MCP tool call are visible to the next.
|
||||
|
||||
## Wiring into MCP clients
|
||||
Connect once per client; the gateway exposes every server in the active profile:
|
||||
```bash
|
||||
docker mcp client connect claude-code # already connected for many users
|
||||
docker mcp client connect cursor
|
||||
docker mcp client connect vscode
|
||||
docker mcp client connect claude-desktop
|
||||
# Supported: claude-code, claude-desktop, cline, codex, continue, crush,
|
||||
# cursor, gemini, goose, gordon, kiro, lmstudio, opencode, sema4,
|
||||
# vscode, zed
|
||||
```
|
||||
|
||||
Verify wiring:
|
||||
```bash
|
||||
docker mcp client ls
|
||||
```
|
||||
|
||||
## Uninstall / reset
|
||||
```bash
|
||||
# Remove server from the profile
|
||||
docker mcp profile server remove default SQLite
|
||||
|
||||
# Drop the database volume (irreversible)
|
||||
docker volume rm mcp-sqlite
|
||||
|
||||
# Remove the image
|
||||
docker rmi mcp/sqlite:latest
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
- **`starting client: calling "initialize": EOF`** — the requested server
|
||||
failed its MCP handshake. Run the image directly to see the error:
|
||||
```bash
|
||||
printf '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"smoke","version":"0.0"}}}\n' \
|
||||
| docker run --rm -i -v mcp-sqlite:/mcp <image-ref> --db-path /mcp/db.sqlite
|
||||
```
|
||||
Common causes: missing entrypoint binary in the image (the
|
||||
`sqlite-mcp-server` failure mode) or missing required env/secrets.
|
||||
- **`cannot use --enable-all-servers with --servers flag`** — these gateway
|
||||
args are mutually exclusive; pick one.
|
||||
- **No new tools appear in `docker mcp tools count` after install** — the
|
||||
gateway may be running with `dynamic-tools` enabled, exposing only meta-tools
|
||||
(`mcp-add`, `mcp-find`, …) until a profile is activated mid-session. Either
|
||||
invoke `docker mcp tools` (which spins up an ephemeral gateway against the
|
||||
default profile) or call `mcp-activate-profile` from inside an MCP session.
|
||||
@@ -0,0 +1,90 @@
|
||||
# How graphify works
|
||||
|
||||
## The three passes
|
||||
|
||||
graphify processes your files in three passes:
|
||||
|
||||
**Pass 1 — Code structure (free, no API calls)**
|
||||
Tree-sitter parses your code files and extracts classes, functions, imports, call graphs, and inline comments. This runs locally with no LLM involved. 25 languages supported. SQL files get special treatment: tables, views, foreign keys, and JOIN relationships are extracted deterministically.
|
||||
|
||||
**Pass 2 — Video and audio (local, no API calls)**
|
||||
Video and audio files are transcribed with faster-whisper. To focus the transcript on your domain, the transcription prompt is seeded with your top god nodes (the most-connected concepts in your code graph so far). Transcripts are cached — re-runs skip already-processed files.
|
||||
|
||||
**Pass 3 — Docs, papers, images (Claude subagents, costs tokens)**
|
||||
Claude runs in parallel over markdown, PDFs, images, and transcripts. Each subagent reads a batch of files and outputs a JSON fragment: nodes, edges, and any group relationships. The fragments are merged into a single graph.
|
||||
|
||||
---
|
||||
|
||||
## How community detection works
|
||||
|
||||
Communities are found using the [Leiden algorithm](https://www.nature.com/articles/s41598-019-41695-z) — a graph-clustering method that groups nodes by edge density. Nodes with many connections between them end up in the same community.
|
||||
|
||||
**No embeddings needed.** The semantic similarity edges that Claude extracts (`semantically_similar_to`) are already in the graph, so they influence community shape directly. The graph structure is the similarity signal — there's no separate embedding step or vector database.
|
||||
|
||||
---
|
||||
|
||||
## Confidence tagging
|
||||
|
||||
Every relationship is tagged with one of three labels:
|
||||
|
||||
| Tag | Meaning |
|
||||
|-----|---------|
|
||||
| `EXTRACTED` | Found directly in the source (e.g. a function call, an import) |
|
||||
| `INFERRED` | A reasonable inference Claude made, with a `confidence_score` (0.0–1.0) |
|
||||
| `AMBIGUOUS` | Uncertain — flagged in the report for manual review |
|
||||
|
||||
EXTRACTED edges always have confidence 1.0. INFERRED edges use a discrete rubric:
|
||||
- **0.95** — near-certain (explicit cross-file reference, one plausible target)
|
||||
- **0.85** — strong evidence (naming + context align)
|
||||
- **0.75** — reasonable (contextual but not explicit)
|
||||
- **0.65** — weak (naming similarity only)
|
||||
- **0.55** — speculative
|
||||
|
||||
---
|
||||
|
||||
## Token benchmark
|
||||
|
||||
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.
|
||||
|
||||
On a mixed corpus (Karpathy repos + 5 papers + 4 images, 52 files): **71.5x fewer tokens per query** vs reading the raw files directly.
|
||||
|
||||
| Corpus | Files | Reduction |
|
||||
|--------|-------|-----------|
|
||||
| Karpathy repos + papers + images | 52 | **71.5x** |
|
||||
| graphify source + Transformer paper | 4 | **5.4x** |
|
||||
| httpx (synthetic Python library) | 6 | ~1x |
|
||||
|
||||
Token reduction scales with corpus size. Six files already fits in a context window — the graph value there is structural clarity, not compression. At 52 files the savings compound quickly.
|
||||
|
||||
Each `worked/` folder in the repo has the raw input files and actual output (`GRAPH_REPORT.md`, `graph.json`) so you can run it yourself and verify.
|
||||
|
||||
---
|
||||
|
||||
## Parallel extraction
|
||||
|
||||
Code files are extracted in parallel using `ProcessPoolExecutor` — bypasses Python's GIL for genuine multiprocessing. Doc/paper/image batches are dispatched as parallel Claude subagents. On a corpus of 84 code files, parallel AST extraction runs in about 1.66x less time than sequential.
|
||||
|
||||
---
|
||||
|
||||
## SHA256 cache
|
||||
|
||||
Every extracted file is fingerprinted by content hash. Re-runs skip unchanged files entirely — only new or modified files go through extraction again. The cache lives in `graphify-out/cache/`.
|
||||
|
||||
---
|
||||
|
||||
## The graph format
|
||||
|
||||
The output `graph.json` uses NetworkX's node-link format. Each node has:
|
||||
- `id` — stable identifier
|
||||
- `label` — human-readable name
|
||||
- `file_type` — `code`, `document`, `paper`, `image`, `rationale`
|
||||
- `source_file` — where it came from
|
||||
|
||||
Each edge has:
|
||||
- `source`, `target` — node IDs
|
||||
- `relation` — verb phrase (e.g. `calls`, `imports`, `implements`, `semantically_similar_to`)
|
||||
- `confidence` — `EXTRACTED`, `INFERRED`, or `AMBIGUOUS`
|
||||
- `confidence_score` — float (INFERRED only)
|
||||
- `source_file` — where the relationship was found
|
||||
|
||||
Hyperedges (group relationships connecting 3+ nodes) live in `G.graph["hyperedges"]`.
|
||||
@@ -0,0 +1,47 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" role="img" aria-label="Graphify">
|
||||
<defs>
|
||||
<style>
|
||||
.edge { stroke: #22c55e; stroke-width: 1.1; stroke-linecap: round; opacity: 0.55; fill: none; }
|
||||
.edge-hot { stroke: #4ade80; stroke-width: 1.2; stroke-linecap: round; opacity: 0.9; fill: none; }
|
||||
.node { fill: #040806; stroke: #22c55e; stroke-width: 1.3; }
|
||||
.node-hub { fill: #0a1410; stroke: #4ade80; stroke-width: 1.6; }
|
||||
.node-amber { fill: #040806; stroke: #f59e0b; stroke-width: 1.3; }
|
||||
.node-amber-core { fill: #f59e0b; }
|
||||
.node-core { fill: #22c55e; }
|
||||
.node-hub-core { fill: #4ade80; }
|
||||
</style>
|
||||
</defs>
|
||||
|
||||
<!-- subtle halo around hub -->
|
||||
<circle cx="24" cy="24" r="11" fill="none" stroke="#22c55e" stroke-width="0.4" opacity="0.18"/>
|
||||
|
||||
<!-- edges: hub to satellites -->
|
||||
<line class="edge-hot" x1="24" y1="24" x2="10" y2="11"/>
|
||||
<line class="edge-hot" x1="24" y1="24" x2="39" y2="14"/>
|
||||
<line class="edge-hot" x1="24" y1="24" x2="38" y2="36"/>
|
||||
<line class="edge-hot" x1="24" y1="24" x2="11" y2="37"/>
|
||||
|
||||
<!-- perimeter edges -->
|
||||
<line class="edge" x1="10" y1="11" x2="39" y2="14"/>
|
||||
<line class="edge" x1="39" y1="14" x2="38" y2="36"/>
|
||||
<line class="edge" x1="38" y1="36" x2="11" y2="37"/>
|
||||
<line class="edge" x1="11" y1="37" x2="10" y2="11"/>
|
||||
|
||||
<!-- satellite nodes -->
|
||||
<circle class="node" cx="10" cy="11" r="2.6"/>
|
||||
<circle class="node-core" cx="10" cy="11" r="1.1"/>
|
||||
|
||||
<circle class="node" cx="39" cy="14" r="2.6"/>
|
||||
<circle class="node-core" cx="39" cy="14" r="1.1"/>
|
||||
|
||||
<!-- amber accent node -->
|
||||
<circle class="node-amber" cx="38" cy="36" r="2.8"/>
|
||||
<circle class="node-amber-core" cx="38" cy="36" r="1.25"/>
|
||||
|
||||
<circle class="node" cx="11" cy="37" r="2.6"/>
|
||||
<circle class="node-core" cx="11" cy="37" r="1.1"/>
|
||||
|
||||
<!-- central hub / god-node -->
|
||||
<circle class="node-hub" cx="24" cy="24" r="4.4"/>
|
||||
<circle class="node-hub-core" cx="24" cy="24" r="1.8"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.0 KiB |
@@ -0,0 +1,33 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 260 64" role="img" aria-label="Graphify">
|
||||
<rect width="260" height="64" rx="8" fill="#040806"/>
|
||||
<defs>
|
||||
<style>
|
||||
.logo-text { font-family: 'Segoe UI', 'Helvetica Neue', Arial, sans-serif; font-size: 42px; font-weight: 700; letter-spacing: -1.6px; }
|
||||
</style>
|
||||
</defs>
|
||||
<!-- icon mark -->
|
||||
<circle cx="24" cy="32" r="11" fill="none" stroke="#22c55e" stroke-width="0.4" opacity="0.18"/>
|
||||
<line x1="24" y1="32" x2="10" y2="19" stroke="#4ade80" stroke-width="1.2" stroke-linecap="round" opacity="0.9"/>
|
||||
<line x1="24" y1="32" x2="39" y2="22" stroke="#4ade80" stroke-width="1.2" stroke-linecap="round" opacity="0.9"/>
|
||||
<line x1="24" y1="32" x2="38" y2="44" stroke="#4ade80" stroke-width="1.2" stroke-linecap="round" opacity="0.9"/>
|
||||
<line x1="24" y1="32" x2="11" y2="45" stroke="#4ade80" stroke-width="1.2" stroke-linecap="round" opacity="0.9"/>
|
||||
<line x1="10" y1="19" x2="39" y2="22" stroke="#22c55e" stroke-width="1.1" stroke-linecap="round" opacity="0.55"/>
|
||||
<line x1="39" y1="22" x2="38" y2="44" stroke="#22c55e" stroke-width="1.1" stroke-linecap="round" opacity="0.55"/>
|
||||
<line x1="38" y1="44" x2="11" y2="45" stroke="#22c55e" stroke-width="1.1" stroke-linecap="round" opacity="0.55"/>
|
||||
<line x1="11" y1="45" x2="10" y2="19" stroke="#22c55e" stroke-width="1.1" stroke-linecap="round" opacity="0.55"/>
|
||||
<circle cx="10" cy="19" r="2.6" fill="#040806" stroke="#22c55e" stroke-width="1.3"/>
|
||||
<circle cx="10" cy="19" r="1.1" fill="#22c55e"/>
|
||||
<circle cx="39" cy="22" r="2.6" fill="#040806" stroke="#22c55e" stroke-width="1.3"/>
|
||||
<circle cx="39" cy="22" r="1.1" fill="#22c55e"/>
|
||||
<circle cx="38" cy="44" r="2.8" fill="#040806" stroke="#f59e0b" stroke-width="1.3"/>
|
||||
<circle cx="38" cy="44" r="1.25" fill="#f59e0b"/>
|
||||
<circle cx="11" cy="45" r="2.6" fill="#040806" stroke="#22c55e" stroke-width="1.3"/>
|
||||
<circle cx="11" cy="45" r="1.1" fill="#22c55e"/>
|
||||
<circle cx="24" cy="32" r="4.4" fill="#0a1410" stroke="#4ade80" stroke-width="1.6"/>
|
||||
<circle cx="24" cy="32" r="1.8" fill="#4ade80"/>
|
||||
<!-- divider -->
|
||||
<line x1="56" y1="18" x2="56" y2="46" stroke="#22c55e" stroke-width="1" opacity="0.2"/>
|
||||
<!-- text: Graph in near-white, ify in green -->
|
||||
<text x="68" y="47" class="logo-text" fill="#e6f5ec">Graph</text>
|
||||
<text x="178" y="47" class="logo-text" fill="#22c55e">ify</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.3 KiB |
@@ -0,0 +1,177 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
</p>
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**مهارة لمساعد برمجة الذكاء الاصطناعي.** اكتب `/graphify` في Claude Code أو Codex أو OpenCode أو Cursor أو Gemini CLI أو GitHub Copilot CLI أو VS Code Copilot Chat أو Aider أو OpenClaw أو Factory Droid أو Trae أو Hermes أو Kiro أو Google Antigravity — يقرأ ملفاتك ويبني رسماً بيانياً للمعرفة ويعيد إليك البنية التي لم تكن تعلم بوجودها. افهم قاعدة الكود بشكل أسرع. اكتشف "السبب" وراء القرارات المعمارية.
|
||||
|
||||
متعدد الوسائط بالكامل. أضف كوداً أو ملفات PDF أو markdown أو لقطات شاشة أو رسوماً بيانية أو صور سبورة أو صوراً بلغات أخرى أو ملفات فيديو وصوت — يستخرج graphify المفاهيم والعلاقات من كل ذلك ويربطها في رسم بياني واحد. يتم نسخ مقاطع الفيديو محلياً باستخدام Whisper. يدعم 25 لغة برمجة عبر 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 بمجلد `/raw` يضع فيه الأوراق البحثية والتغريدات ولقطات الشاشة والملاحظات. graphify هو الإجابة على تلك المشكلة — **71.5 مرة** أقل في الرموز لكل استعلام مقارنةً بقراءة الملفات الخام، مستمر عبر الجلسات، صادق حول ما تم العثور عليه مقابل ما تم استنتاجه.
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
/graphify . # يعمل مع أي مجلد — الكود، الملاحظات، الأوراق البحثية، كل شيء
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html رسم بياني تفاعلي — افتحه في أي متصفح، انقر على العقد، ابحث، صفّ
|
||||
├── GRAPH_REPORT.md عقد الإله، الاتصالات المفاجئة، الأسئلة المقترحة
|
||||
├── graph.json رسم بياني دائم — استعلم بعد أسابيع دون إعادة القراءة
|
||||
└── cache/ ذاكرة تخزين مؤقت SHA256 — إعادة التشغيل تعالج الملفات المتغيرة فقط
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
أضف ملف `.graphifyignore` لاستبعاد المجلدات:
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
نفس صيغة `.gitignore`.
|
||||
|
||||
## كيف يعمل
|
||||
|
||||
يعمل graphify في ثلاث مراحل. أولاً، تمريرة AST حتمية تستخرج البنية من ملفات الكود (الفئات، الدوال، الاستيرادات، رسوم بيانية الاستدعاء، docstrings، تعليقات المبرر) — دون الحاجة إلى LLM. ثانياً، يتم نسخ ملفات الفيديو والصوت محلياً باستخدام faster-whisper. ثالثاً، تعمل عوامل 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), [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, أو [Google Antigravity](https://antigravity.google)
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
# موصى به — يعمل على Mac وLinux دون إعداد PATH
|
||||
uv tool install graphifyy && graphify install
|
||||
# أو مع pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# أو pip العادي
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
> **الحزمة الرسمية:** اسم حزمة PyPI هو `graphifyy` (تثبيت بـ `pip install graphifyy`). الحزم الأخرى المسماة `graphify*` على PyPI ليست تابعة لهذا المشروع. المستودع الرسمي الوحيد هو [safishamsi/graphify](https://github.com/safishamsi/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` |
|
||||
| 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` |
|
||||
| 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` |
|
||||
|
||||
افتح مساعد الكود الذكاء الاصطناعي واكتب:
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
ملاحظة: يستخدم Codex `$` بدلاً من `/` للمهارات، لذا اكتب `$graphify .`.
|
||||
|
||||
## الاستخدام
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
/graphify # المجلد الحالي
|
||||
/graphify ./raw # مجلد محدد
|
||||
/graphify ./raw --update # إعادة استخراج الملفات المتغيرة فقط
|
||||
/graphify ./raw --directed # رسم بياني موجّه
|
||||
/graphify ./raw --no-viz # تقرير + JSON فقط، بدون HTML
|
||||
/graphify ./raw --obsidian # إنشاء Obsidian vault
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # جلب ورقة بحثية
|
||||
/graphify add <video-url> # تحميل صوت، نسخ، إضافة
|
||||
/graphify query "ما الذي يربط Attention بالمحسِّن؟"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # تثبيت Git hooks
|
||||
graphify update ./src # إعادة استخراج ملفات الكود، بدون LLM
|
||||
graphify watch ./src # تحديث تلقائي للرسم البياني
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## ما ستحصل عليه
|
||||
|
||||
**عقد الإله** — المفاهيم ذات أعلى درجة (كل شيء يمر بها)
|
||||
|
||||
**الاتصالات المفاجئة** — مرتبة حسب الدرجة المركبة. حواف الكود-الورقة البحثية تحصل على تصنيف أعلى. كل نتيجة تتضمن سبباً بلغة طبيعية.
|
||||
|
||||
**الأسئلة المقترحة** — 4-5 أسئلة الرسم البياني في وضع فريد للإجابة عليها
|
||||
|
||||
**"السبب"** — يتم استخراج docstrings والتعليقات المضمنة (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`) ومبررات التصميم كعقد `rationale_for`.
|
||||
|
||||
**درجات الثقة** — كل حافة INFERRED لها `confidence_score` (0.0-1.0).
|
||||
|
||||
**معيار الرموز** — يُطبع تلقائياً بعد كل تشغيل. على مجموعة بيانات مختلطة: **71.5 مرة** أقل في الرموز لكل استعلام مقارنةً بالملفات الخام.
|
||||
|
||||
**المزامنة التلقائية** (`--watch`) — يحدّث الرسم البياني تلقائياً عند تغيير الكود.
|
||||
|
||||
**Git hooks** (`graphify hook install`) — يثبّت خطافات post-commit وpost-checkout.
|
||||
|
||||
## الخصوصية
|
||||
|
||||
يرسل graphify محتوى الملفات إلى API نموذج مساعد الذكاء الاصطناعي الخاص بك للاستخراج الدلالي من المستندات والأوراق البحثية والصور. تتم معالجة ملفات الكود محلياً عبر tree-sitter AST. يتم نسخ ملفات الفيديو والصوت محلياً باستخدام faster-whisper. لا قياس عن بُعد، لا تتبع للاستخدام.
|
||||
|
||||
## المكدس التقني
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. استخراج دلالي عبر Claude أو GPT-4 أو نموذج منصتك. نسخ الفيديو عبر faster-whisper + yt-dlp (اختياري).
|
||||
|
||||
## مبني على graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) هو الطبقة المؤسسية فوق graphify. حيث يحوّل graphify مجلداً من الملفات إلى رسم بياني للمعرفة، يطبّق Penpax نفس الرسم البياني على حياتك المهنية بأكملها — باستمرار.
|
||||
|
||||
**نسخة تجريبية مجانية قريباً.** [انضم إلى قائمة الانتظار →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## سجل النجوم
|
||||
|
||||
</div>
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Dovednost pro asistenty kódování AI.** Napište `/graphify` v Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro nebo Google Antigravity — přečte vaše soubory, vytvoří znalostní graf a vrátí vám strukturu, o které jste nevěděli, že existuje. Pochopte kódovou základnu rychleji. Najděte „proč" za architektonickými rozhodnutími.
|
||||
|
||||
Plně multimodální. Přidejte kód, PDF, markdown, snímky obrazovky, diagramy, fotografie tabule, obrázky v jiných jazycích nebo video a zvukové soubory — graphify extrahuje koncepty a vztahy ze všeho a spojuje je do jediného grafu. Videa jsou přepisována lokálně pomocí Whisper. Podporuje 25 programovacích jazyků prostřednictvím tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy udržuje složku `/raw`, kde ukládá články, tweety, snímky obrazovky a poznámky. graphify je odpovědí na tento problém — **71,5x** méně tokenů na dotaz ve srovnání se čtením surových souborů, přetrvávající mezi sezeními.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktivní graf — otevřete v libovolném prohlížeči
|
||||
├── GRAPH_REPORT.md boží uzly, překvapivá propojení, navrhované otázky
|
||||
├── graph.json trvalý graf — dotazovatelný týdny poté
|
||||
└── cache/ SHA256 cache — opakovaná spuštění zpracovávají pouze změněné soubory
|
||||
```
|
||||
|
||||
## Jak to funguje
|
||||
|
||||
graphify pracuje ve třech průchodech. Nejprve deterministický průchod AST extrahuje strukturu z kódových souborů bez LLM. Poté jsou video a zvukové soubory přepisovány lokálně pomocí faster-whisper. Nakonec sub-agenti Claude běží paralelně na dokumentech, článcích, obrázcích a přepisech. Výsledky jsou sloučeny do grafu NetworkX, clusterovány pomocí Leiden a exportovány jako interaktivní HTML, dotazovatelný JSON a auditní zpráva.
|
||||
|
||||
Každý vztah je označen `EXTRACTED`, `INFERRED` (se skóre spolehlivosti) nebo `AMBIGUOUS`.
|
||||
|
||||
## Instalace
|
||||
|
||||
**Požadavky:** Python 3.10+ a jedno z: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) a další.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# nebo s pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# nebo pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Oficiální balíček:** Balíček PyPI se jmenuje `graphifyy`. Jediné oficiální úložiště je [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Použití
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "co spojuje Attention s optimizerem?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Co získáte
|
||||
|
||||
**Boží uzly** — koncepty s nejvyšším stupněm · **Překvapivá propojení** — seřazená podle skóre · **Navrhované otázky** · **„Proč"** — docstringy a návrhové odůvodnění extrahované jako uzly · **Benchmark tokenů** — **71,5x** méně tokenů na smíšeném korpusu.
|
||||
|
||||
## Soukromí
|
||||
|
||||
Kódové soubory jsou zpracovávány lokálně prostřednictvím tree-sitter AST. Videa jsou přepisována lokálně pomocí faster-whisper. Žádná telemetrie.
|
||||
|
||||
## Postaveno na graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) je enterprise vrstva nad graphify. **Bezplatná zkušební verze brzy.** [Přidejte se na čekací listinu →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**En færdighed til AI-kodeassistenter.** Skriv `/graphify` i Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro eller Google Antigravity — den læser dine filer, bygger en vidensgraf og giver dig den struktur tilbage, du ikke vidste eksisterede. Forstå en kodebase hurtigere. Find "hvorfor" bag arkitektoniske beslutninger.
|
||||
|
||||
Fuldt multimodal. Tilføj kode, PDF'er, markdown, skærmbilleder, diagrammer, whiteboardfotos, billeder på andre sprog eller video- og lydfiler — graphify udtrækker begreber og relationer fra alt og forbinder dem i én graf. Videoer transskriberes lokalt med Whisper. Understøtter 25 programmeringssprog via tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy opretholder en `/raw`-mappe, hvor han lægger artikler, tweets, skærmbilleder og noter. graphify er svaret på det problem — **71,5x** færre tokens pr. forespørgsel sammenlignet med at læse rå filer, vedvarende mellem sessioner.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktiv graf — åbn i enhver browser
|
||||
├── GRAPH_REPORT.md gudknuder, overraskende forbindelser, foreslåede spørgsmål
|
||||
├── graph.json vedvarende graf — forespørgselsbar uger senere
|
||||
└── cache/ SHA256-cache — gentagne kørsler behandler kun ændrede filer
|
||||
```
|
||||
|
||||
## Sådan fungerer det
|
||||
|
||||
graphify arbejder i tre gennemløb. Først udtrækker et deterministisk AST-gennemløb struktur fra kodefiler uden LLM. Derefter transskriberes video- og lydfiler lokalt med faster-whisper. Endelig kører Claude-underagenter parallelt på dokumenter, artikler, billeder og transskriptioner. Resultaterne flettes ind i en NetworkX-graf, klynges med Leiden og eksporteres som interaktiv HTML, forespørgselsbar JSON og revisionsrapport.
|
||||
|
||||
Hver relation er mærket `EXTRACTED`, `INFERRED` (med konfidensscore) eller `AMBIGUOUS`.
|
||||
|
||||
## Installation
|
||||
|
||||
**Krav:** Python 3.10+ og én af: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) og andre.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# eller med pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# eller pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Officiel pakke:** PyPI-pakken hedder `graphifyy`. Det eneste officielle lager er [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Brug
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "hvad forbinder Attention med optimizeren?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Hvad du får
|
||||
|
||||
**Gudknuder** — begreber med den højeste grad · **Overraskende forbindelser** — rangeret efter score · **Foreslåede spørgsmål** · **"Hvorfor"** — docstrings og designbegrundelse udtrukket som knuder · **Token-benchmark** — **71,5x** færre tokens på blandet korpus.
|
||||
|
||||
## Privatliv
|
||||
|
||||
Kodefiler behandles lokalt via tree-sitter AST. Videoer transskriberes lokalt med faster-whisper. Ingen telemetri.
|
||||
|
||||
## Bygget på graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) er enterprise-laget oven på graphify. **Gratis prøveperiode kommer snart.** [Tilmeld dig ventelisten →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,180 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
</p>
|
||||
|
||||
**Eine KI-Coding-Assistent-Skill.** Tippe `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro oder Google Antigravity — es liest deine Dateien, baut einen Wissensgraphen und gibt dir Struktur zurück, die du vorher nicht sehen konntest. Verstehe eine Codebasis schneller. Finde das „Warum" hinter Architekturentscheidungen.
|
||||
|
||||
Vollständig multimodal. Leg Code, PDFs, Markdown, Screenshots, Diagramme, Whiteboard-Fotos, Bilder in anderen Sprachen oder Video- und Audiodateien ab — graphify extrahiert Konzepte und Beziehungen aus allem und verbindet sie in einem einzigen Graphen. Videos werden lokal mit Whisper transkribiert, angetrieben durch einen domänenspezifischen Prompt aus deinem Korpus. 25 Programmiersprachen werden über tree-sitter AST unterstützt (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 führt einen `/raw`-Ordner, in dem er Papers, Tweets, Screenshots und Notizen ablegt. graphify ist die Antwort auf dieses Problem — 71,5-fach weniger Tokens pro Abfrage gegenüber dem Lesen der Rohdateien, persistent über Sitzungen hinweg, ehrlich darüber, was gefunden vs. erschlossen wurde.
|
||||
|
||||
```
|
||||
/graphify . # funktioniert mit jedem Ordner — Codebase, Notizen, Papers, alles
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktiver Graph — im Browser öffnen, Knoten anklicken, suchen, filtern
|
||||
├── GRAPH_REPORT.md Gott-Knoten, überraschende Verbindungen, vorgeschlagene Fragen
|
||||
├── graph.json persistenter Graph — Wochen später abfragen, ohne neu zu lesen
|
||||
└── cache/ SHA256-Cache — erneute Ausführungen verarbeiten nur geänderte Dateien
|
||||
```
|
||||
|
||||
Füge eine `.graphifyignore`-Datei hinzu, um Ordner auszuschließen:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
Gleiche Syntax wie `.gitignore`. Du kannst eine einzelne `.graphifyignore` im Repo-Stammverzeichnis behalten — Muster funktionieren korrekt, auch wenn graphify auf einem Unterordner ausgeführt wird.
|
||||
|
||||
## So funktioniert es
|
||||
|
||||
graphify läuft in drei Durchgängen. Zuerst extrahiert ein deterministischer AST-Durchgang Strukturen aus Code-Dateien (Klassen, Funktionen, Importe, Aufrufgraphen, Docstrings, Begründungskommentare) — ohne LLM. Zweitens werden Video- und Audiodateien lokal mit faster-whisper transkribiert, angetrieben durch einen domänenspezifischen Prompt aus Korpus-Gott-Knoten — Transkripte werden gecacht, sodass erneute Ausführungen sofort sind. Drittens laufen Claude-Subagenten parallel über Dokumente, Papers, Bilder und Transkripte, um Konzepte, Beziehungen und Designbegründungen zu extrahieren. Die Ergebnisse werden in einem NetworkX-Graphen zusammengeführt, mit Leiden-Community-Erkennung geclustert und als interaktives HTML, abfragbares JSON und ein Klartext-Audit-Report exportiert.
|
||||
|
||||
**Clustering basiert auf Graph-Topologie — keine Embeddings.** Leiden findet Communities durch Kantendichte. Die semantischen Ähnlichkeitskanten, die Claude extrahiert (`semantically_similar_to`, markiert als INFERRED), sind bereits im Graphen, sodass sie die Community-Erkennung direkt beeinflussen. Die Graphstruktur ist das Ähnlichkeitssignal — kein separater Embedding-Schritt oder Vektordatenbank nötig.
|
||||
|
||||
Jede Beziehung ist markiert als `EXTRACTED` (direkt in der Quelle gefunden), `INFERRED` (begründete Schlussfolgerung mit Konfidenzwert) oder `AMBIGUOUS` (zur Überprüfung markiert). Du weißt immer, was gefunden vs. erschlossen wurde.
|
||||
|
||||
## Installation
|
||||
|
||||
**Voraussetzungen:** Python 3.10+ und eines von: [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 oder [Google Antigravity](https://antigravity.google)
|
||||
|
||||
```bash
|
||||
# Empfohlen — funktioniert auf Mac und Linux ohne PATH-Einrichtung
|
||||
uv tool install graphifyy && graphify install
|
||||
# oder mit pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# oder einfaches pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Offizielles Paket:** Das PyPI-Paket heißt `graphifyy` (installieren mit `pip install graphifyy`). Andere Pakete mit Namen `graphify*` auf PyPI sind nicht mit diesem Projekt verbunden. Das einzige offizielle Repository ist [safishamsi/graphify](https://github.com/safishamsi/graphify). CLI und Skill-Befehl heißen weiterhin `graphify`.
|
||||
|
||||
> **`graphify: command not found`?** Verwende `uv tool install graphifyy` (empfohlen) oder `pipx install graphifyy` — beide platzieren die CLI an einem verwalteten Ort, der automatisch im PATH ist. Mit einfachem `pip` musst du möglicherweise `~/.local/bin` (Linux) oder `~/Library/Python/3.x/bin` (Mac) zum PATH hinzufügen, oder `python -m graphify` verwenden.
|
||||
|
||||
### Plattformunterstützung
|
||||
|
||||
| Plattform | Installationsbefehl |
|
||||
|-----------|---------------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (automatisch erkannt) oder `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` |
|
||||
|
||||
Dann öffne deinen KI-Coding-Assistenten und tippe:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
Hinweis: Codex verwendet `$` statt `/` für Skill-Aufrufe, also tippe `$graphify .`.
|
||||
|
||||
### Assistenten immer den Graphen nutzen lassen (empfohlen)
|
||||
|
||||
Nach dem Erstellen eines Graphen, führe dies einmal in deinem Projekt aus:
|
||||
|
||||
| Plattform | Befehl |
|
||||
|-----------|--------|
|
||||
| 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` |
|
||||
|
||||
## Verwendung
|
||||
|
||||
```
|
||||
/graphify # aktuelles Verzeichnis verarbeiten
|
||||
/graphify ./raw # spezifischen Ordner verarbeiten
|
||||
/graphify ./raw --mode deep # aggressivere INFERRED-Kanten-Extraktion
|
||||
/graphify ./raw --update # nur geänderte Dateien neu extrahieren
|
||||
/graphify ./raw --directed # gerichteten Graphen erstellen
|
||||
/graphify ./raw --cluster-only # Clustering auf bestehendem Graphen neu ausführen
|
||||
/graphify ./raw --no-viz # kein HTML, nur Report + JSON
|
||||
/graphify ./raw --obsidian # Obsidian-Vault generieren (opt-in)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # Paper abrufen, speichern, Graphen aktualisieren
|
||||
/graphify add <video-url> # Audio herunterladen, transkribieren, hinzufügen
|
||||
/graphify query "was verbindet Attention mit dem Optimizer?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # Git-Hooks installieren
|
||||
graphify update ./src # Code-Dateien neu extrahieren, kein LLM benötigt
|
||||
graphify watch ./src # Graphen bei Änderungen automatisch aktualisieren
|
||||
```
|
||||
|
||||
## Was du bekommst
|
||||
|
||||
**Gott-Knoten** — Konzepte mit dem höchsten Grad (durch die alles fließt)
|
||||
|
||||
**Überraschende Verbindungen** — nach Composite-Score eingestuft. Code-Paper-Kanten werden höher bewertet. Jedes Ergebnis enthält ein Klartext-Warum.
|
||||
|
||||
**Vorgeschlagene Fragen** — 4-5 Fragen, die der Graph einzigartig gut beantworten kann
|
||||
|
||||
**Das „Warum"** — Docstrings, Inline-Kommentare (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), und Designbegründungen aus Dokumenten werden als `rationale_for`-Knoten extrahiert.
|
||||
|
||||
**Konfidenzwerte** — jede INFERRED-Kante hat einen `confidence_score` (0,0-1,0).
|
||||
|
||||
**Token-Benchmark** — wird automatisch nach jeder Ausführung gedruckt. Auf einem gemischten Korpus: **71,5-fach** weniger Tokens pro Abfrage gegenüber Rohdateien.
|
||||
|
||||
**Auto-Sync** (`--watch`) — läuft im Hintergrund und aktualisiert den Graphen bei Codeänderungen automatisch.
|
||||
|
||||
**Git-Hooks** (`graphify hook install`) — installiert Post-Commit- und Post-Checkout-Hooks.
|
||||
|
||||
## Datenschutz
|
||||
|
||||
graphify sendet Dateiinhalte an die Modell-API deines KI-Assistenten für semantische Extraktion von Dokumenten, Papers und Bildern. Code-Dateien werden lokal via tree-sitter AST verarbeitet — kein Dateiinhalt verlässt dein Gerät für Code. Video- und Audiodateien werden lokal mit faster-whisper transkribiert. Keine Telemetrie, keine Nutzungsverfolgung.
|
||||
|
||||
## Tech-Stack
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantische Extraktion via Claude, GPT-4 oder welches Modell deine Plattform verwendet. Video-Transkription via faster-whisper + yt-dlp (optional).
|
||||
|
||||
## Auf graphify aufgebaut — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) ist die Enterprise-Schicht über graphify. Wo graphify einen Ordner mit Dateien in einen Wissensgraphen verwandelt, wendet Penpax denselben Graphen auf dein gesamtes Arbeitsleben an — kontinuierlich.
|
||||
|
||||
**Kostenlose Testversion startet bald.** [Auf die Warteliste setzen →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## Star-Verlauf
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Μια δεξιότητα για βοηθούς κώδικα AI.** Πληκτρολογήστε `/graphify` στο Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro ή Google Antigravity — διαβάζει τα αρχεία σας, δημιουργεί ένα γράφο γνώσης και σας επιστρέφει δομή που δεν ξέρατε ότι υπήρχε. Κατανοήστε μια βάση κώδικα γρηγορότερα. Βρείτε το «γιατί» πίσω από αρχιτεκτονικές αποφάσεις.
|
||||
|
||||
Πλήρως πολυτροπικό. Προσθέστε κώδικα, PDF, markdown, στιγμιότυπα οθόνης, διαγράμματα, φωτογραφίες πίνακα, εικόνες σε άλλες γλώσσες ή αρχεία βίντεο και ήχου — το graphify εξάγει έννοιες και σχέσεις από όλα και τα συνδέει σε ένα ενιαίο γράφο. Τα βίντεο μεταγράφονται τοπικά με το Whisper. Υποστηρίζει 25 γλώσσες προγραμματισμού μέσω tree-sitter AST.
|
||||
|
||||
> Ο Andrej Karpathy διατηρεί ένα φάκελο `/raw` όπου αποθηκεύει εργασίες, tweets, στιγμιότυπα και σημειώσεις. Το graphify είναι η απάντηση σε αυτό το πρόβλημα — **71,5x** λιγότερα token ανά ερώτημα σε σύγκριση με την ανάγνωση αρχείων, επίμονο μεταξύ συνεδριών.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html διαδραστικός γράφος — ανοίξτε σε οποιοδήποτε πρόγραμμα περιήγησης
|
||||
├── GRAPH_REPORT.md κόμβοι-θεοί, εκπληκτικές συνδέσεις, προτεινόμενες ερωτήσεις
|
||||
├── graph.json επίμονος γράφος — μπορεί να υποβληθεί σε ερωτήματα εβδομάδες αργότερα
|
||||
└── cache/ κρυφή μνήμη SHA256 — επαναλαμβανόμενες εκτελέσεις επεξεργάζονται μόνο τα αλλαγμένα αρχεία
|
||||
```
|
||||
|
||||
## Πώς λειτουργεί
|
||||
|
||||
Το graphify λειτουργεί σε τρεις διελεύσεις. Πρώτα, μια ντετερμινιστική διέλευση AST εξάγει δομή από αρχεία κώδικα χωρίς LLM. Στη συνέχεια, τα αρχεία βίντεο και ήχου μεταγράφονται τοπικά με faster-whisper. Τέλος, οι υπο-πράκτορες Claude εκτελούνται παράλληλα σε έγγραφα, εργασίες, εικόνες και μεταγραφές. Τα αποτελέσματα συγχωνεύονται σε ένα γράφο NetworkX, ομαδοποιούνται με Leiden και εξάγονται ως διαδραστική HTML, JSON για ερωτήματα και αναφορά ελέγχου.
|
||||
|
||||
Κάθε σχέση επισημαίνεται ως `EXTRACTED`, `INFERRED` (με βαθμολογία εμπιστοσύνης) ή `AMBIGUOUS`.
|
||||
|
||||
## Εγκατάσταση
|
||||
|
||||
**Απαιτήσεις:** Python 3.10+ και ένα από: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) και άλλα.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# ή με pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# ή pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Επίσημο πακέτο:** Το πακέτο PyPI ονομάζεται `graphifyy`. Το μοναδικό επίσημο αποθετήριο είναι το [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Χρήση
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "τι συνδέει το Attention με τον optimizer;"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Τι λαμβάνετε
|
||||
|
||||
**Κόμβοι-θεοί** — έννοιες με τον υψηλότερο βαθμό · **Εκπληκτικές συνδέσεις** — ταξινομημένες κατά βαθμολογία · **Προτεινόμενες ερωτήσεις** · **Το «γιατί»** — docstrings και αιτιολόγηση σχεδιασμού εξαγόμενα ως κόμβοι · **Σημείο αναφοράς token** — **71,5x** λιγότερα token σε μικτό σώμα κειμένου.
|
||||
|
||||
## Απόρρητο
|
||||
|
||||
Τα αρχεία κώδικα επεξεργάζονται τοπικά μέσω tree-sitter AST. Τα βίντεο μεταγράφονται τοπικά με faster-whisper. Χωρίς τηλεμετρία.
|
||||
|
||||
## Δημιουργήθηκε στο graphify — Penpax
|
||||
|
||||
Το [**Penpax**](https://safishamsi.github.io/penpax.ai) είναι το εταιρικό επίπεδο πάνω από το graphify. **Δωρεάν δοκιμή σύντομα.** [Εγγραφείτε στη λίστα αναμονής →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,170 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
</p>
|
||||
|
||||
**Una habilidad para asistentes de código IA.** Escribe `/graphify` en Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro o Google Antigravity — lee tus archivos, construye un grafo de conocimiento y te devuelve estructura que no sabías que existía. Entiende una base de código más rápido. Encuentra el «por qué» detrás de las decisiones arquitectónicas.
|
||||
|
||||
Totalmente multimodal. Deposita código, PDFs, markdown, capturas de pantalla, diagramas, fotos de pizarras, imágenes en otros idiomas, o archivos de video y audio — graphify extrae conceptos y relaciones de todo ello y los conecta en un solo grafo. Los videos se transcriben localmente con Whisper usando un prompt adaptado al dominio derivado de tu corpus. 25 lenguajes de programación soportados mediante 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 mantiene una carpeta `/raw` donde deposita papers, tweets, capturas de pantalla y notas. graphify es la respuesta a ese problema — 71,5 veces menos tokens por consulta versus leer los archivos sin procesar, persistente entre sesiones, honesto sobre lo que encontró versus lo que infirió.
|
||||
|
||||
```
|
||||
/graphify . # funciona con cualquier carpeta — tu código, notas, papers, todo
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html grafo interactivo — abrir en cualquier navegador, hacer clic en nodos, buscar
|
||||
├── GRAPH_REPORT.md nodos dios, conexiones sorprendentes, preguntas sugeridas
|
||||
├── graph.json grafo persistente — consultar semanas después sin releer
|
||||
└── cache/ caché SHA256 — las re-ejecuciones solo procesan archivos modificados
|
||||
```
|
||||
|
||||
Añade un archivo `.graphifyignore` para excluir carpetas:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
Misma sintaxis que `.gitignore`. Puedes mantener un único `.graphifyignore` en la raíz del repositorio.
|
||||
|
||||
## Cómo funciona
|
||||
|
||||
graphify se ejecuta en tres pasadas. Primero, una pasada AST determinista extrae estructura de los archivos de código (clases, funciones, importaciones, grafos de llamadas, docstrings, comentarios de justificación) sin necesidad de LLM. Segundo, los archivos de video y audio se transcriben localmente con faster-whisper usando un prompt adaptado al dominio derivado de los nodos dios del corpus. Tercero, subagentes de Claude se ejecutan en paralelo sobre documentos, papers, imágenes y transcripciones para extraer conceptos, relaciones y justificaciones de diseño. Los resultados se fusionan en un grafo NetworkX, se agrupan con detección de comunidades Leiden, y se exportan como HTML interactivo, JSON consultable y un informe de auditoría en lenguaje natural.
|
||||
|
||||
**El clustering se basa en la topología del grafo — sin embeddings.** Leiden encuentra comunidades por densidad de aristas. Las aristas de similitud semántica que Claude extrae (`semantically_similar_to`, marcadas como INFERRED) ya están en el grafo. La estructura del grafo es la señal de similitud — no se necesita paso de embedding separado ni base de datos vectorial.
|
||||
|
||||
Cada relación está etiquetada como `EXTRACTED` (encontrada directamente en la fuente), `INFERRED` (inferencia razonable con puntuación de confianza) o `AMBIGUOUS` (marcada para revisión).
|
||||
|
||||
## Instalación
|
||||
|
||||
**Requisitos:** Python 3.10+ y uno de: [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 o [Google Antigravity](https://antigravity.google)
|
||||
|
||||
```bash
|
||||
# Recomendado — funciona en Mac y Linux sin configurar el PATH
|
||||
uv tool install graphifyy && graphify install
|
||||
# o con pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# o pip simple
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Paquete oficial:** El paquete PyPI se llama `graphifyy` (instalar con `pip install graphifyy`). Otros paquetes llamados `graphify*` en PyPI no están afiliados con este proyecto. El único repositorio oficial es [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
### Soporte de plataformas
|
||||
|
||||
| Plataforma | Comando de instalación |
|
||||
|------------|------------------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (detección automática) o `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` |
|
||||
|
||||
Luego abre tu asistente de código IA y escribe:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
Nota: Codex usa `$` en lugar de `/` para habilidades, así que escribe `$graphify .`.
|
||||
|
||||
### Hacer que el asistente siempre use el grafo (recomendado)
|
||||
|
||||
Después de construir un grafo, ejecuta esto una vez en tu proyecto:
|
||||
|
||||
| Plataforma | Comando |
|
||||
|------------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
## Uso
|
||||
|
||||
```
|
||||
/graphify # directorio actual
|
||||
/graphify ./raw # carpeta específica
|
||||
/graphify ./raw --mode deep # extracción de aristas INFERRED más agresiva
|
||||
/graphify ./raw --update # re-extraer solo archivos modificados
|
||||
/graphify ./raw --directed # grafo dirigido
|
||||
/graphify ./raw --cluster-only # re-ejecutar clustering en grafo existente
|
||||
/graphify ./raw --no-viz # sin HTML, solo informe + JSON
|
||||
/graphify ./raw --obsidian # generar vault de Obsidian (opt-in)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # obtener un paper
|
||||
/graphify add <video-url> # descargar audio, transcribir, añadir
|
||||
/graphify query "¿qué conecta Attention con el optimizador?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # instalar hooks de Git
|
||||
graphify update ./src # re-extraer archivos de código, sin LLM
|
||||
graphify watch ./src # actualización automática del grafo
|
||||
```
|
||||
|
||||
## Qué obtienes
|
||||
|
||||
**Nodos dios** — conceptos con mayor grado (por donde todo pasa)
|
||||
|
||||
**Conexiones sorprendentes** — clasificadas por puntuación compuesta. Las aristas código-paper puntúan más alto. Cada resultado incluye un por qué en lenguaje natural.
|
||||
|
||||
**Preguntas sugeridas** — 4-5 preguntas que el grafo está en posición única de responder
|
||||
|
||||
**El «por qué»** — docstrings, comentarios inline (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), y justificaciones de diseño extraídas como nodos `rationale_for`.
|
||||
|
||||
**Puntuaciones de confianza** — cada arista INFERRED tiene un `confidence_score` (0,0-1,0).
|
||||
|
||||
**Benchmark de tokens** — impreso automáticamente tras cada ejecución. En un corpus mixto: **71,5 veces** menos tokens por consulta vs archivos sin procesar.
|
||||
|
||||
**Sincronización automática** (`--watch`) — actualiza el grafo automáticamente cuando cambia el código.
|
||||
|
||||
**Hooks de Git** (`graphify hook install`) — instala hooks post-commit y post-checkout.
|
||||
|
||||
## Privacidad
|
||||
|
||||
graphify envía contenido de archivos a la API del modelo de tu asistente IA para extracción semántica de documentos, papers e imágenes. Los archivos de código se procesan localmente mediante tree-sitter AST. Los archivos de video y audio se transcriben localmente con faster-whisper. Sin telemetría, sin seguimiento de uso.
|
||||
|
||||
## Stack técnico
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Extracción semántica via Claude, GPT-4 o el modelo de tu plataforma. Transcripción de video via faster-whisper + yt-dlp (opcional).
|
||||
|
||||
## Construido sobre graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) es la capa enterprise sobre graphify. Donde graphify convierte una carpeta de archivos en un grafo de conocimiento, Penpax aplica el mismo grafo a toda tu vida laboral — continuamente.
|
||||
|
||||
**Prueba gratuita próximamente.** [Unirse a la lista de espera →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## Historial de estrellas
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Taito tekoälykoodiavustajille.** Kirjoita `/graphify` Claude Codessa, Codexissa, OpenCodessa, Cursorissa, Gemini CLI:ssä, GitHub Copilot CLI:ssä, VS Code Copilot Chatissa, Aiderissa, OpenClawissa, Factory Droidissa, Traessa, Hermeksessä, Kirossa tai Google Antigravityssa — se lukee tiedostosi, rakentaa tietograafin ja palauttaa sinulle rakenteen, jota et tiennyt olevan. Ymmärrä koodikanta nopeammin. Löydä arkkitehtuuripäätösten taustalla oleva "miksi".
|
||||
|
||||
Täysin multimodaalinen. Lisää koodia, PDF:iä, markdownia, kuvakaappauksia, kaavioita, liitutaulun valokuvia, muilla kielillä olevia kuvia tai video- ja äänitiedostoja — graphify poimii käsitteitä ja suhteita kaikesta ja yhdistää ne yhdeksi graafaksi. Videot litteroidaan paikallisesti Whisperillä. Tukee 25 ohjelmointikieltä tree-sitter AST:n kautta.
|
||||
|
||||
> Andrej Karpathy ylläpitää `/raw`-kansiota, johon hän tallentaa papereita, tviittejä, kuvakaappauksia ja muistiinpanoja. graphify on vastaus tähän ongelmaan — **71,5x** vähemmän tokeneita kyselyä kohden verrattuna raakatiedostojen lukemiseen, pysyvä istuntojen välillä.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktiivinen graafi — avaa missä tahansa selaimessa
|
||||
├── GRAPH_REPORT.md jumalsolmut, yllättävät yhteydet, ehdotetut kysymykset
|
||||
├── graph.json pysyvä graafi — kyselytavissa viikkojen kuluttua
|
||||
└── cache/ SHA256-välimuisti — toistuvat ajot käsittelevät vain muuttuneet tiedostot
|
||||
```
|
||||
|
||||
## Miten se toimii
|
||||
|
||||
graphify toimii kolmessa läpiajossa. Ensin deterministinen AST-läpiajo poimii rakenteen kooditiedostoista ilman LLM:ää. Sitten video- ja äänitiedostot litteroidaan paikallisesti faster-whisperillä. Lopuksi Clauden ala-agentit suoritetaan rinnakkain asiakirjoissa, papereissa, kuvissa ja litteroinneissa. Tulokset yhdistetään NetworkX-graafiin, klusteroidaan Leidenillä ja viedään interaktiivisena HTML:nä, kyselytavissa olevana JSON:na ja tarkastusraporttina.
|
||||
|
||||
Jokainen suhde on merkitty `EXTRACTED`, `INFERRED` (luottamuspisteineen) tai `AMBIGUOUS`.
|
||||
|
||||
## Asennus
|
||||
|
||||
**Vaatimukset:** Python 3.10+ ja jokin seuraavista: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) ja muut.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# tai pipx:llä
|
||||
pipx install graphifyy && graphify install
|
||||
# tai pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Virallinen paketti:** PyPI-paketti on nimeltään `graphifyy`. Ainoa virallinen repositorio on [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Käyttö
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "mikä yhdistää Attentionin optimizeriin?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Mitä saat
|
||||
|
||||
**Jumalsolmut** — korkeimman asteen käsitteet · **Yllättävät yhteydet** — pisteiden mukaan järjestetty · **Ehdotetut kysymykset** · **"Miksi"** — docstringit ja suunnitteluperusteet solmuina · **Token-vertailu** — **71,5x** vähemmän tokeneita sekakorpuksessa.
|
||||
|
||||
## Yksityisyys
|
||||
|
||||
Kooditiedostot käsitellään paikallisesti tree-sitter AST:n kautta. Videot litteroidaan paikallisesti faster-whisperillä. Ei telemetriaa.
|
||||
|
||||
## Rakennettu graphifyn päälle — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) on graphifyn päälle rakennettu yritystaso. **Ilmainen kokeilujakso tulossa pian.** [Liity odotuslistalle →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,170 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
</p>
|
||||
|
||||
**Une compétence pour assistant de code IA.** Tapez `/graphify` dans Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro ou Google Antigravity — il lit vos fichiers, construit un graphe de connaissances et vous révèle une structure que vous ne voyiez pas auparavant. Comprenez une base de code plus rapidement. Trouvez le « pourquoi » derrière les décisions architecturales.
|
||||
|
||||
Entièrement multimodal. Déposez du code, des PDFs, du markdown, des captures d'écran, des diagrammes, des photos de tableau blanc, des images dans d'autres langues, ou des fichiers vidéo et audio — graphify extrait les concepts et les relations de tout cela et les connecte en un seul graphe. Les vidéos sont transcrites localement avec Whisper grâce à un prompt adapté au domaine. 25 langages de programmation supportés 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 maintient un dossier `/raw` où il dépose des articles, tweets, captures d'écran et notes. graphify est la réponse à ce problème — 71,5 fois moins de tokens par requête versus la lecture des fichiers bruts, persistant entre les sessions, honnête sur ce qui a été trouvé versus déduit.
|
||||
|
||||
```
|
||||
/graphify . # fonctionne sur n'importe quel dossier — code, notes, articles, tout
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html graphe interactif — ouvrir dans un navigateur, cliquer, rechercher, filtrer
|
||||
├── GRAPH_REPORT.md nœuds dieu, connexions surprenantes, questions suggérées
|
||||
├── graph.json graphe persistant — interrogeable des semaines plus tard sans relire
|
||||
└── cache/ cache SHA256 — les réexécutions ne traitent que les fichiers modifiés
|
||||
```
|
||||
|
||||
Ajoutez un fichier `.graphifyignore` pour exclure des dossiers :
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
Même syntaxe que `.gitignore`. Un seul `.graphifyignore` à la racine du dépôt suffit.
|
||||
|
||||
## Comment ça fonctionne
|
||||
|
||||
graphify s'exécute en trois passes. D'abord, un passage AST déterministe extrait la structure des fichiers de code (classes, fonctions, imports, graphes d'appel, docstrings, commentaires de justification) sans LLM. Ensuite, les fichiers vidéo et audio sont transcrits localement avec faster-whisper. Enfin, des sous-agents Claude s'exécutent en parallèle sur les docs, articles, images et transcriptions pour extraire concepts, relations et justifications de conception. Les résultats sont fusionnés dans un graphe NetworkX, regroupés avec la détection de communautés Leiden, et exportés en HTML interactif, JSON interrogeable et un rapport d'audit en langage naturel.
|
||||
|
||||
**Le clustering est basé sur la topologie du graphe — pas d'embeddings.** Leiden trouve les communautés par densité d'arêtes. Les arêtes de similarité sémantique extraites par Claude (`semantically_similar_to`, marquées INFERRED) sont déjà dans le graphe. La structure du graphe est le signal de similarité — pas d'étape d'embedding séparée ni de base de données vectorielle nécessaire.
|
||||
|
||||
Chaque relation est étiquetée `EXTRACTED` (trouvée directement dans la source), `INFERRED` (déduction raisonnable avec un score de confiance) ou `AMBIGUOUS` (marquée pour révision).
|
||||
|
||||
## Installation
|
||||
|
||||
**Prérequis :** Python 3.10+ et l'un de : [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 ou [Google Antigravity](https://antigravity.google)
|
||||
|
||||
```bash
|
||||
# Recommandé — fonctionne sur Mac et Linux sans configuration du PATH
|
||||
uv tool install graphifyy && graphify install
|
||||
# ou avec pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# ou pip simple
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Package officiel :** Le package PyPI s'appelle `graphifyy` (installer avec `pip install graphifyy`). Les autres packages nommés `graphify*` sur PyPI ne sont pas affiliés à ce projet. Le seul dépôt officiel est [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
### Support des plateformes
|
||||
|
||||
| Plateforme | Commande d'installation |
|
||||
|------------|------------------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (détection automatique) ou `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` |
|
||||
|
||||
Ensuite, ouvrez votre assistant de code IA et tapez :
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
Note : Codex utilise `$` au lieu de `/` pour les compétences, tapez donc `$graphify .`.
|
||||
|
||||
### Toujours utiliser le graphe (recommandé)
|
||||
|
||||
Après avoir construit un graphe, exécutez ceci une fois dans votre projet :
|
||||
|
||||
| Plateforme | Commande |
|
||||
|------------|----------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
## Utilisation
|
||||
|
||||
```
|
||||
/graphify # répertoire courant
|
||||
/graphify ./raw # dossier spécifique
|
||||
/graphify ./raw --mode deep # extraction d'arêtes INFERRED plus agressive
|
||||
/graphify ./raw --update # ne réextraire que les fichiers modifiés
|
||||
/graphify ./raw --directed # graphe dirigé
|
||||
/graphify ./raw --cluster-only # relancer le clustering sur le graphe existant
|
||||
/graphify ./raw --no-viz # pas d'HTML, juste rapport + JSON
|
||||
/graphify ./raw --obsidian # générer un vault Obsidian (opt-in)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # récupérer un article
|
||||
/graphify add <video-url> # télécharger l'audio, transcrire, ajouter
|
||||
/graphify query "qu'est-ce qui connecte Attention à l'optimiseur ?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # installer les hooks Git
|
||||
graphify update ./src # réextraire les fichiers de code, sans LLM
|
||||
graphify watch ./src # mise à jour automatique du graphe
|
||||
```
|
||||
|
||||
## Ce que vous obtenez
|
||||
|
||||
**Nœuds dieu** — concepts avec le plus haut degré (tout passe par eux)
|
||||
|
||||
**Connexions surprenantes** — classées par score composite. Les arêtes code-article sont mieux notées. Chaque résultat inclut un pourquoi en langage naturel.
|
||||
|
||||
**Questions suggérées** — 4-5 questions que le graphe est particulièrement bien placé pour répondre
|
||||
|
||||
**Le « pourquoi »** — docstrings, commentaires inline (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), et justifications de conception extraits comme nœuds `rationale_for`.
|
||||
|
||||
**Scores de confiance** — chaque arête INFERRED a un `confidence_score` (0,0-1,0).
|
||||
|
||||
**Benchmark de tokens** — affiché automatiquement après chaque exécution. Sur un corpus mixte : **71,5 fois** moins de tokens par requête vs fichiers bruts.
|
||||
|
||||
**Synchronisation automatique** (`--watch`) — met à jour le graphe automatiquement lors des modifications de code.
|
||||
|
||||
**Hooks Git** (`graphify hook install`) — installe des hooks post-commit et post-checkout.
|
||||
|
||||
## Confidentialité
|
||||
|
||||
graphify envoie le contenu des fichiers à l'API du modèle de votre assistant IA pour l'extraction sémantique des docs, articles et images. Les fichiers de code sont traités localement via tree-sitter AST. Les fichiers vidéo et audio sont transcrits localement avec faster-whisper. Aucune télémétrie, aucun suivi d'utilisation.
|
||||
|
||||
## Stack technique
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Extraction sémantique via Claude, GPT-4 ou le modèle de votre plateforme. Transcription vidéo via faster-whisper + yt-dlp (optionnel).
|
||||
|
||||
## Construit sur graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) est la couche enterprise au-dessus de graphify. Là où graphify transforme un dossier de fichiers en graphe de connaissances, Penpax applique le même graphe à toute votre vie professionnelle — en continu.
|
||||
|
||||
**Essai gratuit bientôt disponible.** [Rejoindre la liste d'attente →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## Historique des étoiles
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,143 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
</p>
|
||||
|
||||
**एक AI कोडिंग असिस्टेंट स्किल।** Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro या Google Antigravity में `/graphify` टाइप करें — यह आपकी फ़ाइलें पढ़ता है, एक नॉलेज ग्राफ बनाता है, और आपको वह संरचना वापस देता है जो आप नहीं जानते थे कि मौजूद है। कोडबेस को तेज़ी से समझें। आर्किटेक्चरल निर्णयों के पीछे का "क्यों" खोजें।
|
||||
|
||||
पूरी तरह मल्टीमोडल। कोड, PDFs, मार्कडाउन, स्क्रीनशॉट, डायग्राम, व्हाइटबोर्ड फोटो, अन्य भाषाओं में छवियां, या वीडियो और ऑडियो फ़ाइलें डालें — graphify इन सभी से अवधारणाएं और संबंध निकालता है और उन्हें एक ग्राफ में जोड़ता है। वीडियो को Whisper से स्थानीय रूप से ट्रांसक्राइब किया जाता है। 25 प्रोग्रामिंग भाषाएं 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 एक `/raw` फोल्डर रखते हैं जहां वह papers, tweets, स्क्रीनशॉट और नोट्स डालते हैं। graphify उस समस्या का जवाब है — रॉ फ़ाइलें पढ़ने की तुलना में प्रति क्वेरी **71.5x** कम tokens, सत्रों में स्थायी, ईमानदार कि क्या पाया गया बनाम अनुमान लगाया गया।
|
||||
|
||||
```
|
||||
/graphify . # किसी भी फोल्डर पर काम करता है — कोडबेस, नोट्स, papers, सब कुछ
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html इंटरेक्टिव ग्राफ — किसी भी ब्राउज़र में खोलें, नोड्स क्लिक करें, खोजें
|
||||
├── GRAPH_REPORT.md गॉड नोड्स, आश्चर्यजनक कनेक्शन, सुझाए गए प्रश्न
|
||||
├── graph.json स्थायी ग्राफ — हफ्तों बाद भी क्वेरी करें
|
||||
└── cache/ SHA256 कैश — पुनः चलाने पर केवल बदली हुई फ़ाइलें प्रोसेस होती हैं
|
||||
```
|
||||
|
||||
अनचाहे फोल्डर को बाहर करने के लिए `.graphifyignore` फ़ाइल जोड़ें:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
`.gitignore` जैसी ही सिंटेक्स।
|
||||
|
||||
## यह कैसे काम करता है
|
||||
|
||||
graphify तीन चरणों में चलता है। पहले, एक निर्धारक AST पास कोड फ़ाइलों से संरचना निकालता है — बिना किसी LLM के। दूसरे, वीडियो और ऑडियो फ़ाइलों को faster-whisper से स्थानीय रूप से ट्रांसक्राइब किया जाता है। तीसरे, Claude सबएजेंट दस्तावेज़ों, papers, छवियों और ट्रांसक्रिप्ट पर समानांतर में चलते हैं। परिणामों को NetworkX ग्राफ में मर्ज किया जाता है, Leiden कम्युनिटी डिटेक्शन से क्लस्टर किया जाता है, और इंटरेक्टिव HTML, क्वेरी करने योग्य JSON और एक ऑडिट रिपोर्ट के रूप में निर्यात किया जाता है।
|
||||
|
||||
**क्लस्टरिंग ग्राफ-टोपोलॉजी आधारित है — कोई embeddings नहीं।** Claude द्वारा निकाले गए सिमेंटिक समानता किनारे पहले से ग्राफ में हैं, इसलिए वे कम्युनिटी डिटेक्शन को सीधे प्रभावित करते हैं।
|
||||
|
||||
प्रत्येक संबंध `EXTRACTED` (स्रोत में सीधे पाया गया), `INFERRED` (उचित अनुमान, कॉन्फिडेंस स्कोर के साथ) या `AMBIGUOUS` (समीक्षा के लिए चिह्नित) के रूप में टैग किया जाता है।
|
||||
|
||||
## इंस्टॉलेशन
|
||||
|
||||
**आवश्यकताएं:** Python 3.10+ और निम्न में से एक: [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 या [Google Antigravity](https://antigravity.google)
|
||||
|
||||
```bash
|
||||
# अनुशंसित — Mac और Linux पर PATH सेटअप के बिना काम करता है
|
||||
uv tool install graphifyy && graphify install
|
||||
# या pipx के साथ
|
||||
pipx install graphifyy && graphify install
|
||||
# या सामान्य pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **आधिकारिक पैकेज:** PyPI पैकेज का नाम `graphifyy` है (`pip install graphifyy` से इंस्टॉल करें)। PyPI पर `graphify*` नाम वाले अन्य पैकेज इस प्रोजेक्ट से संबद्ध नहीं हैं। एकमात्र आधिकारिक रिपॉजिटरी [safishamsi/graphify](https://github.com/safishamsi/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` |
|
||||
| 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` |
|
||||
| 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` |
|
||||
|
||||
फिर अपना AI कोडिंग असिस्टेंट खोलें और टाइप करें:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
## उपयोग
|
||||
|
||||
```
|
||||
/graphify # वर्तमान डायरेक्टरी
|
||||
/graphify ./raw # विशिष्ट फोल्डर
|
||||
/graphify ./raw --update # केवल बदली हुई फ़ाइलें फिर से निकालें
|
||||
/graphify ./raw --directed # निर्देशित ग्राफ
|
||||
/graphify ./raw --no-viz # केवल रिपोर्ट + JSON
|
||||
/graphify ./raw --obsidian # Obsidian vault बनाएं
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # paper प्राप्त करें
|
||||
/graphify add <video-url> # वीडियो ट्रांसक्राइब करें
|
||||
/graphify query "attention और optimizer को क्या जोड़ता है?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # Git hooks इंस्टॉल करें
|
||||
graphify update ./src # कोड फ़ाइलें पुनः निकालें, LLM की जरूरत नहीं
|
||||
graphify watch ./src # स्वचालित ग्राफ अपडेट
|
||||
```
|
||||
|
||||
## आपको क्या मिलता है
|
||||
|
||||
**गॉड नोड्स** — सबसे अधिक डिग्री वाली अवधारणाएं (जिनसे सब कुछ गुजरता है)
|
||||
|
||||
**आश्चर्यजनक कनेक्शन** — कम्पोजिट स्कोर द्वारा रैंक किए गए। कोड-पेपर किनारे उच्च रैंक पाते हैं।
|
||||
|
||||
**सुझाए गए प्रश्न** — 4-5 प्रश्न जिन्हें ग्राफ विशेष रूप से अच्छी तरह उत्तर दे सकता है
|
||||
|
||||
**"क्यों"** — docstrings, inline comments, और design rationale को `rationale_for` नोड्स के रूप में निकाला जाता है।
|
||||
|
||||
**कॉन्फिडेंस स्कोर** — प्रत्येक INFERRED किनारे का `confidence_score` (0.0-1.0) होता है।
|
||||
|
||||
**टोकन बेंचमार्क** — प्रत्येक रन के बाद स्वचालित रूप से प्रिंट होता है। मिश्रित corpus पर: रॉ फ़ाइलों की तुलना में **71.5x** कम tokens।
|
||||
|
||||
## गोपनीयता
|
||||
|
||||
graphify दस्तावेज़ों, papers और छवियों के सिमेंटिक निष्कर्षण के लिए आपके AI असिस्टेंट की मॉडल API को फ़ाइल सामग्री भेजता है। कोड फ़ाइलें tree-sitter AST के माध्यम से स्थानीय रूप से प्रोसेस होती हैं। वीडियो और ऑडियो फ़ाइलें faster-whisper से स्थानीय रूप से ट्रांसक्राइब होती हैं। कोई टेलीमेट्री नहीं, कोई ट्रैकिंग नहीं।
|
||||
|
||||
## graphify पर बनाया — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) graphify के ऊपर एंटरप्राइज़ लेयर है। जहां graphify फ़ाइलों के एक फोल्डर को नॉलेज ग्राफ में बदलता है, Penpax वही ग्राफ आपके पूरे कार्य जीवन पर लागू करता है — निरंतर।
|
||||
|
||||
**फ्री ट्रायल जल्द लॉन्च होगा।** [वेटलिस्ट में शामिल हों →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## Star इतिहास
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Képesség AI kódolási asszisztensekhez.** Írja be a `/graphify` parancsot a Claude Code-ban, Codexben, OpenCode-ban, Cursorban, Gemini CLI-ben, GitHub Copilot CLI-ben, VS Code Copilot Chatben, Aiderben, OpenClawban, Factory Droidban, Traeben, Hermesben, Kiroban vagy a Google Antigravityben — beolvassa a fájljait, tudásgráfot épít, és visszaadja azt a struktúrát, amelyről nem tudta, hogy létezik. Értse meg gyorsabban a kódbázist. Találja meg az architektúrális döntések mögött álló „miértet".
|
||||
|
||||
Teljesen multimodális. Adjon hozzá kódot, PDF-eket, markdownt, képernyőképeket, diagramokat, táblafotókat, más nyelvű képeket vagy video- és hangfájlokat — a graphify mindenből kinyeri a fogalmakat és kapcsolatokat, és egyetlen gráfba köti össze őket. A videókat a Whisper segítségével helyben írja át. 25 programozási nyelvet támogat tree-sitter AST-n keresztül.
|
||||
|
||||
> Andrej Karpathy fenntart egy `/raw` mappát, ahova cikkeket, tweeteket, képernyőképeket és jegyzeteket helyez el. A graphify erre a problémára adott válasz — **71,5x** kevesebb token lekérdezésenként a nyers fájlok olvasásához képest, munkamenetek között is megmarad.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktív gráf — nyissa meg bármely böngészőben
|
||||
├── GRAPH_REPORT.md isten-csúcspontok, meglepő kapcsolatok, javasolt kérdések
|
||||
├── graph.json állandó gráf — hetekkel később is lekérdezhető
|
||||
└── cache/ SHA256-gyorsítótár — ismételt futtatások csak a módosított fájlokat dolgozzák fel
|
||||
```
|
||||
|
||||
## Hogyan működik
|
||||
|
||||
A graphify három menetben dolgozik. Először egy determinisztikus AST-menet kinyeri a struktúrát a kódfájlokból LLM nélkül. Ezután a video- és hangfájlokat a faster-whisper segítségével helyben írja át. Végül a Claude alügynökök párhuzamosan futnak dokumentumokon, cikkeken, képeken és átiratokban. Az eredményeket egy NetworkX-gráfba olvasztja össze, Leiden-nel klaszterezik, és interaktív HTML-ként, lekérdezhető JSON-ként és auditjelentésként exportálja.
|
||||
|
||||
Minden kapcsolat `EXTRACTED`, `INFERRED` (megbízhatósági pontszámmal) vagy `AMBIGUOUS` feliratot kap.
|
||||
|
||||
## Telepítés
|
||||
|
||||
**Követelmények:** Python 3.10+ és az alábbiak egyike: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) és mások.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# vagy pipx-szel
|
||||
pipx install graphifyy && graphify install
|
||||
# vagy pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Hivatalos csomag:** A PyPI-csomag neve `graphifyy`. Az egyetlen hivatalos tároló a [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Használat
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "mi köti össze az Attentiont az optimalizálóval?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Mit kap
|
||||
|
||||
**Isten-csúcspontok** — a legmagasabb fokú fogalmak · **Meglepő kapcsolatok** — pontszám szerint rendezve · **Javasolt kérdések** · **A „miért"** — docstringek és tervezési indoklások csúcspontként kinyerve · **Token-benchmark** — **71,5x** kevesebb token vegyes korpuszon.
|
||||
|
||||
## Adatvédelem
|
||||
|
||||
A kódfájlokat helyben dolgozza fel tree-sitter AST-n keresztül. A videókat helyben írja át a faster-whisper. Nincs telemetria.
|
||||
|
||||
## A graphify-ra épülve — Penpax
|
||||
|
||||
A [**Penpax**](https://safishamsi.github.io/penpax.ai) a graphify feletti vállalati réteg. **Ingyenes próbaverzió hamarosan.** [Csatlakozzon a várólistához →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Keterampilan untuk asisten kode AI.** Ketik `/graphify` di Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, atau Google Antigravity — membaca file Anda, membangun graf pengetahuan, dan mengembalikan struktur yang tidak Anda ketahui ada. Pahami codebase lebih cepat. Temukan "mengapa" di balik keputusan arsitektur.
|
||||
|
||||
Sepenuhnya multimodal. Tambahkan kode, PDF, markdown, tangkapan layar, diagram, foto papan tulis, gambar dalam bahasa lain, atau file video dan audio — graphify mengekstrak konsep dan hubungan dari semuanya dan menghubungkannya dalam satu graf. Video ditranskrip secara lokal dengan Whisper. Mendukung 25 bahasa pemrograman melalui tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy memelihara folder `/raw` tempat ia menyimpan makalah, tweet, tangkapan layar, dan catatan. graphify adalah jawaban untuk masalah itu — **71,5x** lebih sedikit token per kueri dibandingkan membaca file mentah, persisten di antara sesi.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html graf interaktif — buka di browser mana saja
|
||||
├── GRAPH_REPORT.md node dewa, koneksi mengejutkan, pertanyaan yang disarankan
|
||||
├── graph.json graf persisten — dapat dikueri berminggu-minggu kemudian
|
||||
└── cache/ cache SHA256 — pengulangan hanya memproses file yang berubah
|
||||
```
|
||||
|
||||
## Cara Kerja
|
||||
|
||||
graphify bekerja dalam tiga tahap. Pertama, tahap AST deterministik mengekstrak struktur dari file kode tanpa LLM. Kemudian file video dan audio ditranskrip secara lokal dengan faster-whisper. Terakhir, sub-agen Claude berjalan secara paralel pada dokumen, makalah, gambar, dan transkripsi. Hasilnya digabungkan ke dalam graf NetworkX, dikelompokkan dengan Leiden, dan diekspor sebagai HTML interaktif, JSON yang dapat dikueri, dan laporan audit.
|
||||
|
||||
Setiap hubungan diberi label `EXTRACTED`, `INFERRED` (dengan skor kepercayaan), atau `AMBIGUOUS`.
|
||||
|
||||
## Instalasi
|
||||
|
||||
**Persyaratan:** Python 3.10+ dan salah satu dari: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) dan lainnya.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# atau dengan pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# atau pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Paket resmi:** Paket PyPI bernama `graphifyy`. Satu-satunya repositori resmi adalah [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Penggunaan
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "apa yang menghubungkan Attention dengan optimizer?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Apa yang Anda Dapatkan
|
||||
|
||||
**Node dewa** — konsep dengan derajat tertinggi · **Koneksi mengejutkan** — diurutkan berdasarkan skor · **Pertanyaan yang disarankan** · **"Mengapa"** — docstring dan alasan desain diekstrak sebagai node · **Benchmark token** — **71,5x** lebih sedikit token pada corpus campuran.
|
||||
|
||||
## Privasi
|
||||
|
||||
File kode diproses secara lokal melalui tree-sitter AST. Video ditranskrip secara lokal dengan faster-whisper. Tidak ada telemetri.
|
||||
|
||||
## Dibangun di atas graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) adalah lapisan enterprise di atas graphify. **Uji coba gratis segera hadir.** [Bergabunglah dengan daftar tunggu →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,78 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Una skill per assistenti di codice IA.** Scrivi `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro o Google Antigravity — legge i tuoi file, costruisce un grafo della conoscenza e ti restituisce struttura che non sapevi esistesse. Comprendi una codebase più velocemente. Trova il "perché" dietro le decisioni architetturali.
|
||||
|
||||
Completamente multimodale. Aggiungi codice, PDF, markdown, screenshot, diagrammi, foto di lavagne, immagini in altre lingue, o file video e audio — graphify estrae concetti e relazioni da tutto e li connette in un unico grafo. I video vengono trascritti localmente con Whisper. Supporta 25 linguaggi di programmazione via tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy mantiene una cartella `/raw` dove deposita paper, tweet, screenshot e note. graphify è la risposta a quel problema — **71,5x** meno token per query rispetto alla lettura dei file grezzi, persistente tra le sessioni.
|
||||
|
||||
```
|
||||
/graphify . # funziona con qualsiasi cartella
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html grafo interattivo — apri in qualsiasi browser
|
||||
├── GRAPH_REPORT.md nodi dio, connessioni sorprendenti, domande suggerite
|
||||
├── graph.json grafo persistente — interrogabile settimane dopo
|
||||
└── cache/ cache SHA256 — le riesecuzioni elaborano solo i file modificati
|
||||
```
|
||||
|
||||
## Come funziona
|
||||
|
||||
graphify esegue in tre passaggi. Prima, un passaggio AST deterministico estrae la struttura dai file di codice senza LLM. Poi, i file video e audio vengono trascritti localmente con faster-whisper. Infine, i subagenti Claude eseguono in parallelo su documenti, paper, immagini e trascrizioni. I risultati vengono uniti in un grafo NetworkX, raggruppati con Leiden e esportati come HTML interattivo, JSON interrogabile e report di audit.
|
||||
|
||||
Ogni relazione è etichettata `EXTRACTED`, `INFERRED` (con punteggio di confidenza) o `AMBIGUOUS`.
|
||||
|
||||
## Installazione
|
||||
|
||||
**Requisiti:** Python 3.10+ e uno tra: [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), [Aider](https://aider.chat) e altri.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# oppure con pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# oppure pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Pacchetto ufficiale:** Il pacchetto PyPI si chiama `graphifyy`. L'unico repository ufficiale è [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Utilizzo
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update # solo file modificati
|
||||
/graphify ./raw --mode deep
|
||||
/graphify query "cosa connette Attention all'ottimizzatore?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Cosa ottieni
|
||||
|
||||
**Nodi dio** — concetti con il grado più alto · **Connessioni sorprendenti** — classificate per punteggio · **Domande suggerite** — 4-5 domande che il grafo è in grado di rispondere in modo unico · **Il "perché"** — docstring e rationale di design estratti come nodi · **Benchmark token** — **71,5x** meno token su corpus misto.
|
||||
|
||||
## Privacy
|
||||
|
||||
I file di codice vengono elaborati localmente via tree-sitter AST. I video vengono trascritti localmente con faster-whisper. Nessuna telemetria.
|
||||
|
||||
## Costruito su graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) è il livello enterprise su graphify. **Prova gratuita in arrivo.** [Unisciti alla lista d'attesa →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -1,6 +1,6 @@
|
||||
# graphify
|
||||
|
||||
[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja-JP.md) | [한국어](README.ko-KR.md)
|
||||
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
|
||||
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://pypi.org/project/graphifyy/)
|
||||
@@ -1,6 +1,6 @@
|
||||
# graphify
|
||||
|
||||
[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja-JP.md) | [한국어](README.ko-KR.md)
|
||||
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
|
||||
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://pypi.org/project/graphifyy/)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Een vaardigheid voor AI-codeassistenten.** Typ `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro of Google Antigravity — het leest je bestanden, bouwt een kennisgraaf en geeft je structuur terug die je niet wist dat er was. Begrijp een codebase sneller. Vind het "waarom" achter architecturale beslissingen.
|
||||
|
||||
Volledig multimodaal. Voeg code, PDF's, markdown, schermafbeeldingen, diagrammen, whiteboard-foto's, afbeeldingen in andere talen of video- en audiobestanden toe — graphify extraheert concepten en relaties uit alles en verbindt ze in één graaf. Video's worden lokaal getranscribeerd met Whisper. Ondersteunt 25 programmeertalen via tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy houdt een `/raw`-map bij waar hij papers, tweets, schermafbeeldingen en notities neerlegt. graphify is het antwoord op dat probleem — **71,5x** minder tokens per query versus het lezen van ruwe bestanden, persistent tussen sessies.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interactieve graaf — open in elke browser
|
||||
├── GRAPH_REPORT.md godknooppunten, verrassende verbindingen, voorgestelde vragen
|
||||
├── graph.json persistente graaf — weken later opvraagbaar
|
||||
└── cache/ SHA256-cache — herhaalde runs verwerken alleen gewijzigde bestanden
|
||||
```
|
||||
|
||||
## Hoe het werkt
|
||||
|
||||
graphify werkt in drie passes. Eerst extraheert een deterministische AST-pass structuur uit codebestanden zonder LLM. Vervolgens worden video- en audiobestanden lokaal getranscribeerd met faster-whisper. Ten slotte werken Claude-subagenten parallel over documenten, papers, afbeeldingen en transcripties. De resultaten worden samengevoegd in een NetworkX-graaf, geclusterd met Leiden en geëxporteerd als interactieve HTML, opvraagbare JSON en een auditrapport.
|
||||
|
||||
Elke relatie is gelabeld als `EXTRACTED`, `INFERRED` (met betrouwbaarheidsscore) of `AMBIGUOUS`.
|
||||
|
||||
## Installatie
|
||||
|
||||
**Vereisten:** Python 3.10+ en één van: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [Cursor](https://cursor.com), [Aider](https://aider.chat) en andere.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# of met pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# of pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Officieel pakket:** Het PyPI-pakket heet `graphifyy`. De enige officiële repository is [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Gebruik
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "wat verbindt Attention met de optimizer?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Wat je krijgt
|
||||
|
||||
**Godknooppunten** — concepten met de hoogste graad · **Verrassende verbindingen** — gerangschikt op score · **Voorgestelde vragen** · **Het "waarom"** — docstrings en ontwerprationale als knooppunten · **Tokenbenchmark** — **71,5x** minder tokens op gemengd corpus.
|
||||
|
||||
## Privacy
|
||||
|
||||
Codebestanden worden lokaal verwerkt via tree-sitter AST. Video's lokaal getranscribeerd met faster-whisper. Geen telemetrie.
|
||||
|
||||
## Gebouwd op graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) is de enterprise-laag boven op graphify. **Gratis proefversie binnenkort.** [Meld je aan voor de wachtlijst →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**En ferdighet for AI-kodeassistenter.** Skriv `/graphify` i Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro eller Google Antigravity — den leser filene dine, bygger en kunnskapsgraf og gir deg tilbake strukturen du ikke visste eksisterte. Forstå en kodebase raskere. Finn «hvorfor» bak arkitektoniske beslutninger.
|
||||
|
||||
Fullt multimodal. Legg til kode, PDF-er, markdown, skjermbilder, diagrammer, whiteboardbilder, bilder på andre språk eller video- og lydfiler — graphify ekstraherer begreper og relasjoner fra alt og kobler dem i én graf. Videoer transkriberes lokalt med Whisper. Støtter 25 programmeringsspråk via tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy opprettholder en `/raw`-mappe der han legger artikler, tweets, skjermbilder og notater. graphify er svaret på det problemet — **71,5x** færre tokens per spørring sammenlignet med å lese råfiler, vedvarende mellom sesjoner.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktiv graf — åpne i en hvilken som helst nettleser
|
||||
├── GRAPH_REPORT.md gudnoder, overraskende forbindelser, foreslåtte spørsmål
|
||||
├── graph.json vedvarende graf — forespørselbar uker senere
|
||||
└── cache/ SHA256-cache — gjentatte kjøringer behandler bare endrede filer
|
||||
```
|
||||
|
||||
## Hvordan det fungerer
|
||||
|
||||
graphify arbeider i tre gjennomganger. Først ekstraherer et deterministisk AST-gjennomgang struktur fra kodefiler uten LLM. Deretter transkriberes video- og lydfiler lokalt med faster-whisper. Til slutt kjører Claude-underagenter parallelt på dokumenter, artikler, bilder og transkripsjoner. Resultatene slås sammen i en NetworkX-graf, klynges med Leiden og eksporteres som interaktiv HTML, forespørselbar JSON og revisjonsrapport.
|
||||
|
||||
Hver relasjon er merket `EXTRACTED`, `INFERRED` (med konfidenspoeng) eller `AMBIGUOUS`.
|
||||
|
||||
## Installasjon
|
||||
|
||||
**Krav:** Python 3.10+ og én av: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) og andre.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# eller med pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# eller pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Offisiell pakke:** PyPI-pakken heter `graphifyy`. Det eneste offisielle depotet er [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Bruk
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "hva kobler Attention til optimizeren?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Hva du får
|
||||
|
||||
**Gudnoder** — begreper med høyest grad · **Overraskende forbindelser** — rangert etter poeng · **Foreslåtte spørsmål** · **«Hvorfor»** — docstrings og designbegrunnelse ekstrahert som noder · **Token-benchmark** — **71,5x** færre tokens på blandet korpus.
|
||||
|
||||
## Personvern
|
||||
|
||||
Kodefiler behandles lokalt via tree-sitter AST. Videoer transkriberes lokalt med faster-whisper. Ingen telemetri.
|
||||
|
||||
## Bygget på graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) er enterprise-laget oppå graphify. **Gratis prøveperiode kommer snart.** [Bli med på ventelisten →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,78 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Umiejętność dla asystenta kodowania AI.** Wpisz `/graphify` w Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro lub Google Antigravity — czyta Twoje pliki, buduje graf wiedzy i zwraca Ci strukturę, o której nie wiedziałeś, że istnieje. Rozumiej bazę kodu szybciej. Znajdź „dlaczego" za decyzjami architektonicznymi.
|
||||
|
||||
W pełni multimodalny. Dodaj kod, PDF, markdown, zrzuty ekranu, diagramy, zdjęcia tablic, obrazy w innych językach lub pliki wideo i audio — graphify wyodrębnia koncepcje i relacje ze wszystkiego i łączy je w jeden graf. Wideo są transkrybowane lokalnie za pomocą Whisper. Obsługuje 25 języków programowania przez tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy prowadzi folder `/raw`, gdzie wrzuca artykuły, tweety, zrzuty ekranu i notatki. graphify jest odpowiedzią na ten problem — **71,5x** mniej tokenów na zapytanie w porównaniu z czytaniem surowych plików, trwały między sesjami.
|
||||
|
||||
```
|
||||
/graphify . # działa na dowolnym folderze
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktywny graf — otwórz w dowolnej przeglądarce
|
||||
├── GRAPH_REPORT.md węzły boga, zaskakujące połączenia, sugerowane pytania
|
||||
├── graph.json trwały graf — zapytaj tygodnie później
|
||||
└── cache/ cache SHA256 — ponowne uruchomienia przetwarzają tylko zmienione pliki
|
||||
```
|
||||
|
||||
## Jak to działa
|
||||
|
||||
graphify działa w trzech przebiegach. Najpierw deterministyczny przebieg AST wyodrębnia strukturę z plików kodu bez LLM. Następnie pliki wideo i audio są transkrybowane lokalnie za pomocą faster-whisper. Na koniec subagenci Claude działają równolegle na dokumentach, artykułach, obrazach i transkrypcjach. Wyniki są łączone w graf NetworkX, grupowane za pomocą Leiden i eksportowane jako interaktywny HTML, JSON i raport audytu.
|
||||
|
||||
Każda relacja jest oznaczona `EXTRACTED`, `INFERRED` (z wynikiem pewności) lub `AMBIGUOUS`.
|
||||
|
||||
## Instalacja
|
||||
|
||||
**Wymagania:** Python 3.10+ i jedno z: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) i inne.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# lub z pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# lub pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Oficjalny pakiet:** Pakiet PyPI nazywa się `graphifyy`. Jedyne oficjalne repozytorium to [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Użycie
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update # tylko zmienione pliki
|
||||
/graphify ./raw --mode deep
|
||||
/graphify query "co łączy Attention z optymalizatorem?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Co otrzymujesz
|
||||
|
||||
**Węzły boga** — koncepcje o najwyższym stopniu · **Zaskakujące połączenia** — posortowane według wyniku · **Sugerowane pytania** — 4-5 pytań, na które graf jest wyjątkowo zdolny odpowiedzieć · **„Dlaczego"** — docstringi i uzasadnienia projektowe wyodrębnione jako węzły · **Benchmark tokenów** — **71,5x** mniej tokenów na mieszanym korpusie.
|
||||
|
||||
## Prywatność
|
||||
|
||||
Pliki kodu są przetwarzane lokalnie przez tree-sitter AST. Wideo transkrybowane lokalnie z faster-whisper. Brak telemetrii.
|
||||
|
||||
## Zbudowane na graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) to warstwa enterprise nad graphify. **Bezpłatna wersja próbna wkrótce.** [Dołącz do listy oczekujących →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,170 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
</p>
|
||||
|
||||
**Uma habilidade para assistentes de código IA.** Digite `/graphify` no Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro ou Google Antigravity — ele lê seus arquivos, constrói um grafo de conhecimento e devolve a você estrutura que você não sabia que existia. Entenda uma base de código mais rapidamente. Encontre o "porquê" por trás das decisões arquiteturais.
|
||||
|
||||
Totalmente multimodal. Adicione código, PDFs, markdown, capturas de tela, diagramas, fotos de quadros brancos, imagens em outros idiomas, ou arquivos de vídeo e áudio — graphify extrai conceitos e relações de tudo isso e os conecta em um único grafo. Vídeos são transcritos localmente com Whisper usando um prompt adaptado ao domínio derivado do seu corpus. 25 linguagens de programação suportadas 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 mantém uma pasta `/raw` onde deposita papers, tweets, capturas de tela e notas. graphify é a resposta para esse problema — 71,5x menos tokens por consulta versus ler os arquivos brutos, persistente entre sessões, honesto sobre o que foi encontrado versus inferido.
|
||||
|
||||
```
|
||||
/graphify . # funciona em qualquer pasta — seu código, notas, papers, tudo
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html grafo interativo — abrir em qualquer navegador, clicar em nós, pesquisar
|
||||
├── GRAPH_REPORT.md nós deus, conexões surpreendentes, perguntas sugeridas
|
||||
├── graph.json grafo persistente — consultar semanas depois sem reler
|
||||
└── cache/ cache SHA256 — re-execuções processam apenas arquivos modificados
|
||||
```
|
||||
|
||||
Adicione um arquivo `.graphifyignore` para excluir pastas:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
Mesma sintaxe do `.gitignore`.
|
||||
|
||||
## Como funciona
|
||||
|
||||
graphify executa em três passes. Primeiro, uma passagem AST determinística extrai estrutura de arquivos de código (classes, funções, importações, grafos de chamadas, docstrings, comentários de justificativa) sem LLM. Segundo, arquivos de vídeo e áudio são transcritos localmente com faster-whisper. Terceiro, subagentes Claude executam em paralelo sobre documentos, papers, imagens e transcrições para extrair conceitos, relações e justificativas de design. Os resultados são mesclados em um grafo NetworkX, agrupados com detecção de comunidades Leiden, e exportados como HTML interativo, JSON consultável e um relatório de auditoria em linguagem natural.
|
||||
|
||||
**O clustering é baseado em topologia de grafo — sem embeddings.** Leiden encontra comunidades por densidade de arestas. As arestas de similaridade semântica que Claude extrai (`semantically_similar_to`, marcadas INFERRED) já estão no grafo. A estrutura do grafo é o sinal de similaridade — nenhum passo de embedding separado ou banco de dados vetorial é necessário.
|
||||
|
||||
Cada relação é marcada como `EXTRACTED` (encontrada diretamente na fonte), `INFERRED` (inferência razoável com pontuação de confiança) ou `AMBIGUOUS` (marcada para revisão).
|
||||
|
||||
## Instalação
|
||||
|
||||
**Requisitos:** Python 3.10+ e um de: [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 ou [Google Antigravity](https://antigravity.google)
|
||||
|
||||
```bash
|
||||
# Recomendado — funciona no Mac e Linux sem configurar o PATH
|
||||
uv tool install graphifyy && graphify install
|
||||
# ou com pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# ou pip simples
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Pacote oficial:** O pacote PyPI chama-se `graphifyy` (instalar com `pip install graphifyy`). Outros pacotes chamados `graphify*` no PyPI não são afiliados a este projeto. O único repositório oficial é [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
### Suporte a plataformas
|
||||
|
||||
| Plataforma | Comando de instalação |
|
||||
|------------|-----------------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (detecção automática) ou `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` |
|
||||
|
||||
Depois abra seu assistente de código IA e digite:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
Nota: Codex usa `$` em vez de `/` para habilidades, então digite `$graphify .`.
|
||||
|
||||
### Fazer o assistente sempre usar o grafo (recomendado)
|
||||
|
||||
Após construir um grafo, execute isso uma vez no seu projeto:
|
||||
|
||||
| Plataforma | Comando |
|
||||
|------------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
## Uso
|
||||
|
||||
```
|
||||
/graphify # diretório atual
|
||||
/graphify ./raw # pasta específica
|
||||
/graphify ./raw --mode deep # extração de arestas INFERRED mais agressiva
|
||||
/graphify ./raw --update # re-extrair apenas arquivos modificados
|
||||
/graphify ./raw --directed # grafo dirigido
|
||||
/graphify ./raw --cluster-only # re-executar clustering no grafo existente
|
||||
/graphify ./raw --no-viz # sem HTML, apenas relatório + JSON
|
||||
/graphify ./raw --obsidian # gerar vault do Obsidian (opt-in)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # buscar um paper
|
||||
/graphify add <video-url> # baixar áudio, transcrever, adicionar
|
||||
/graphify query "o que conecta Attention ao otimizador?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # instalar hooks do Git
|
||||
graphify update ./src # re-extrair arquivos de código, sem LLM
|
||||
graphify watch ./src # atualização automática do grafo
|
||||
```
|
||||
|
||||
## O que você obtém
|
||||
|
||||
**Nós deus** — conceitos com maior grau (por onde tudo passa)
|
||||
|
||||
**Conexões surpreendentes** — classificadas por pontuação composta. Arestas código-paper pontuam mais alto. Cada resultado inclui um porquê em linguagem natural.
|
||||
|
||||
**Perguntas sugeridas** — 4-5 perguntas que o grafo está em posição única de responder
|
||||
|
||||
**O "porquê"** — docstrings, comentários inline (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), e justificativas de design extraídas como nós `rationale_for`.
|
||||
|
||||
**Pontuações de confiança** — cada aresta INFERRED tem um `confidence_score` (0,0-1,0).
|
||||
|
||||
**Benchmark de tokens** — impresso automaticamente após cada execução. Em um corpus misto: **71,5x** menos tokens por consulta vs arquivos brutos.
|
||||
|
||||
**Sincronização automática** (`--watch`) — atualiza o grafo automaticamente quando o código muda.
|
||||
|
||||
**Hooks do Git** (`graphify hook install`) — instala hooks post-commit e post-checkout.
|
||||
|
||||
## Privacidade
|
||||
|
||||
graphify envia conteúdo de arquivos para a API do modelo do seu assistente IA para extração semântica de documentos, papers e imagens. Arquivos de código são processados localmente via tree-sitter AST. Arquivos de vídeo e áudio são transcritos localmente com faster-whisper. Sem telemetria, sem rastreamento de uso.
|
||||
|
||||
## Stack técnico
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Extração semântica via Claude, GPT-4 ou o modelo da sua plataforma. Transcrição de vídeo via faster-whisper + yt-dlp (opcional).
|
||||
|
||||
## Construído sobre graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) é a camada enterprise sobre o graphify. Onde o graphify transforma uma pasta de arquivos em um grafo de conhecimento, o Penpax aplica o mesmo grafo a toda a sua vida profissional — continuamente.
|
||||
|
||||
**Teste gratuito em breve.** [Entrar na lista de espera →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## Histórico de estrelas
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**O abilitate pentru asistenții de cod AI.** Tastați `/graphify` în Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro sau Google Antigravity — citește fișierele dvs., construiește un graf de cunoștințe și vă returnează structura pe care nu știați că există. Înțelegeți mai rapid o bază de cod. Găsiți „de ce"-ul din spatele deciziilor arhitecturale.
|
||||
|
||||
Complet multimodal. Adăugați cod, PDF-uri, markdown, capturi de ecran, diagrame, fotografii cu tablă albă, imagini în alte limbi sau fișiere video și audio — graphify extrage concepte și relații din toate și le conectează într-un singur graf. Videoclipurile sunt transcrise local cu Whisper. Suportă 25 de limbaje de programare prin tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy menține un folder `/raw` unde depune lucrări, tweet-uri, capturi de ecran și note. graphify este răspunsul la această problemă — **71,5x** mai puțini token pe interogare față de citirea fișierelor brute, persistent între sesiuni.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html graf interactiv — deschideți în orice browser
|
||||
├── GRAPH_REPORT.md noduri-zeu, conexiuni surprinzătoare, întrebări sugerate
|
||||
├── graph.json graf persistent — interogabil săptămâni mai târziu
|
||||
└── cache/ cache SHA256 — rulările repetate procesează doar fișierele modificate
|
||||
```
|
||||
|
||||
## Cum funcționează
|
||||
|
||||
graphify lucrează în trei treceri. Mai întâi, o trecere AST deterministă extrage structura din fișierele de cod fără LLM. Apoi fișierele video și audio sunt transcrise local cu faster-whisper. În final, sub-agenții Claude rulează în paralel pe documente, lucrări, imagini și transcrieri. Rezultatele sunt îmbinate într-un graf NetworkX, grupate cu Leiden și exportate ca HTML interactiv, JSON interogabil și raport de audit.
|
||||
|
||||
Fiecare relație este etichetată `EXTRACTED`, `INFERRED` (cu scor de încredere) sau `AMBIGUOUS`.
|
||||
|
||||
## Instalare
|
||||
|
||||
**Cerințe:** Python 3.10+ și unul din: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) și altele.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# sau cu pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# sau pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Pachet oficial:** Pachetul PyPI se numește `graphifyy`. Singurul depozit oficial este [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Utilizare
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "ce conectează Attention cu optimizatorul?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Ce obțineți
|
||||
|
||||
**Noduri-zeu** — concepte cu cel mai mare grad · **Conexiuni surprinzătoare** — clasificate după scor · **Întrebări sugerate** · **„De ce"** — docstring-uri și raționale de design extrase ca noduri · **Benchmark token** — **71,5x** mai puțini token pe corpus mixt.
|
||||
|
||||
## Confidențialitate
|
||||
|
||||
Fișierele de cod sunt procesate local prin tree-sitter AST. Videoclipurile sunt transcrise local cu faster-whisper. Fără telemetrie.
|
||||
|
||||
## Construit pe graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) este stratul enterprise peste graphify. **Perioadă de probă gratuită în curând.** [Alăturați-vă listei de așteptare →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,170 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
</p>
|
||||
|
||||
**Навык для AI-ассистента по написанию кода.** Введите `/graphify` в Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro или Google Antigravity — он прочитает ваши файлы, построит граф знаний и вернёт вам структуру, о существовании которой вы не подозревали. Понимайте кодовую базу быстрее. Находите «почему» за архитектурными решениями.
|
||||
|
||||
Полностью мультимодальный. Добавляйте код, PDF, markdown, скриншоты, диаграммы, фотографии досок, изображения на других языках, видео и аудиофайлы — graphify извлекает концепции и связи из всего этого и объединяет их в один граф. Видео транскрибируются локально с Whisper, используя доменный промпт из вашего корпуса. Поддерживается 25 языков программирования через 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).
|
||||
|
||||
> Андрей Карпати ведёт папку `/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 работает в три прохода. Сначала детерминированный AST-проход извлекает структуру из файлов кода (классы, функции, импорты, графы вызовов, docstrings, комментарии с обоснованием) — без LLM. Затем видео и аудиофайлы транскрибируются локально с faster-whisper. Наконец, 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), [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 или [Google Antigravity](https://antigravity.google)
|
||||
|
||||
```bash
|
||||
# Рекомендуется — работает на Mac и Linux без настройки PATH
|
||||
uv tool install graphifyy && graphify install
|
||||
# или с pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# или обычный pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Официальный пакет:** Пакет PyPI называется `graphifyy` (установить через `pip install graphifyy`). Другие пакеты с именем `graphify*` на PyPI не связаны с этим проектом. Единственный официальный репозиторий — [safishamsi/graphify](https://github.com/safishamsi/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` |
|
||||
| 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` |
|
||||
|
||||
Затем откройте AI-ассистент и введите:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
Примечание: Codex использует `$` вместо `/` для навыков, поэтому вводите `$graphify .`.
|
||||
|
||||
### Заставить ассистента всегда использовать граф (рекомендуется)
|
||||
|
||||
После построения графа выполните это один раз в вашем проекте:
|
||||
|
||||
| Платформа | Команда |
|
||||
|-----------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
## Использование
|
||||
|
||||
```
|
||||
/graphify # текущая директория
|
||||
/graphify ./raw # конкретная папка
|
||||
/graphify ./raw --mode deep # более агрессивное извлечение INFERRED-рёбер
|
||||
/graphify ./raw --update # повторно извлечь только изменённые файлы
|
||||
/graphify ./raw --directed # направленный граф
|
||||
/graphify ./raw --cluster-only # перезапустить кластеризацию на существующем графе
|
||||
/graphify ./raw --no-viz # без HTML, только отчёт + JSON
|
||||
/graphify ./raw --obsidian # создать Obsidian vault (opt-in)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # получить статью
|
||||
/graphify add <video-url> # скачать аудио, транскрибировать, добавить
|
||||
/graphify query "что связывает Attention с оптимизатором?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # установить Git-хуки
|
||||
graphify update ./src # повторно извлечь файлы кода, без LLM
|
||||
graphify watch ./src # автоматическое обновление графа
|
||||
```
|
||||
|
||||
## Что вы получаете
|
||||
|
||||
**Бог-узлы** — концепции с наибольшей степенью (через которые проходит всё)
|
||||
|
||||
**Неожиданные связи** — отсортированы по составному баллу. Рёбра код-статья получают более высокий рейтинг. Каждый результат содержит объяснение «почему» на естественном языке.
|
||||
|
||||
**Предлагаемые вопросы** — 4-5 вопросов, на которые граф уникально способен ответить
|
||||
|
||||
**«Почему»** — docstrings, встроенные комментарии (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), и обоснования дизайна из документов извлекаются как узлы `rationale_for`.
|
||||
|
||||
**Оценки уверенности** — каждое INFERRED-ребро имеет `confidence_score` (0,0-1,0).
|
||||
|
||||
**Бенчмарк токенов** — выводится автоматически после каждого запуска. На смешанном корпусе: **71,5-кратное** сокращение токенов на запрос vs сырые файлы.
|
||||
|
||||
**Авто-синхронизация** (`--watch`) — обновляет граф автоматически при изменении кода.
|
||||
|
||||
**Git-хуки** (`graphify hook install`) — устанавливает post-commit и post-checkout хуки.
|
||||
|
||||
## Конфиденциальность
|
||||
|
||||
graphify отправляет содержимое файлов в API модели вашего AI-ассистента для семантического извлечения из документов, статей и изображений. Файлы кода обрабатываются локально через tree-sitter AST. Видео и аудиофайлы транскрибируются локально с faster-whisper. Никакой телеметрии, никакого отслеживания использования.
|
||||
|
||||
## Технологический стек
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Семантическое извлечение через Claude, GPT-4 или модель вашей платформы. Транскрипция видео через faster-whisper + yt-dlp (опционально).
|
||||
|
||||
## Построено на graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) — корпоративный слой поверх graphify. Там, где graphify превращает папку с файлами в граф знаний, Penpax применяет тот же граф ко всей вашей рабочей жизни — непрерывно.
|
||||
|
||||
**Бесплатный пробный период скоро.** [Вступить в список ожидания →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## История звёзд
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**En färdighet för AI-kodassistenter.** Skriv `/graphify` i Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro eller Google Antigravity — den läser dina filer, bygger ett kunskapsgrafer och ger tillbaka strukturen du inte visste fanns. Förstå en kodbas snabbare. Hitta "varför" bakom arkitekturella beslut.
|
||||
|
||||
Helt multimodal. Lägg till kod, PDF:er, markdown, skärmdumpar, diagram, whiteboardfoton, bilder på andra språk eller video- och ljudfiler — graphify extraherar begrepp och relationer från allt och kopplar samman dem i ett enda graf. Videor transkriberas lokalt med Whisper. Stödjer 25 programmeringsspråk via tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy håller en `/raw`-mapp där han lägger papper, tweets, skärmdumpar och anteckningar. graphify är svaret på det problemet — **71,5x** färre tokens per fråga jämfört med att läsa råfiler, beständigt mellan sessioner.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktivt diagram — öppna i valfri webbläsare
|
||||
├── GRAPH_REPORT.md gudnoder, överraskande kopplingar, föreslagna frågor
|
||||
├── graph.json beständigt diagram — kan frågas veckor senare
|
||||
└── cache/ SHA256-cache — upprepade körningar behandlar bara ändrade filer
|
||||
```
|
||||
|
||||
## Hur det fungerar
|
||||
|
||||
graphify arbetar i tre pass. Först extraherar ett deterministiskt AST-pass struktur från kodfiler utan LLM. Sedan transkriberas video- och ljudfiler lokalt med faster-whisper. Slutligen kör Claude-subagenter parallellt på dokument, papper, bilder och transkriptioner. Resultaten slås samman i ett NetworkX-diagram, klustras med Leiden och exporteras som interaktiv HTML, frågebar JSON och revisionsrapport.
|
||||
|
||||
Varje relation är märkt `EXTRACTED`, `INFERRED` (med konfidenspoäng) eller `AMBIGUOUS`.
|
||||
|
||||
## Installation
|
||||
|
||||
**Krav:** Python 3.10+ och ett av: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) med flera.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# eller med pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# eller pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Officiellt paket:** PyPI-paketet heter `graphifyy`. Det enda officiella förrådet är [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Användning
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "vad kopplar Attention till optimizern?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Vad du får
|
||||
|
||||
**Gudnoder** — begrepp med högst grad · **Överraskande kopplingar** — rangordnade efter poäng · **Föreslagna frågor** · **"Varför"** — docsträngar och designmotivering extraherade som noder · **Token-benchmark** — **71,5x** färre tokens på blandat korpus.
|
||||
|
||||
## Integritet
|
||||
|
||||
Kodfiler behandlas lokalt via tree-sitter AST. Videor transkriberas lokalt med faster-whisper. Ingen telemetri.
|
||||
|
||||
## Byggt på graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) är enterprise-lagret ovanpå graphify. **Gratis provperiod kommer snart.** [Gå med i väntelistan →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**ทักษะสำหรับผู้ช่วยเขียนโค้ด AI** พิมพ์ `/graphify` ใน Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro หรือ Google Antigravity — มันจะอ่านไฟล์ของคุณ สร้างกราฟความรู้ และส่งคืนโครงสร้างที่คุณไม่รู้ว่ามีอยู่ ทำความเข้าใจ codebase ได้เร็วขึ้น ค้นหา "ทำไม" เบื้องหลังการตัดสินใจด้านสถาปัตยกรรม
|
||||
|
||||
มัลติโมดัลอย่างสมบูรณ์ เพิ่มโค้ด, PDF, markdown, ภาพหน้าจอ, ไดอะแกรม, ภาพถ่ายกระดานไวท์บอร์ด, รูปภาพในภาษาอื่น หรือไฟล์วิดีโอและเสียง — graphify ดึงแนวคิดและความสัมพันธ์จากทุกอย่างและเชื่อมต่อกันในกราฟเดียว วิดีโอถูกถอดเสียงในเครื่องด้วย Whisper รองรับ 25 ภาษาการเขียนโปรแกรมผ่าน tree-sitter AST
|
||||
|
||||
> Andrej Karpathy รักษาโฟลเดอร์ `/raw` ที่เขาวางงานวิจัย, ทวีต, ภาพหน้าจอ และบันทึก graphify คือคำตอบสำหรับปัญหานั้น — **71.5 เท่า** โทเค็นน้อยลงต่อการสืบค้นเมื่อเทียบกับการอ่านไฟล์ดิบ, ยั่งยืนระหว่างเซสชัน
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html กราฟแบบโต้ตอบ — เปิดในเบราว์เซอร์ใดก็ได้
|
||||
├── GRAPH_REPORT.md โหนดพระเจ้า, การเชื่อมต่อที่น่าประหลาดใจ, คำถามที่แนะนำ
|
||||
├── graph.json กราฟถาวร — สามารถสืบค้นได้หลายสัปดาห์ต่อมา
|
||||
└── cache/ SHA256-cache — การรันซ้ำประมวลผลเฉพาะไฟล์ที่เปลี่ยนแปลง
|
||||
```
|
||||
|
||||
## วิธีการทำงาน
|
||||
|
||||
graphify ทำงานใน 3 รอบ ก่อนอื่น AST pass แบบ deterministic ดึงโครงสร้างจากไฟล์โค้ดโดยไม่ต้องใช้ LLM จากนั้นไฟล์วิดีโอและเสียงถูกถอดเสียงในเครื่องด้วย faster-whisper สุดท้าย Claude sub-agent ทำงานแบบขนานกันบนเอกสาร, งานวิจัย, รูปภาพ และบทถอดเสียง ผลลัพธ์ถูกรวมเข้ากับกราฟ NetworkX, จัดกลุ่มด้วย Leiden และส่งออกเป็น HTML แบบโต้ตอบ, JSON ที่สืบค้นได้ และรายงานการตรวจสอบ
|
||||
|
||||
ความสัมพันธ์แต่ละอย่างถูกติดป้าย `EXTRACTED`, `INFERRED` (พร้อมคะแนนความเชื่อมั่น) หรือ `AMBIGUOUS`
|
||||
|
||||
## การติดตั้ง
|
||||
|
||||
**ข้อกำหนด:** Python 3.10+ และหนึ่งใน: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) และอื่นๆ
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# หรือกับ pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# หรือ pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **แพ็กเกจอย่างเป็นทางการ:** แพ็กเกจ PyPI ชื่อ `graphifyy` repository อย่างเป็นทางการเดียวคือ [safishamsi/graphify](https://github.com/safishamsi/graphify)
|
||||
|
||||
## การใช้งาน
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "อะไรเชื่อม Attention กับ optimizer?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## สิ่งที่คุณได้รับ
|
||||
|
||||
**โหนดพระเจ้า** — แนวคิดที่มีระดับสูงสุด · **การเชื่อมต่อที่น่าประหลาดใจ** — จัดอันดับตามคะแนน · **คำถามที่แนะนำ** · **"ทำไม"** — docstring และเหตุผลการออกแบบที่ดึงออกมาเป็นโหนด · **เกณฑ์มาตรฐานโทเค็น** — **71.5 เท่า** โทเค็นน้อยลงบน corpus ผสม
|
||||
|
||||
## ความเป็นส่วนตัว
|
||||
|
||||
ไฟล์โค้ดถูกประมวลผลในเครื่องผ่าน tree-sitter AST วิดีโอถูกถอดเสียงในเครื่องด้วย faster-whisper ไม่มีการส่งข้อมูลวัดผล
|
||||
|
||||
## สร้างบน graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) คือชั้น enterprise เหนือ graphify **ทดลองใช้ฟรีเร็วๆ นี้** [เข้าร่วมรายชื่อรอ →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Yapay zeka kod asistanları için bir beceri.** Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro veya Google Antigravity'de `/graphify` yazın — dosyalarınızı okur, bir bilgi grafiği oluşturur ve farkında olmadığınız yapıyı size geri verir. Kod tabanını daha hızlı anlayın. Mimari kararların arkasındaki "neden"i bulun.
|
||||
|
||||
Tamamen çok modlu. Kod, PDF, markdown, ekran görüntüleri, diyagramlar, beyaz tahta fotoğrafları, başka dillerdeki görüntüler veya video ve ses dosyaları ekleyin — graphify her şeyden kavramları ve ilişkileri çıkarır ve bunları tek bir grafikte birleştirir. Videolar Whisper ile yerel olarak transkribe edilir. tree-sitter AST aracılığıyla 25 programlama dilini destekler.
|
||||
|
||||
> Andrej Karpathy, makaleleri, tweetleri, ekran görüntülerini ve notları bıraktığı bir `/raw` klasörü tutar. graphify bu soruna yanıttır — ham dosyaları okumaya kıyasla sorgu başına **71,5x** daha az token, oturumlar arasında kalıcı.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html etkileşimli grafik — herhangi bir tarayıcıda açın
|
||||
├── GRAPH_REPORT.md tanrı düğümleri, şaşırtıcı bağlantılar, önerilen sorular
|
||||
├── graph.json kalıcı grafik — haftalar sonra sorgulanabilir
|
||||
└── cache/ SHA256 önbelleği — tekrarlanan çalışmalar yalnızca değiştirilen dosyaları işler
|
||||
```
|
||||
|
||||
## Nasıl çalışır
|
||||
|
||||
graphify üç geçişte çalışır. Önce deterministik bir AST geçişi, LLM olmadan kod dosyalarından yapı çıkarır. Ardından video ve ses dosyaları faster-whisper ile yerel olarak transkribe edilir. Son olarak Claude alt ajanları belgeler, makaleler, görüntüler ve transkriptler üzerinde paralel olarak çalışır. Sonuçlar bir NetworkX grafiğinde birleştirilir, Leiden ile kümelenir ve etkileşimli HTML, sorgulanabilir JSON ve denetim raporu olarak dışa aktarılır.
|
||||
|
||||
Her ilişki `EXTRACTED`, `INFERRED` (güven puanıyla) veya `AMBIGUOUS` olarak etiketlenir.
|
||||
|
||||
## Kurulum
|
||||
|
||||
**Gereksinimler:** Python 3.10+ ve şunlardan biri: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) ve diğerleri.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# veya pipx ile
|
||||
pipx install graphifyy && graphify install
|
||||
# veya pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Resmi paket:** PyPI paketi `graphifyy` olarak adlandırılır. Tek resmi depo [safishamsi/graphify](https://github.com/safishamsi/graphify)'dir.
|
||||
|
||||
## Kullanım
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "Attention'ı optimizer'a ne bağlıyor?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Ne elde edersiniz
|
||||
|
||||
**Tanrı düğümleri** — en yüksek dereceli kavramlar · **Şaşırtıcı bağlantılar** — puana göre sıralanmış · **Önerilen sorular** · **"Neden"** — doküman dizileri ve tasarım gerekçeleri düğümler olarak çıkarılır · **Token kıyaslaması** — karma derlemede **71,5x** daha az token.
|
||||
|
||||
## Gizlilik
|
||||
|
||||
Kod dosyaları tree-sitter AST aracılığıyla yerel olarak işlenir. Videolar faster-whisper ile yerel olarak transkribe edilir. Telemetri yok.
|
||||
|
||||
## graphify üzerine inşa edildi — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai), graphify üzerindeki kurumsal katmandır. **Ücretsiz deneme yakında.** [Bekleme listesine katılın →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Навичка для ШІ-асистентів кодування.** Введіть `/graphify` у Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro або Google Antigravity — він читає ваші файли, будує граф знань і повертає вам структуру, про яку ви не знали. Розумійте кодову базу швидше. Знайдіть «чому» за архітектурними рішеннями.
|
||||
|
||||
Повністю мультимодальний. Додавайте код, PDF, markdown, знімки екрана, діаграми, фотографії дошок, зображення іншими мовами або відео- та аудіофайли — graphify витягує концепції та зв'язки з усього і з'єднує їх в один граф. Відео транскрибуються локально за допомогою Whisper. Підтримує 25 мов програмування через tree-sitter AST.
|
||||
|
||||
> Андрій Карпатій веде папку `/raw`, куди кладе статті, твіти, знімки екрана та нотатки. graphify — відповідь на цю проблему — **71,5x** менше токенів на запит порівняно з читанням сирих файлів, зберігається між сесіями.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html інтерактивний граф — відкрийте в будь-якому браузері
|
||||
├── GRAPH_REPORT.md вузли-боги, несподівані зв'язки, запропоновані питання
|
||||
├── graph.json постійний граф — можна запитувати через тижні
|
||||
└── cache/ SHA256-кеш — повторні запуски обробляють лише змінені файли
|
||||
```
|
||||
|
||||
## Як це працює
|
||||
|
||||
graphify працює в три проходи. Спочатку детерміністичний прохід AST витягує структуру з файлів коду без LLM. Потім відео та аудіофайли транскрибуються локально за допомогою faster-whisper. Нарешті субагенти Claude працюють паралельно над документами, статтями, зображеннями та транскрипціями. Результати об'єднуються в граф NetworkX, кластеризуються з Leiden і експортуються як інтерактивний HTML, JSON для запитів і звіт аудиту.
|
||||
|
||||
Кожен зв'язок позначений як `EXTRACTED`, `INFERRED` (з оцінкою впевненості) або `AMBIGUOUS`.
|
||||
|
||||
## Встановлення
|
||||
|
||||
**Вимоги:** Python 3.10+ та одне з: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) та інші.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# або з pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# або pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Офіційний пакет:** Пакет PyPI називається `graphifyy`. Єдиний офіційний репозиторій — [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Використання
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "що пов'язує Attention з оптимізатором?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Що ви отримуєте
|
||||
|
||||
**Вузли-боги** — концепції з найвищим ступенем · **Несподівані зв'язки** — відсортовані за оцінкою · **Запропоновані питання** · **«Чому»** — рядки документації та обґрунтування дизайну витягнуті як вузли · **Бенчмарк токенів** — **71,5x** менше токенів на змішаному корпусі.
|
||||
|
||||
## Конфіденційність
|
||||
|
||||
Файли коду обробляються локально через tree-sitter AST. Відео транскрибуються локально за допомогою faster-whisper. Без телеметрії.
|
||||
|
||||
## Побудовано на graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) — корпоративний рівень над graphify. **Безкоштовна пробна версія незабаром.** [Приєднайтесь до списку очікування →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Kỹ năng dành cho trợ lý lập trình AI.** Gõ `/graphify` trong Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro hoặc Google Antigravity — nó đọc các tệp của bạn, xây dựng đồ thị kiến thức và trả lại cho bạn cấu trúc mà bạn không biết là tồn tại. Hiểu codebase nhanh hơn. Tìm ra "tại sao" đằng sau các quyết định kiến trúc.
|
||||
|
||||
Hoàn toàn đa phương thức. Thêm code, PDF, markdown, ảnh chụp màn hình, sơ đồ, ảnh bảng trắng, hình ảnh bằng ngôn ngữ khác hoặc tệp video và âm thanh — graphify trích xuất các khái niệm và mối quan hệ từ tất cả mọi thứ và kết nối chúng trong một đồ thị duy nhất. Video được phiên âm cục bộ bằng Whisper. Hỗ trợ 25 ngôn ngữ lập trình qua tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy duy trì một thư mục `/raw` nơi anh ấy đặt các bài báo, tweet, ảnh chụp màn hình và ghi chú. graphify là câu trả lời cho vấn đề đó — **71,5x** ít token hơn trên mỗi truy vấn so với đọc các tệp thô, liên tục giữa các phiên.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html đồ thị tương tác — mở trong bất kỳ trình duyệt nào
|
||||
├── GRAPH_REPORT.md nút thần, kết nối bất ngờ, câu hỏi được đề xuất
|
||||
├── graph.json đồ thị liên tục — có thể truy vấn sau nhiều tuần
|
||||
└── cache/ bộ nhớ đệm SHA256 — các lần chạy lại chỉ xử lý các tệp đã thay đổi
|
||||
```
|
||||
|
||||
## Cách hoạt động
|
||||
|
||||
graphify hoạt động theo ba lần duyệt. Đầu tiên, một lần duyệt AST xác định trích xuất cấu trúc từ các tệp code mà không cần LLM. Sau đó, các tệp video và âm thanh được phiên âm cục bộ bằng faster-whisper. Cuối cùng, các sub-agent Claude chạy song song trên các tài liệu, bài báo, hình ảnh và bản phiên âm. Kết quả được hợp nhất vào đồ thị NetworkX, phân cụm với Leiden và xuất dưới dạng HTML tương tác, JSON có thể truy vấn và báo cáo kiểm tra.
|
||||
|
||||
Mỗi mối quan hệ được gắn nhãn `EXTRACTED`, `INFERRED` (với điểm tin cậy) hoặc `AMBIGUOUS`.
|
||||
|
||||
## Cài đặt
|
||||
|
||||
**Yêu cầu:** Python 3.10+ và một trong: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) và các công cụ khác.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# hoặc với pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# hoặc pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Gói chính thức:** Gói PyPI có tên là `graphifyy`. Kho lưu trữ chính thức duy nhất là [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Sử dụng
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "điều gì kết nối Attention với optimizer?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Những gì bạn nhận được
|
||||
|
||||
**Nút thần** — các khái niệm có bậc cao nhất · **Kết nối bất ngờ** — được xếp hạng theo điểm · **Câu hỏi được đề xuất** · **"Tại sao"** — docstring và lý do thiết kế được trích xuất dưới dạng nút · **Benchmark token** — **71,5x** ít token hơn trên corpus hỗn hợp.
|
||||
|
||||
## Quyền riêng tư
|
||||
|
||||
Các tệp code được xử lý cục bộ qua tree-sitter AST. Video được phiên âm cục bộ với faster-whisper. Không có telemetry.
|
||||
|
||||
## Được xây dựng trên graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) là lớp doanh nghiệp trên graphify. **Dùng thử miễn phí sắp ra mắt.** [Tham gia danh sách chờ →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -1,6 +1,6 @@
|
||||
# graphify
|
||||
|
||||
[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja-JP.md) | [한국어](README.ko-KR.md)
|
||||
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
|
||||
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://pypi.org/project/graphifyy/)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**AI 程式碼助手的技能。** 在 Claude Code、Codex、OpenCode、Cursor、Gemini CLI、GitHub Copilot CLI、VS Code Copilot Chat、Aider、OpenClaw、Factory Droid、Trae、Hermes、Kiro 或 Google Antigravity 中輸入 `/graphify` — 它會讀取您的檔案、建立知識圖譜,並返回您不知道存在的結構。更快理解程式碼庫。找到架構決策背後的「為什麼」。
|
||||
|
||||
完全多模態。添加程式碼、PDF、Markdown、截圖、圖表、白板照片、其他語言的圖片或視訊和音訊檔案 — graphify 從所有內容中提取概念和關係,並將它們連接成單一圖譜。視訊使用 Whisper 在本地轉錄。透過 tree-sitter AST 支援 25 種程式語言。
|
||||
|
||||
> Andrej Karpathy 維護一個 `/raw` 資料夾,在那裡他放置論文、推文、截圖和筆記。graphify 是這個問題的答案 — 每次查詢比讀取原始檔案少 **71.5 倍** 的 token,在會話之間持久存在。
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html 互動式圖譜 — 在任何瀏覽器中開啟
|
||||
├── GRAPH_REPORT.md 神級節點、令人驚訝的連接、建議問題
|
||||
├── graph.json 持久圖譜 — 幾週後仍可查詢
|
||||
└── cache/ SHA256 快取 — 重複執行只處理已變更的檔案
|
||||
```
|
||||
|
||||
## 運作原理
|
||||
|
||||
graphify 分三個階段工作。首先,確定性 AST 遍歷在不使用 LLM 的情況下從程式碼檔案中提取結構。然後使用 faster-whisper 在本地轉錄視訊和音訊檔案。最後,Claude 子代理並行處理文件、論文、圖片和轉錄文字。結果被合併到 NetworkX 圖譜中,使用 Leiden 進行聚類,並匯出為互動式 HTML、可查詢 JSON 和審計報告。
|
||||
|
||||
每個關係都標記為 `EXTRACTED`、`INFERRED`(帶有置信度分數)或 `AMBIGUOUS`。
|
||||
|
||||
## 安裝
|
||||
|
||||
**需求:** Python 3.10+ 以及以下之一:[Claude Code](https://claude.ai/code)、[Codex](https://openai.com/codex)、[OpenCode](https://opencode.ai)、[Cursor](https://cursor.com) 等。
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# 或使用 pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# 或 pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **官方套件:** PyPI 套件名稱為 `graphifyy`。唯一的官方儲存庫是 [safishamsi/graphify](https://github.com/safishamsi/graphify)。
|
||||
|
||||
## 使用方式
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "什麼將 Attention 與 optimizer 連接起來?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## 您會得到什麼
|
||||
|
||||
**神級節點** — 度數最高的概念 · **令人驚訝的連接** — 按分數排名 · **建議問題** · **「為什麼」** — 提取為節點的文件字串和設計理由 · **Token 基準測試** — 在混合語料庫上少 **71.5 倍** 的 token。
|
||||
|
||||
## 隱私
|
||||
|
||||
程式碼檔案透過 tree-sitter AST 在本地處理。視訊使用 faster-whisper 在本地轉錄。無遙測。
|
||||
|
||||
## 基於 graphify 構建 — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) 是 graphify 之上的企業層。**免費試用即將推出。** [加入等待名單 →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
+905
-50
File diff suppressed because it is too large.
Load diff
+50
-2
@@ -1,7 +1,34 @@
|
||||
"""Graph analysis: god nodes (most connected), surprising connections (cross-community), suggested questions."""
|
||||
from __future__ import annotations
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
|
||||
# Language families — extensions sharing a runtime can legitimately call each other
|
||||
_LANG_FAMILY: dict[str, str] = {
|
||||
**{e: "python" for e in (".py", ".pyw")},
|
||||
**{e: "js" for e in (".js", ".jsx", ".mjs", ".ejs", ".ts", ".tsx", ".vue", ".svelte")},
|
||||
**{e: "go" for e in (".go",)},
|
||||
**{e: "rust" for e in (".rs",)},
|
||||
**{e: "jvm" for e in (".java", ".kt", ".kts", ".scala")},
|
||||
**{e: "c" for e in (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp")},
|
||||
**{e: "ruby" for e in (".rb",)},
|
||||
**{e: "swift" for e in (".swift",)},
|
||||
**{e: "dotnet" for e in (".cs",)},
|
||||
**{e: "php" for e in (".php",)},
|
||||
**{e: "r" for e in (".r",)},
|
||||
}
|
||||
|
||||
|
||||
def _cross_language(src_a: str, src_b: str) -> bool:
|
||||
"""Return True if two source files belong to different language families."""
|
||||
ext_a = Path(src_a).suffix.lower()
|
||||
ext_b = Path(src_b).suffix.lower()
|
||||
fam_a = _LANG_FAMILY.get(ext_a)
|
||||
fam_b = _LANG_FAMILY.get(ext_b)
|
||||
if fam_a is None or fam_b is None:
|
||||
return False
|
||||
return fam_a != fam_b
|
||||
|
||||
|
||||
def _node_community_map(communities: dict[int, list[str]]) -> dict[str, int]:
|
||||
"""Invert communities dict: node_id -> community_id."""
|
||||
@@ -51,7 +78,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
|
||||
@@ -143,7 +170,13 @@ def _surprise_score(
|
||||
|
||||
# 1. Confidence weight - uncertain connections are more noteworthy
|
||||
conf = data.get("confidence", "EXTRACTED")
|
||||
relation = data.get("relation", "")
|
||||
conf_bonus = {"AMBIGUOUS": 3, "INFERRED": 2, "EXTRACTED": 1}.get(conf, 1)
|
||||
|
||||
# Cross-language INFERRED calls are likely resolver pollution, not real surprises
|
||||
if conf == "INFERRED" and relation == "calls" and _cross_language(u_source, v_source):
|
||||
conf_bonus = 0 # downgrade: don't promote likely false positives
|
||||
|
||||
score += conf_bonus
|
||||
if conf in ("AMBIGUOUS", "INFERRED"):
|
||||
reasons.append(f"{conf.lower()} connection - not explicitly stated in source")
|
||||
@@ -218,7 +251,11 @@ def _cross_file_surprises(G: nx.Graph, communities: dict[int, list[str]], 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),
|
||||
@@ -258,6 +295,8 @@ def _cross_community_surprises(
|
||||
# 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 = []
|
||||
@@ -294,7 +333,11 @@ def _cross_community_surprises(
|
||||
# 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),
|
||||
@@ -352,7 +395,8 @@ def suggest_questions(
|
||||
|
||||
# 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, seed=42)
|
||||
# Top bridge nodes that are NOT file-level hubs
|
||||
bridges = sorted(
|
||||
[(n, s) for n, s in betweenness.items()
|
||||
@@ -392,7 +436,11 @@ 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({
|
||||
|
||||
@@ -75,7 +75,7 @@ def run_benchmark(
|
||||
|
||||
Returns dict with: corpus_tokens, avg_query_tokens, reduction_ratio, per_question
|
||||
"""
|
||||
data = json.loads(Path(graph_path).read_text())
|
||||
data = json.loads(Path(graph_path).read_text(encoding="utf-8"))
|
||||
try:
|
||||
G = json_graph.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
|
||||
@@ -21,17 +21,57 @@
|
||||
# before any graph construction happens.
|
||||
#
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
from .validate import validate_extraction
|
||||
|
||||
|
||||
def _normalize_id(s: str) -> str:
|
||||
"""Normalize an ID string the same way extract._make_id does.
|
||||
|
||||
Used to reconcile edge endpoints when the LLM generates IDs with slightly
|
||||
different punctuation or casing than the AST extractor.
|
||||
"""
|
||||
cleaned = re.sub(r"[^a-zA-Z0-9]+", "_", s)
|
||||
return cleaned.strip("_").lower()
|
||||
|
||||
|
||||
def _norm_source_file(p: str | None) -> str | None:
|
||||
"""Normalize path separators to forward slashes so Windows backslash paths
|
||||
and POSIX paths from semantic subagents resolve to the same node identity."""
|
||||
return p.replace("\\", "/") if p else p
|
||||
|
||||
|
||||
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"])
|
||||
|
||||
# Canonicalize legacy node/edge schema before validation.
|
||||
for node in extraction.get("nodes", []):
|
||||
if isinstance(node, dict) and "source" in node and "source_file" not in node:
|
||||
# Count edges that reference this node so the warning is actionable (#479)
|
||||
node_id = node.get("id", "?")
|
||||
affected_edges = sum(
|
||||
1 for e in extraction.get("edges", [])
|
||||
if e.get("source") == node_id or e.get("target") == node_id
|
||||
)
|
||||
print(
|
||||
f"[graphify] WARNING: node '{node_id}' uses field 'source' instead of "
|
||||
f"'source_file' — {affected_edges} edge(s) may be misrouted. "
|
||||
f"Rename the field to 'source_file' to silence this warning.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
node["source_file"] = node.pop("source")
|
||||
|
||||
errors = validate_extraction(extraction)
|
||||
# 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]
|
||||
@@ -39,13 +79,32 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
|
||||
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", []):
|
||||
if "source_file" in node:
|
||||
node["source_file"] = _norm_source_file(node["source_file"])
|
||||
G.add_node(node["id"], **{k: v for k, v in node.items() if k != "id"})
|
||||
node_set = set(G.nodes())
|
||||
# Normalized ID map: lets edges survive when the LLM generates IDs with
|
||||
# slightly different casing or punctuation than the AST extractor.
|
||||
# e.g. "Session_ValidateToken" maps to "session_validatetoken".
|
||||
norm_to_id: dict[str, str] = {_normalize_id(nid): nid for nid in node_set}
|
||||
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"]
|
||||
# Remap mismatched IDs via normalization before dropping the edge.
|
||||
if src not in node_set:
|
||||
src = norm_to_id.get(_normalize_id(src), src)
|
||||
if tgt not in node_set:
|
||||
tgt = norm_to_id.get(_normalize_id(tgt), tgt)
|
||||
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")}
|
||||
if "source_file" in attrs:
|
||||
attrs["source_file"] = _norm_source_file(attrs["source_file"])
|
||||
# Preserve original edge direction - undirected graphs lose it otherwise,
|
||||
# causing display functions to show edges backwards.
|
||||
attrs["_src"] = src
|
||||
@@ -76,3 +135,110 @@ def build(extractions: list[dict], *, directed: bool = False) -> nx.Graph:
|
||||
combined["input_tokens"] += ext.get("input_tokens", 0)
|
||||
combined["output_tokens"] += ext.get("output_tokens", 0)
|
||||
return build_from_json(combined, directed=directed)
|
||||
|
||||
|
||||
def _norm_label(label: str) -> str:
|
||||
"""Canonical dedup key — lowercase, alphanumeric only."""
|
||||
return re.sub(r"[^a-z0-9 ]", "", label.lower()).strip()
|
||||
|
||||
|
||||
def deduplicate_by_label(nodes: list[dict], edges: list[dict]) -> tuple[list[dict], list[dict]]:
|
||||
"""Merge nodes that share a normalised label, rewriting edge references.
|
||||
|
||||
Prefers IDs without chunk suffixes (_c\\d+) and shorter IDs when tied.
|
||||
Drops self-loops created by the merge. Called in build() automatically.
|
||||
"""
|
||||
_CHUNK_SUFFIX = re.compile(r"_c\d+$")
|
||||
canonical: dict[str, dict] = {} # norm_label -> surviving node
|
||||
remap: dict[str, str] = {} # old_id -> surviving_id
|
||||
|
||||
for node in nodes:
|
||||
key = _norm_label(node.get("label", node.get("id", "")))
|
||||
if not key:
|
||||
continue
|
||||
existing = canonical.get(key)
|
||||
if existing is None:
|
||||
canonical[key] = node
|
||||
else:
|
||||
has_suffix = bool(_CHUNK_SUFFIX.search(node["id"]))
|
||||
existing_has_suffix = bool(_CHUNK_SUFFIX.search(existing["id"]))
|
||||
if has_suffix and not existing_has_suffix:
|
||||
remap[node["id"]] = existing["id"]
|
||||
elif existing_has_suffix and not has_suffix:
|
||||
remap[existing["id"]] = node["id"]
|
||||
canonical[key] = node
|
||||
elif len(node["id"]) < len(existing["id"]):
|
||||
remap[existing["id"]] = node["id"]
|
||||
canonical[key] = node
|
||||
else:
|
||||
remap[node["id"]] = existing["id"]
|
||||
|
||||
if not remap:
|
||||
return nodes, edges
|
||||
|
||||
print(f"[graphify] Deduplicated {len(remap)} duplicate node(s) by label.", file=sys.stderr)
|
||||
deduped_nodes = list(canonical.values())
|
||||
deduped_edges = []
|
||||
for edge in edges:
|
||||
e = dict(edge)
|
||||
e["source"] = remap.get(e["source"], e["source"])
|
||||
e["target"] = remap.get(e["target"], e["target"])
|
||||
if e["source"] != e["target"]:
|
||||
deduped_edges.append(e)
|
||||
return deduped_nodes, deduped_edges
|
||||
|
||||
|
||||
def build_merge(
|
||||
new_chunks: list[dict],
|
||||
graph_path: str | Path = "graphify-out/graph.json",
|
||||
prune_sources: list[str] | None = None,
|
||||
*,
|
||||
directed: bool = False,
|
||||
) -> nx.Graph:
|
||||
"""Load existing graph.json, merge new chunks into it, and save back.
|
||||
|
||||
Never replaces — only grows (or prunes deleted-file nodes via prune_sources).
|
||||
Safe to call repeatedly: existing nodes and edges are preserved.
|
||||
"""
|
||||
from networkx.readwrite import json_graph as _jg
|
||||
|
||||
graph_path = Path(graph_path)
|
||||
if graph_path.exists():
|
||||
data = json.loads(graph_path.read_text(encoding="utf-8"))
|
||||
try:
|
||||
existing_G = _jg.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
existing_G = _jg.node_link_graph(data)
|
||||
# Reconstruct as a plain extraction dict so build() can merge it
|
||||
existing_nodes = [{"id": n, **existing_G.nodes[n]} for n in existing_G.nodes]
|
||||
existing_edges = [
|
||||
{"source": u, "target": v, **d} for u, v, d in existing_G.edges(data=True)
|
||||
]
|
||||
base = [{"nodes": existing_nodes, "edges": existing_edges}]
|
||||
else:
|
||||
base = []
|
||||
|
||||
all_chunks = base + list(new_chunks)
|
||||
G = build(all_chunks, directed=directed)
|
||||
|
||||
# Prune nodes from deleted source files
|
||||
if prune_sources:
|
||||
to_remove = [
|
||||
n for n, d in G.nodes(data=True)
|
||||
if d.get("source_file") in prune_sources
|
||||
]
|
||||
G.remove_nodes_from(to_remove)
|
||||
if to_remove:
|
||||
print(f"[graphify] Pruned {len(to_remove)} node(s) from deleted sources.", file=sys.stderr)
|
||||
|
||||
# Safety check: refuse to shrink the graph silently (#479)
|
||||
if graph_path.exists():
|
||||
existing_n = len(existing_nodes)
|
||||
new_n = G.number_of_nodes()
|
||||
if new_n < existing_n:
|
||||
raise ValueError(
|
||||
f"graphify: build_merge would shrink graph from {existing_n} → {new_n} nodes. "
|
||||
f"Pass prune_sources explicitly if you intend to remove nodes."
|
||||
)
|
||||
|
||||
return G
|
||||
+123
-36
@@ -4,8 +4,14 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
# Output directory name — override with GRAPHIFY_OUT env var for worktrees or
|
||||
# shared-output setups. Accepts a relative name ("graphify-out-feature") or an
|
||||
# absolute path ("/shared/graphify-out").
|
||||
_GRAPHIFY_OUT = os.environ.get("GRAPHIFY_OUT", "graphify-out")
|
||||
|
||||
|
||||
def _body_content(content: bytes) -> bytes:
|
||||
"""Strip YAML frontmatter from Markdown content, returning only the body."""
|
||||
@@ -17,77 +23,156 @@ def _body_content(content: bytes) -> bytes:
|
||||
return content
|
||||
|
||||
|
||||
def file_hash(path: Path) -> str:
|
||||
"""SHA256 of file contents + resolved path. Prevents cache collisions on identical content.
|
||||
def _normalize_path(path: Path) -> Path:
|
||||
"""Normalize path for consistent cache keys across Windows path spellings."""
|
||||
import sys
|
||||
if sys.platform != "win32":
|
||||
return path
|
||||
s = str(path)
|
||||
if s.startswith("\\\\?\\"):
|
||||
s = s[4:] # strip extended-length prefix \\?\
|
||||
return Path(os.path.normcase(s))
|
||||
|
||||
|
||||
def file_hash(path: Path, root: Path = Path(".")) -> str:
|
||||
"""SHA256 of file contents + path relative to root.
|
||||
|
||||
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)
|
||||
p = _normalize_path(Path(path))
|
||||
root = _normalize_path(Path(root))
|
||||
if not p.is_file():
|
||||
raise IsADirectoryError(f"file_hash requires a file, got: {p}")
|
||||
raw = p.read_bytes()
|
||||
content = _body_content(raw) if p.suffix.lower() == ".md" else raw
|
||||
h = hashlib.sha256()
|
||||
h.update(content)
|
||||
h.update(b"\x00")
|
||||
h.update(str(p.resolve()).encode())
|
||||
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-out/cache/ - creates it if needed."""
|
||||
d = Path(root) / "graphify-out" / "cache"
|
||||
def cache_dir(root: Path = Path("."), kind: str = "ast") -> Path:
|
||||
"""Returns graphify-out/cache/{kind}/ - creates it if needed.
|
||||
|
||||
kind is "ast" or "semantic". Separate subdirectories prevent semantic cache
|
||||
entries from overwriting AST cache entries for the same source_file (#582).
|
||||
"""
|
||||
_out = Path(_GRAPHIFY_OUT)
|
||||
base = _out if _out.is_absolute() else Path(root).resolve() / _out
|
||||
d = base / "cache" / kind
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def load_cached(path: Path, root: Path = Path(".")) -> dict | None:
|
||||
def load_cached(path: Path, root: Path = Path("."), kind: str = "ast") -> dict | None:
|
||||
"""Return cached extraction for this file if hash matches, else None.
|
||||
|
||||
Cache key: SHA256 of file contents.
|
||||
Cache value: stored as graphify-out/cache/{hash}.json
|
||||
Cache value: stored as graphify-out/cache/{kind}/{hash}.json
|
||||
|
||||
For kind="ast", also checks the legacy flat cache/ directory so users
|
||||
upgrading from pre-0.5.3 don't lose their existing AST cache entries.
|
||||
Returns None if no cache entry or file has changed.
|
||||
"""
|
||||
try:
|
||||
h = file_hash(path)
|
||||
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())
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
entry = cache_dir(root, kind) / f"{h}.json"
|
||||
if entry.exists():
|
||||
try:
|
||||
return json.loads(entry.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
# Migration fallback: check legacy flat cache/ dir for AST entries
|
||||
if kind == "ast":
|
||||
legacy = Path(root).resolve() / _GRAPHIFY_OUT / "cache" / f"{h}.json"
|
||||
if legacy.exists():
|
||||
try:
|
||||
return json.loads(legacy.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
|
||||
def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "ast") -> None:
|
||||
"""Save extraction result for this file.
|
||||
|
||||
Stores as graphify-out/cache/{hash}.json where hash = SHA256 of current file contents.
|
||||
Stores as graphify-out/cache/{kind}/{hash}.json where hash = SHA256 of current file contents.
|
||||
result should be a dict with 'nodes' and 'edges' lists.
|
||||
|
||||
No-ops if `path` is not a regular file. Subagent-produced semantic fragments
|
||||
occasionally carry a directory path in `source_file`; skipping them prevents
|
||||
IsADirectoryError from aborting the whole batch.
|
||||
"""
|
||||
h = file_hash(path)
|
||||
entry = cache_dir(root) / f"{h}.json"
|
||||
tmp = entry.with_suffix(".tmp")
|
||||
p = Path(path)
|
||||
if not p.is_file():
|
||||
return
|
||||
h = file_hash(p, root)
|
||||
target_dir = cache_dir(root, kind)
|
||||
entry = target_dir / f"{h}.json"
|
||||
fd, tmp_path = tempfile.mkstemp(dir=target_dir, prefix=f"{h}.", suffix=".tmp")
|
||||
try:
|
||||
tmp.write_text(json.dumps(result))
|
||||
os.replace(tmp, entry)
|
||||
os.write(fd, json.dumps(result).encode())
|
||||
os.close(fd)
|
||||
try:
|
||||
os.replace(tmp_path, entry)
|
||||
except PermissionError:
|
||||
# Windows: os.replace can fail with WinError 5 if the target is
|
||||
# briefly locked. Fall back to copy-then-delete.
|
||||
import shutil
|
||||
shutil.copy2(tmp_path, entry)
|
||||
os.unlink(tmp_path)
|
||||
except Exception:
|
||||
tmp.unlink(missing_ok=True)
|
||||
try:
|
||||
os.close(fd)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
os.unlink(tmp_path)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def cached_files(root: Path = Path(".")) -> set[str]:
|
||||
"""Return set of file paths that have a valid cache entry (hash still matches)."""
|
||||
d = cache_dir(root)
|
||||
return {p.stem for p in d.glob("*.json")}
|
||||
"""Return set of file hashes that have a valid cache entry (any kind)."""
|
||||
base = Path(root).resolve() / _GRAPHIFY_OUT / "cache"
|
||||
hashes: set[str] = set()
|
||||
# Legacy flat entries
|
||||
if base.is_dir():
|
||||
hashes.update(p.stem for p in base.glob("*.json"))
|
||||
# Namespaced entries
|
||||
for kind in ("ast", "semantic"):
|
||||
d = base / kind
|
||||
if d.is_dir():
|
||||
hashes.update(p.stem for p in d.glob("*.json"))
|
||||
return hashes
|
||||
|
||||
|
||||
def clear_cache(root: Path = Path(".")) -> None:
|
||||
"""Delete all graphify-out/cache/*.json files."""
|
||||
d = cache_dir(root)
|
||||
for f in d.glob("*.json"):
|
||||
f.unlink()
|
||||
"""Delete all cache entries (ast/, semantic/, and legacy flat entries)."""
|
||||
base = Path(root).resolve() / _GRAPHIFY_OUT / "cache"
|
||||
# Legacy flat entries
|
||||
if base.is_dir():
|
||||
for f in base.glob("*.json"):
|
||||
f.unlink()
|
||||
# Namespaced entries
|
||||
for kind in ("ast", "semantic"):
|
||||
d = base / kind
|
||||
if d.is_dir():
|
||||
for f in d.glob("*.json"):
|
||||
f.unlink()
|
||||
|
||||
|
||||
def check_semantic_cache(
|
||||
@@ -105,7 +190,7 @@ def check_semantic_cache(
|
||||
uncached: list[str] = []
|
||||
|
||||
for fpath in files:
|
||||
result = load_cached(Path(fpath), root)
|
||||
result = load_cached(Path(fpath), root, kind="semantic")
|
||||
if result is not None:
|
||||
cached_nodes.extend(result.get("nodes", []))
|
||||
cached_edges.extend(result.get("edges", []))
|
||||
@@ -124,7 +209,9 @@ def save_semantic_cache(
|
||||
) -> int:
|
||||
"""Save semantic extraction results to cache, keyed by source_file.
|
||||
|
||||
Groups nodes and edges by source_file, then saves one cache entry per file.
|
||||
Groups nodes and edges by source_file, then saves one cache entry per file
|
||||
under cache/semantic/ (separate from AST entries in cache/ast/) to prevent
|
||||
hash-key collisions (#582).
|
||||
Returns the number of files cached.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
@@ -148,7 +235,7 @@ def save_semantic_cache(
|
||||
p = Path(fpath)
|
||||
if not p.is_absolute():
|
||||
p = Path(root) / p
|
||||
if p.exists():
|
||||
save_cached(p, result, root)
|
||||
if p.is_file():
|
||||
save_cached(p, result, root, kind="semantic")
|
||||
saved += 1
|
||||
return saved
|
||||
@@ -54,6 +54,8 @@ def _partition(G: nx.Graph) -> dict[str, int]:
|
||||
|
||||
_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
|
||||
_COHESION_SPLIT_THRESHOLD = 0.05 # re-split communities with cohesion below this
|
||||
_COHESION_SPLIT_MIN_SIZE = 50 # only cohesion-split if community has at least this many nodes
|
||||
|
||||
|
||||
def cluster(G: nx.Graph) -> dict[int, list[str]]:
|
||||
@@ -99,6 +101,17 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
|
||||
else:
|
||||
final_communities.append(nodes)
|
||||
|
||||
# Second pass: re-split low-cohesion communities caused by doc-hub nodes
|
||||
# that bridge otherwise-unrelated subsystems (e.g. CLAUDE.md connected to everything).
|
||||
second_pass: list[list[str]] = []
|
||||
for nodes in final_communities:
|
||||
if len(nodes) >= _COHESION_SPLIT_MIN_SIZE and cohesion_score(G, nodes) < _COHESION_SPLIT_THRESHOLD:
|
||||
splits = _split_community(G, nodes)
|
||||
second_pass.extend(splits if len(splits) > 1 else [nodes])
|
||||
else:
|
||||
second_pass.append(nodes)
|
||||
final_communities = second_pass
|
||||
|
||||
# Re-index by size descending for deterministic ordering
|
||||
final_communities.sort(key=len, reverse=True)
|
||||
return {i: sorted(nodes) for i, nodes in enumerate(final_communities)}
|
||||
|
||||
+406
-63
@@ -18,8 +18,8 @@ class FileType(str, Enum):
|
||||
|
||||
_MANIFEST_PATH = "graphify-out/manifest.json"
|
||||
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.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'}
|
||||
DOC_EXTENSIONS = {'.md', '.txt', '.rst'}
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.ejs', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.dart', '.v', '.sv', '.sql', '.r'}
|
||||
DOC_EXTENSIONS = {'.md', '.mdx', '.txt', '.rst', '.html', '.yaml', '.yml'}
|
||||
PAPER_EXTENSIONS = {'.pdf'}
|
||||
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
|
||||
OFFICE_EXTENSIONS = {'.docx', '.xlsx'}
|
||||
@@ -61,15 +61,14 @@ _PAPER_SIGNAL_THRESHOLD = 3 # need at least this many signals to call it a pape
|
||||
def _is_sensitive(path: Path) -> bool:
|
||||
"""Return True if this file likely contains secrets and should be skipped."""
|
||||
name = path.name
|
||||
full = str(path)
|
||||
return any(p.search(name) or p.search(full) for p in _SENSITIVE_PATTERNS)
|
||||
return any(p.search(name) for p in _SENSITIVE_PATTERNS)
|
||||
|
||||
|
||||
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:
|
||||
@@ -79,8 +78,42 @@ def _looks_like_paper(path: Path) -> bool:
|
||||
_ASSET_DIR_MARKERS = {".imageset", ".xcassets", ".appiconset", ".colorset", ".launchimage"}
|
||||
|
||||
|
||||
_SHEBANG_CODE_INTERPRETERS = {
|
||||
"python", "python3", "python2",
|
||||
"ruby", "perl", "node", "nodejs",
|
||||
"bash", "sh", "dash", "zsh", "fish", "ksh", "tcsh",
|
||||
"lua", "php", "julia", "Rscript",
|
||||
}
|
||||
|
||||
|
||||
def _shebang_file_type(path: Path) -> FileType | None:
|
||||
"""Peek at the first line of an extensionless file for a shebang."""
|
||||
try:
|
||||
with path.open("rb") as f:
|
||||
first = f.read(128)
|
||||
if not first.startswith(b"#!"):
|
||||
return None
|
||||
line = first.split(b"\n")[0].decode(errors="replace")
|
||||
parts = line[2:].strip().split()
|
||||
if not parts:
|
||||
return None
|
||||
interp = parts[0].split("/")[-1] # /usr/bin/env → env
|
||||
if interp == "env" and len(parts) > 1:
|
||||
interp = parts[1].split("/")[-1]
|
||||
if interp in _SHEBANG_CODE_INTERPRETERS:
|
||||
return FileType.CODE
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def classify_file(path: Path) -> FileType | None:
|
||||
# Compound extensions must be checked before simple suffix lookup
|
||||
if path.name.lower().endswith(".blade.php"):
|
||||
return FileType.CODE
|
||||
ext = path.suffix.lower()
|
||||
if not ext:
|
||||
return _shebang_file_type(path)
|
||||
if ext in CODE_EXTENSIONS:
|
||||
return FileType.CODE
|
||||
if ext in PAPER_EXTENSIONS:
|
||||
@@ -167,7 +200,6 @@ def xlsx_to_markdown(path: Path) -> str:
|
||||
ws = wb[sheet_name]
|
||||
rows = []
|
||||
for row in ws.iter_rows(values_only=True):
|
||||
# Skip entirely empty rows
|
||||
if all(cell is None for cell in row):
|
||||
continue
|
||||
rows.append([str(cell) if cell is not None else "" for cell in row])
|
||||
@@ -188,6 +220,91 @@ def xlsx_to_markdown(path: Path) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def xlsx_extract_structure(path: Path) -> dict:
|
||||
"""Extract structural nodes (sheets, named tables, column headers) from an .xlsx file.
|
||||
|
||||
Returns a nodes/edges dict compatible with the graphify extract pipeline.
|
||||
Used in addition to xlsx_to_markdown so Claude sees both structure and content.
|
||||
"""
|
||||
def _nid(*parts: str) -> str:
|
||||
return re.sub(r"[^a-z0-9_]", "_", "_".join(p.lower() for p in parts).strip("_"))
|
||||
|
||||
try:
|
||||
import openpyxl
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": []}
|
||||
|
||||
try:
|
||||
wb = openpyxl.load_workbook(str(path), read_only=False, data_only=True)
|
||||
except Exception:
|
||||
return {"nodes": [], "edges": []}
|
||||
|
||||
stem = _re.sub(r"[^a-z0-9]", "_", path.stem.lower())
|
||||
str_path = str(path)
|
||||
file_nid = _nid(str_path)
|
||||
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "document",
|
||||
"source_file": str_path, "source_location": None}]
|
||||
edges: list[dict] = []
|
||||
seen: set[str] = {file_nid}
|
||||
|
||||
def _add(nid: str, label: str) -> None:
|
||||
if nid not in seen:
|
||||
seen.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "document",
|
||||
"source_file": str_path, "source_location": None})
|
||||
|
||||
def _edge(src: str, tgt: str, relation: str) -> None:
|
||||
edges.append({"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": "EXTRACTED", "source_file": str_path,
|
||||
"source_location": None, "weight": 1.0})
|
||||
|
||||
for sheet_name in wb.sheetnames:
|
||||
ws = wb[sheet_name]
|
||||
sheet_nid = _nid(stem, sheet_name)
|
||||
_add(sheet_nid, f"{sheet_name} (sheet)")
|
||||
_edge(file_nid, sheet_nid, "contains")
|
||||
|
||||
# Named Excel Tables (ListObjects)
|
||||
if hasattr(ws, "tables"):
|
||||
for tbl in ws.tables.values():
|
||||
tbl_nid = _nid(stem, sheet_name, tbl.name)
|
||||
_add(tbl_nid, tbl.name)
|
||||
_edge(sheet_nid, tbl_nid, "contains")
|
||||
# Column headers from table header row
|
||||
ref = tbl.ref # e.g. "A1:D10"
|
||||
if ref:
|
||||
try:
|
||||
from openpyxl.utils import range_boundaries
|
||||
min_col, min_row, max_col, _ = range_boundaries(ref)
|
||||
header_row = list(ws.iter_rows(min_row=min_row, max_row=min_row,
|
||||
min_col=min_col, max_col=max_col,
|
||||
values_only=True))
|
||||
if header_row:
|
||||
for col_name in header_row[0]:
|
||||
if col_name:
|
||||
col_nid = _nid(stem, tbl.name, str(col_name))
|
||||
_add(col_nid, str(col_name))
|
||||
_edge(tbl_nid, col_nid, "contains")
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# Fallback: first non-empty row as column headers
|
||||
for row in ws.iter_rows(max_row=1, values_only=True):
|
||||
for cell in row:
|
||||
if cell:
|
||||
col_nid = _nid(stem, sheet_name, str(cell))
|
||||
_add(col_nid, str(cell))
|
||||
_edge(sheet_nid, col_nid, "contains")
|
||||
break
|
||||
|
||||
try:
|
||||
wb.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
|
||||
|
||||
def convert_office_file(path: Path, out_dir: Path) -> Path | None:
|
||||
"""Convert a .docx or .xlsx to a markdown sidecar in out_dir.
|
||||
|
||||
@@ -226,7 +343,7 @@ def count_words(path: Path) -> int:
|
||||
return len(docx_to_markdown(path).split())
|
||||
if ext == ".xlsx":
|
||||
return len(xlsx_to_markdown(path).split())
|
||||
return len(path.read_text(errors="ignore").split())
|
||||
return len(path.read_text(encoding="utf-8", errors="ignore").split())
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
@@ -239,6 +356,14 @@ _SKIP_DIRS = {
|
||||
"site-packages", "lib64",
|
||||
".pytest_cache", ".mypy_cache", ".ruff_cache",
|
||||
".tox", ".eggs", "*.egg-info",
|
||||
"graphify-out", # never treat own output as source input (#524)
|
||||
}
|
||||
|
||||
# Large generated files that are never useful to extract
|
||||
_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:
|
||||
@@ -253,70 +378,248 @@ def _is_noise_dir(part: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _load_graphifyignore(root: Path) -> list[str]:
|
||||
"""Read .graphifyignore from root **and ancestor directories**, returning patterns.
|
||||
_VCS_MARKERS = (".git", ".hg", ".svn", "_darcs", ".fossil")
|
||||
|
||||
Walks upward from *root* towards the filesystem root, collecting patterns
|
||||
from every ``.graphifyignore`` encountered (like ``.gitignore`` discovery).
|
||||
The search stops at the filesystem root or at a ``.git`` directory boundary
|
||||
so it doesn't leak outside the repository.
|
||||
|
||||
Lines starting with # are comments. Blank lines are ignored.
|
||||
Patterns follow gitignore semantics: glob matched against the path
|
||||
relative to root. A leading slash anchors to root. A trailing slash
|
||||
matches directories only (we match both dir and file for simplicity).
|
||||
def _parse_gitignore_line(raw: str) -> str:
|
||||
"""Parse one raw line from a .graphifyignore file per gitignore spec.
|
||||
|
||||
- Strip newline chars
|
||||
- Strip inline comments (whitespace + # suffix), but only when # is
|
||||
preceded by whitespace — so path#with#hash.py is preserved
|
||||
- Unescape \\# to literal #
|
||||
- Remove trailing spaces unless escaped with backslash
|
||||
- Strip leading whitespace
|
||||
- Return empty string for blank lines and full-line comments
|
||||
"""
|
||||
patterns: list[str] = []
|
||||
current = root.resolve()
|
||||
line = raw.rstrip("\n\r")
|
||||
line = line.lstrip()
|
||||
if not line or line.startswith("#"):
|
||||
return ""
|
||||
# Strip inline comments: require whitespace before # (gitignore extension)
|
||||
line = re.sub(r"\s+#+[^\\].*$", "", line)
|
||||
# Unescape \# → literal #
|
||||
line = line.replace("\\#", "#")
|
||||
# Remove unescaped trailing spaces (per gitignore spec)
|
||||
line = re.sub(r"(?<!\\) +$", "", line)
|
||||
return line
|
||||
|
||||
|
||||
def _find_vcs_root(start: Path) -> Path | None:
|
||||
"""Walk upward from start; return the first directory containing a VCS marker."""
|
||||
current = start.resolve()
|
||||
home = Path.home()
|
||||
while True:
|
||||
ignore_file = current / ".graphifyignore"
|
||||
if ignore_file.exists():
|
||||
for line in ignore_file.read_text(errors="ignore").splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#"):
|
||||
patterns.append(line)
|
||||
# Stop climbing once we've processed the git repo root
|
||||
if (current / ".git").exists():
|
||||
break
|
||||
if any((current / m).exists() for m in _VCS_MARKERS):
|
||||
return current
|
||||
parent = current.parent
|
||||
if parent == current:
|
||||
break # filesystem root
|
||||
if parent == current or current == home:
|
||||
return None
|
||||
current = parent
|
||||
|
||||
|
||||
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
"""Read .graphifyignore files and return (anchor_dir, pattern) pairs.
|
||||
|
||||
Patterns are returned outer-first so that inner (closer) rules are
|
||||
appended last and win via last-match-wins semantics — matching gitignore
|
||||
behavior exactly.
|
||||
|
||||
Walk ceiling: the nearest VCS root if inside a repo, otherwise the scan
|
||||
root itself (hermetic — no leakage across unrelated sibling projects).
|
||||
"""
|
||||
root = root.resolve()
|
||||
ceiling = _find_vcs_root(root) or root
|
||||
|
||||
# Collect ancestor dirs from ceiling down to root (outer → inner)
|
||||
dirs: list[Path] = []
|
||||
current = root
|
||||
while True:
|
||||
dirs.append(current)
|
||||
if current == ceiling:
|
||||
break
|
||||
current = current.parent
|
||||
dirs.reverse() # ceiling first, scan root last
|
||||
|
||||
patterns: list[tuple[Path, str]] = []
|
||||
for d in dirs:
|
||||
ignore_file = d / ".graphifyignore"
|
||||
if ignore_file.exists():
|
||||
for raw in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||
line = _parse_gitignore_line(raw)
|
||||
if line:
|
||||
patterns.append((d, line))
|
||||
return patterns
|
||||
|
||||
|
||||
def _is_ignored(path: Path, root: Path, patterns: list[str]) -> bool:
|
||||
"""Return True if path matches any .graphifyignore pattern."""
|
||||
def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if the path should be ignored per .graphifyignore patterns.
|
||||
|
||||
Uses gitignore last-match-wins semantics: all patterns are evaluated in
|
||||
order; the final matching pattern determines the result. Negation patterns
|
||||
(starting with !) un-ignore a previously ignored path.
|
||||
"""
|
||||
if not patterns:
|
||||
return False
|
||||
try:
|
||||
rel = str(path.relative_to(root))
|
||||
except ValueError:
|
||||
return False
|
||||
rel = rel.replace(os.sep, "/")
|
||||
parts = rel.split("/")
|
||||
for pattern in patterns:
|
||||
# Normalize: strip leading/trailing slashes for matching purposes
|
||||
p = pattern.strip("/")
|
||||
if not p:
|
||||
continue
|
||||
# Match against full relative path
|
||||
|
||||
def _matches(rel: str, p: str) -> bool:
|
||||
parts = rel.split("/")
|
||||
if fnmatch.fnmatch(rel, p):
|
||||
return True
|
||||
# Match against filename alone
|
||||
if fnmatch.fnmatch(path.name, p):
|
||||
return True
|
||||
# Match against any path segment or prefix
|
||||
# e.g. "vendor" or "vendor/" should match "vendor/lib.py"
|
||||
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
|
||||
|
||||
result = False
|
||||
for anchor, pattern in patterns:
|
||||
negated = pattern.startswith("!")
|
||||
raw = pattern[1:] if negated else pattern
|
||||
anchored = raw.startswith("/")
|
||||
p = raw.strip("/")
|
||||
if not p:
|
||||
continue
|
||||
|
||||
matched = False
|
||||
if anchored:
|
||||
try:
|
||||
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
|
||||
matched = _matches(rel_anchor, p)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
rel = str(path.relative_to(root)).replace(os.sep, "/")
|
||||
matched = _matches(rel, p)
|
||||
except ValueError:
|
||||
pass
|
||||
if not matched and anchor != root:
|
||||
try:
|
||||
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
|
||||
matched = _matches(rel_anchor, p)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
if matched:
|
||||
result = not negated # last match wins; ! flips to un-ignore
|
||||
return result
|
||||
|
||||
|
||||
def _load_graphifyinclude(root: Path) -> list[tuple[Path, str]]:
|
||||
"""Read .graphifyinclude allowlist patterns from root and ancestors.
|
||||
|
||||
Include patterns opt matching hidden files/dirs into traversal. Sensitive
|
||||
files and hard-skipped noise directories are still excluded later.
|
||||
Uses the same VCS-root ceiling logic as _load_graphifyignore.
|
||||
"""
|
||||
root = root.resolve()
|
||||
ceiling = _find_vcs_root(root) or root
|
||||
|
||||
dirs: list[Path] = []
|
||||
current = root
|
||||
while True:
|
||||
dirs.append(current)
|
||||
if current == ceiling:
|
||||
break
|
||||
current = current.parent
|
||||
dirs.reverse()
|
||||
|
||||
patterns: list[tuple[Path, str]] = []
|
||||
for d in dirs:
|
||||
include_file = d / ".graphifyinclude"
|
||||
if include_file.exists():
|
||||
for raw in include_file.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||
line = _parse_gitignore_line(raw)
|
||||
if line:
|
||||
patterns.append((d, line))
|
||||
return patterns
|
||||
|
||||
|
||||
def _is_included(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if path matches any .graphifyinclude allowlist 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:
|
||||
anchored = pattern.startswith("/")
|
||||
p = pattern.strip("/")
|
||||
if not p:
|
||||
continue
|
||||
if anchored:
|
||||
try:
|
||||
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
|
||||
if _matches(rel_anchor, p):
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
rel = str(path.relative_to(root)).replace(os.sep, "/")
|
||||
if _matches(rel, p):
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
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 _could_contain_included_path(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if a directory may contain files matched by .graphifyinclude."""
|
||||
if not patterns:
|
||||
return False
|
||||
|
||||
rels: list[str] = []
|
||||
try:
|
||||
rels.append(str(path.relative_to(root)).replace(os.sep, "/"))
|
||||
except ValueError:
|
||||
pass
|
||||
for anchor, _ in patterns:
|
||||
if anchor != root:
|
||||
try:
|
||||
rels.append(str(path.relative_to(anchor)).replace(os.sep, "/"))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
for rel in rels:
|
||||
rel = rel.strip("/")
|
||||
if not rel:
|
||||
return True
|
||||
for _, pattern in patterns:
|
||||
p = pattern.strip("/")
|
||||
if not p:
|
||||
continue
|
||||
if p == rel or p.startswith(rel + "/"):
|
||||
return True
|
||||
if fnmatch.fnmatch(rel, p):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
root = root.resolve()
|
||||
files: dict[FileType, list[str]] = {
|
||||
FileType.CODE: [],
|
||||
FileType.DOCUMENT: [],
|
||||
@@ -328,6 +631,7 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
|
||||
skipped_sensitive: list[str] = []
|
||||
ignore_patterns = _load_graphifyignore(root)
|
||||
include_patterns = _load_graphifyinclude(root)
|
||||
|
||||
# Always include graphify-out/memory/ - query results filed back into the graph
|
||||
memory_dir = root / "graphify-out" / "memory"
|
||||
@@ -349,14 +653,21 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
dirnames.clear()
|
||||
continue
|
||||
if not in_memory_tree:
|
||||
# Prune noise dirs in-place so os.walk never descends into them
|
||||
# Prune noise dirs in-place so os.walk never descends into them.
|
||||
# Hidden dirs are allowed through if they could contain an
|
||||
# explicitly included path (.graphifyinclude allowlist).
|
||||
# When negation patterns (!) exist, skip directory-level ignore
|
||||
# pruning so negated files inside can still be reached.
|
||||
has_negation = any(p.startswith("!") for _, p in ignore_patterns)
|
||||
dirnames[:] = [
|
||||
d for d in dirnames
|
||||
if not d.startswith(".")
|
||||
if (not d.startswith(".") or _could_contain_included_path(dp / d, root, include_patterns))
|
||||
and not _is_noise_dir(d)
|
||||
and not _is_ignored(dp / d, root, ignore_patterns)
|
||||
and (has_negation or 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)
|
||||
@@ -369,8 +680,9 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
in_memory = memory_dir.exists() and str(p).startswith(str(memory_dir))
|
||||
if not in_memory:
|
||||
# Hidden files are already excluded via dir pruning above,
|
||||
# but catch hidden files at the root level
|
||||
if p.name.startswith("."):
|
||||
# but catch hidden files at the root level. A .graphifyinclude
|
||||
# entry can opt a specific hidden file back in.
|
||||
if p.name.startswith(".") and not _is_included(p, root, include_patterns):
|
||||
continue
|
||||
# Skip files inside our own converted/ dir (avoid re-processing sidecars)
|
||||
if str(p).startswith(str(converted_dir)):
|
||||
@@ -424,32 +736,49 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict[str, float]:
|
||||
"""Load the file modification time manifest from a previous run."""
|
||||
def _md5_file(path: Path) -> str:
|
||||
"""MD5 of file contents streamed in 64KB chunks — for change detection only."""
|
||||
import hashlib as _hl
|
||||
h = _hl.md5(usedforsecurity=False)
|
||||
try:
|
||||
return json.loads(Path(manifest_path).read_text())
|
||||
with path.open("rb") as f:
|
||||
for chunk in iter(lambda: f.read(65536), b""):
|
||||
h.update(chunk)
|
||||
except OSError:
|
||||
return ""
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict:
|
||||
"""Load the manifest from a previous run. Returns {} on any error."""
|
||||
try:
|
||||
return json.loads(Path(manifest_path).read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def save_manifest(files: dict[str, list[str]], manifest_path: str = _MANIFEST_PATH) -> None:
|
||||
"""Save current file mtimes so the next --update run can diff against them."""
|
||||
manifest: dict[str, float] = {}
|
||||
"""Save current file mtimes + content hashes for change detection on --update."""
|
||||
manifest: dict[str, dict] = {}
|
||||
for file_list in files.values():
|
||||
for f in file_list:
|
||||
try:
|
||||
manifest[f] = Path(f).stat().st_mtime
|
||||
p = Path(f)
|
||||
manifest[f] = {"mtime": p.stat().st_mtime, "hash": _md5_file(p)}
|
||||
except OSError:
|
||||
pass # file deleted between detect() and manifest write - skip it
|
||||
Path(manifest_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
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:
|
||||
"""Like detect(), but returns only new or modified files since the last run.
|
||||
|
||||
Compares current file mtimes against the stored manifest.
|
||||
Use for --update mode: re-extract only what changed, merge into existing graph.
|
||||
Fast path: mtime unchanged → unchanged (free, no hash).
|
||||
Slow path: mtime bumped → compare MD5. Same hash = sync tool touched mtime,
|
||||
treat as unchanged. Different hash = actually changed, re-extract.
|
||||
|
||||
Backwards compatible with legacy manifests storing plain float mtime values.
|
||||
"""
|
||||
full = detect(root)
|
||||
manifest = load_manifest(manifest_path)
|
||||
@@ -467,12 +796,26 @@ def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
|
||||
|
||||
for ftype, file_list in full["files"].items():
|
||||
for f in file_list:
|
||||
stored_mtime = manifest.get(f)
|
||||
stored = manifest.get(f)
|
||||
try:
|
||||
current_mtime = Path(f).stat().st_mtime
|
||||
except Exception:
|
||||
current_mtime = 0
|
||||
if stored_mtime is None or current_mtime > stored_mtime:
|
||||
|
||||
# Legacy manifest: plain float value
|
||||
if isinstance(stored, (int, float)):
|
||||
changed = stored is None or current_mtime > stored
|
||||
elif isinstance(stored, dict):
|
||||
stored_mtime = stored.get("mtime")
|
||||
if stored_mtime is None or current_mtime != stored_mtime:
|
||||
# mtime bumped — verify with content hash before re-extracting
|
||||
changed = _md5_file(Path(f)) != stored.get("hash", "")
|
||||
else:
|
||||
changed = False
|
||||
else:
|
||||
changed = True # unknown format, re-extract to be safe
|
||||
|
||||
if changed:
|
||||
new_files[ftype].append(f)
|
||||
else:
|
||||
unchanged_files[ftype].append(f)
|
||||
|
||||
+184
-51
@@ -11,6 +11,12 @@ 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",
|
||||
"#EDC948", "#B07AA1", "#FF9DA7", "#9C755F", "#BAB0AC",
|
||||
@@ -19,6 +25,22 @@ COMMUNITY_COLORS = [
|
||||
MAX_NODES_FOR_VIZ = 5_000
|
||||
|
||||
|
||||
def _viz_node_limit() -> int:
|
||||
"""Return the effective viz node limit, honoring GRAPHIFY_VIZ_NODE_LIMIT env var.
|
||||
|
||||
Falls back to MAX_NODES_FOR_VIZ when the env var is unset, empty, or non-integer.
|
||||
Set to 0 to disable HTML viz unconditionally (useful for CI runners).
|
||||
"""
|
||||
import os
|
||||
raw = os.environ.get("GRAPHIFY_VIZ_NODE_LIMIT")
|
||||
if raw is None or not raw.strip():
|
||||
return MAX_NODES_FOR_VIZ
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError:
|
||||
return MAX_NODES_FOR_VIZ
|
||||
|
||||
|
||||
def _html_styles() -> str:
|
||||
return """<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
@@ -49,6 +71,14 @@ def _html_styles() -> str:
|
||||
.legend-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.legend-count { color: #666; font-size: 11px; }
|
||||
#stats { padding: 10px 14px; border-top: 1px solid #2a2a4e; font-size: 11px; color: #555; }
|
||||
#legend-controls { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; padding: 4px 0; }
|
||||
#legend-controls label { display: flex; align-items: center; gap: 6px; cursor: pointer; font-size: 12px; color: #aaa; user-select: none; }
|
||||
#legend-controls label:hover { color: #e0e0e0; }
|
||||
.legend-cb, #select-all-cb { appearance: none; -webkit-appearance: none; width: 14px; height: 14px; border: 1.5px solid #3a3a5e; border-radius: 3px; background: #0f0f1a; cursor: pointer; position: relative; flex-shrink: 0; }
|
||||
.legend-cb:checked, #select-all-cb:checked { background: #4E79A7; border-color: #4E79A7; }
|
||||
.legend-cb:checked::after, #select-all-cb:checked::after { content: ''; position: absolute; left: 3.5px; top: 1px; width: 4px; height: 7px; border: solid #fff; border-width: 0 2px 2px 0; transform: rotate(45deg); }
|
||||
#select-all-cb:indeterminate { background: #4E79A7; border-color: #4E79A7; }
|
||||
#select-all-cb:indeterminate::after { content: ''; position: absolute; left: 2px; top: 5px; width: 8px; height: 2px; background: #fff; border: none; transform: none; }
|
||||
</style>"""
|
||||
|
||||
|
||||
@@ -56,32 +86,24 @@ def _hyperedge_script(hyperedges_json: str) -> str:
|
||||
return f"""<script>
|
||||
// Render hyperedges as shaded regions
|
||||
const hyperedges = {hyperedges_json};
|
||||
function drawHyperedges() {{
|
||||
const canvas = network.canvas.frame.canvas;
|
||||
const ctx = canvas.getContext('2d');
|
||||
// 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;
|
||||
// Draw convex hull as filled polygon
|
||||
ctx.save();
|
||||
ctx.globalAlpha = 0.12;
|
||||
ctx.fillStyle = '#6366f1';
|
||||
ctx.strokeStyle = '#6366f1';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
const scale = network.getScale();
|
||||
const offset = network.getViewPosition();
|
||||
const toCanvas = (p) => ({{
|
||||
x: (p.x - offset.x) * scale + canvas.width / 2,
|
||||
y: (p.y - offset.y) * scale + canvas.height / 2
|
||||
}});
|
||||
const pts = positions.map(toCanvas);
|
||||
// Expand hull slightly
|
||||
const cx = pts.reduce((s, p) => s + p.x, 0) / pts.length;
|
||||
const cy = pts.reduce((s, p) => s + p.y, 0) / pts.length;
|
||||
const expanded = pts.map(p => ({{
|
||||
// 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
|
||||
}}));
|
||||
@@ -99,8 +121,7 @@ function drawHyperedges() {{
|
||||
ctx.fillText(h.label, cx, cy - 5);
|
||||
ctx.restore();
|
||||
}});
|
||||
}}
|
||||
network.on('afterDrawing', drawHyperedges);
|
||||
}});
|
||||
</script>"""
|
||||
|
||||
|
||||
@@ -243,15 +264,42 @@ document.addEventListener('click', e => {{
|
||||
}});
|
||||
|
||||
const hiddenCommunities = new Set();
|
||||
|
||||
const selectAllCb = document.getElementById('select-all-cb');
|
||||
|
||||
function updateSelectAllState() {{
|
||||
const total = LEGEND.length;
|
||||
const hidden = hiddenCommunities.size;
|
||||
selectAllCb.checked = hidden === 0;
|
||||
selectAllCb.indeterminate = hidden > 0 && hidden < total;
|
||||
}}
|
||||
|
||||
function toggleAllCommunities(hide) {{
|
||||
document.querySelectorAll('.legend-item').forEach(item => {{
|
||||
hide ? item.classList.add('dimmed') : item.classList.remove('dimmed');
|
||||
}});
|
||||
document.querySelectorAll('.legend-cb').forEach(cb => {{
|
||||
cb.checked = !hide;
|
||||
}});
|
||||
LEGEND.forEach(c => {{
|
||||
if (hide) hiddenCommunities.add(c.cid); else hiddenCommunities.delete(c.cid);
|
||||
}});
|
||||
const updates = RAW_NODES.map(n => ({{ id: n.id, hidden: hide }}));
|
||||
nodesDS.update(updates);
|
||||
updateSelectAllState();
|
||||
}}
|
||||
|
||||
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)) {{
|
||||
const cb = document.createElement('input');
|
||||
cb.type = 'checkbox';
|
||||
cb.className = 'legend-cb';
|
||||
cb.checked = true;
|
||||
cb.addEventListener('change', (e) => {{
|
||||
e.stopPropagation();
|
||||
if (cb.checked) {{
|
||||
hiddenCommunities.delete(c.cid);
|
||||
item.classList.remove('dimmed');
|
||||
}} else {{
|
||||
@@ -260,8 +308,18 @@ LEGEND.forEach(c => {{
|
||||
}}
|
||||
const updates = RAW_NODES
|
||||
.filter(n => n.community === c.cid)
|
||||
.map(n => ({{ id: n.id, hidden: hiddenCommunities.has(c.cid) }}));
|
||||
.map(n => ({{ id: n.id, hidden: !cb.checked }}));
|
||||
nodesDS.update(updates);
|
||||
updateSelectAllState();
|
||||
}});
|
||||
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.prepend(cb);
|
||||
item.onclick = (e) => {{
|
||||
if (e.target === cb) return;
|
||||
cb.checked = !cb.checked;
|
||||
cb.dispatchEvent(new Event('change'));
|
||||
}};
|
||||
legendEl.appendChild(item);
|
||||
}});
|
||||
@@ -282,7 +340,27 @@ def attach_hyperedges(G: nx.Graph, hyperedges: list) -> None:
|
||||
G.graph["hyperedges"] = existing
|
||||
|
||||
|
||||
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) -> None:
|
||||
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *, force: bool = False) -> bool:
|
||||
# Safety check: refuse to silently shrink an existing graph (#479)
|
||||
existing_path = Path(output_path)
|
||||
if not force and existing_path.exists():
|
||||
try:
|
||||
existing_data = json.loads(existing_path.read_text(encoding="utf-8"))
|
||||
existing_n = len(existing_data.get("nodes", []))
|
||||
new_n = G.number_of_nodes()
|
||||
if new_n < existing_n:
|
||||
import sys as _sys
|
||||
print(
|
||||
f"[graphify] WARNING: new graph has {new_n} nodes but existing "
|
||||
f"graph.json has {existing_n}. Refusing to overwrite — you may be "
|
||||
f"missing chunk files from a previous session. "
|
||||
f"Pass force=True to override.",
|
||||
file=_sys.stderr,
|
||||
)
|
||||
return False
|
||||
except Exception:
|
||||
pass # unreadable existing file — proceed with write
|
||||
|
||||
node_community = _node_community_map(communities)
|
||||
try:
|
||||
data = json_graph.node_link_data(G, edges="links")
|
||||
@@ -290,13 +368,39 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) ->
|
||||
data = json_graph.node_link_data(G)
|
||||
for node in data["nodes"]:
|
||||
node["community"] = node_community.get(node["id"])
|
||||
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)
|
||||
# Restore original edge direction. Undirected NetworkX storage may
|
||||
# canonicalize endpoint order, flipping `calls` and other directional
|
||||
# edges in graph.json. The build path stashes the true endpoints in
|
||||
# _src/_tgt for exactly this purpose (#563).
|
||||
true_src = link.pop("_src", None)
|
||||
true_tgt = link.pop("_tgt", None)
|
||||
if true_src is not None and true_tgt is not None:
|
||||
link["source"] = true_src
|
||||
link["target"] = true_tgt
|
||||
data["hyperedges"] = getattr(G, "graph", {}).get("hyperedges", [])
|
||||
with open(output_path, "w") as f:
|
||||
with open(output_path, "w", encoding="utf-8") as f: # nosec
|
||||
json.dump(data, f, indent=2)
|
||||
return True
|
||||
|
||||
|
||||
def prune_dangling_edges(graph_data: dict) -> tuple[dict, int]:
|
||||
"""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:
|
||||
@@ -322,7 +426,7 @@ def to_cypher(G: nx.Graph, output_path: str) -> None:
|
||||
f"MATCH (a {{id: '{u_esc}'}}), (b {{id: '{v_esc}'}}) "
|
||||
f"MERGE (a)-[:{rel} {{confidence: '{conf}'}}]->(b);"
|
||||
)
|
||||
with open(output_path, "w") as f:
|
||||
with open(output_path, "w", encoding="utf-8") as f: # nosec
|
||||
f.write("\n".join(lines))
|
||||
|
||||
|
||||
@@ -331,22 +435,29 @@ def to_html(
|
||||
communities: dict[int, list[str]],
|
||||
output_path: str,
|
||||
community_labels: dict[int, str] | None = None,
|
||||
member_counts: dict[int, int] | None = None,
|
||||
) -> None:
|
||||
"""Generate an interactive vis.js HTML visualization of the graph.
|
||||
|
||||
Features: node size by degree, click-to-inspect panel, search box,
|
||||
community filter, physics clustering by community, confidence-styled edges.
|
||||
Raises ValueError if graph exceeds MAX_NODES_FOR_VIZ.
|
||||
|
||||
If member_counts is provided (aggregated community view), node sizes are
|
||||
based on community member counts rather than graph degree.
|
||||
"""
|
||||
if G.number_of_nodes() > MAX_NODES_FOR_VIZ:
|
||||
limit = _viz_node_limit()
|
||||
if G.number_of_nodes() > limit:
|
||||
raise ValueError(
|
||||
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz. "
|
||||
f"Use --no-viz or reduce input size."
|
||||
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz "
|
||||
f"(limit: {limit}). Use --no-viz, raise GRAPHIFY_VIZ_NODE_LIMIT, "
|
||||
f"or reduce input size."
|
||||
)
|
||||
|
||||
node_community = _node_community_map(communities)
|
||||
degree = dict(G.degree())
|
||||
max_deg = max(degree.values()) if degree else 1
|
||||
max_deg = max(degree.values(), default=1) or 1
|
||||
max_mc = (max(member_counts.values(), default=1) or 1) if member_counts else 1
|
||||
|
||||
# Build nodes list for vis.js
|
||||
vis_nodes = []
|
||||
@@ -355,9 +466,14 @@ def to_html(
|
||||
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
|
||||
label = sanitize_label(data.get("label", node_id))
|
||||
deg = degree.get(node_id, 1)
|
||||
size = 10 + 30 * (deg / max_deg)
|
||||
# Only show label for high-degree nodes by default; others show on hover
|
||||
font_size = 12 if deg >= max_deg * 0.15 else 0
|
||||
if member_counts:
|
||||
mc = member_counts.get(cid, 1)
|
||||
size = 10 + 30 * (mc / max_mc)
|
||||
font_size = 12
|
||||
else:
|
||||
size = 10 + 30 * (deg / max_deg)
|
||||
# Only show label for high-degree nodes by default; others show on hover
|
||||
font_size = 12 if deg >= max_deg * 0.15 else 0
|
||||
vis_nodes.append({
|
||||
"id": node_id,
|
||||
"label": label,
|
||||
@@ -367,19 +483,24 @@ def to_html(
|
||||
"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", "")),
|
||||
"source_file": sanitize_label(str(data.get("source_file") or "")),
|
||||
"file_type": data.get("file_type", ""),
|
||||
"degree": deg,
|
||||
})
|
||||
|
||||
# Build edges list
|
||||
# Build edges list. Restore original edge direction from _src/_tgt
|
||||
# (stashed by build.py for exactly this reason): undirected NetworkX
|
||||
# canonicalizes endpoint order, which would otherwise flip the arrow
|
||||
# for `calls` and `rationale_for` in the rendered graph (#563).
|
||||
vis_edges = []
|
||||
for u, v, data in G.edges(data=True):
|
||||
confidence = data.get("confidence", "EXTRACTED")
|
||||
relation = data.get("relation", "")
|
||||
true_src = data.get("_src", u)
|
||||
true_tgt = data.get("_tgt", v)
|
||||
vis_edges.append({
|
||||
"from": u,
|
||||
"to": v,
|
||||
"from": true_src,
|
||||
"to": true_tgt,
|
||||
"label": relation,
|
||||
"title": _html.escape(f"{relation} [{confidence}]"),
|
||||
"dashes": confidence != "EXTRACTED",
|
||||
@@ -393,13 +514,17 @@ def to_html(
|
||||
for cid in sorted((community_labels or {}).keys()):
|
||||
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
|
||||
lbl = _html.escape(sanitize_label((community_labels or {}).get(cid, f"Community {cid}")))
|
||||
n = len(communities.get(cid, []))
|
||||
n = member_counts.get(cid, len(communities.get(cid, []))) if member_counts else len(communities.get(cid, []))
|
||||
legend_data.append({"cid": cid, "color": color, "label": lbl, "count": n})
|
||||
|
||||
nodes_json = json.dumps(vis_nodes)
|
||||
edges_json = json.dumps(vis_edges)
|
||||
legend_json = json.dumps(legend_data)
|
||||
hyperedges_json = json.dumps(getattr(G, "graph", {}).get("hyperedges", []))
|
||||
# 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 · {G.number_of_edges()} edges · {len(communities)} communities"
|
||||
|
||||
@@ -424,6 +549,9 @@ def to_html(
|
||||
</div>
|
||||
<div id="legend-wrap">
|
||||
<h3>Communities</h3>
|
||||
<div id="legend-controls">
|
||||
<label><input type="checkbox" id="select-all-cb" checked onchange="toggleAllCommunities(!this.checked)">Select All</label>
|
||||
</div>
|
||||
<div id="legend"></div>
|
||||
</div>
|
||||
<div id="stats">{stats}</div>
|
||||
@@ -433,7 +561,7 @@ def to_html(
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
Path(output_path).write_text(html, encoding="utf-8")
|
||||
Path(output_path).write_text(html, encoding="utf-8") # nosec
|
||||
|
||||
|
||||
# Keep backward-compatible alias - skill.md calls generate_html
|
||||
@@ -463,7 +591,10 @@ def to_obsidian(
|
||||
# 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.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).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] = {}
|
||||
@@ -545,7 +676,7 @@ def to_obsidian(
|
||||
lines.append(inline_tags)
|
||||
|
||||
fname = node_filename[node_id] + ".md"
|
||||
(out / fname).write_text("\n".join(lines), encoding="utf-8")
|
||||
(out / fname).write_text("\n".join(lines), encoding="utf-8") # nosec
|
||||
|
||||
# Write one _COMMUNITY_name.md overview note per community
|
||||
# Build inter-community edge counts for "Connections to other communities"
|
||||
@@ -662,7 +793,7 @@ def to_obsidian(
|
||||
|
||||
community_safe = safe_name(community_name)
|
||||
fname = f"_COMMUNITY_{community_safe}.md"
|
||||
(out / fname).write_text("\n".join(lines), encoding="utf-8")
|
||||
(out / fname).write_text("\n".join(lines), encoding="utf-8") # nosec
|
||||
community_notes_written += 1
|
||||
|
||||
# Improvement 4: write .obsidian/graph.json to color nodes by community in graph view
|
||||
@@ -677,7 +808,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") # nosec
|
||||
|
||||
return G.number_of_nodes() + community_notes_written
|
||||
|
||||
@@ -699,7 +830,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.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).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:
|
||||
@@ -809,7 +942,7 @@ def to_canvas(
|
||||
canvas_nodes.append({
|
||||
"id": f"n_{node_id}",
|
||||
"type": "file",
|
||||
"file": f"graphify/obsidian/{fname}.md",
|
||||
"file": f"{fname}.md",
|
||||
"x": nx_x,
|
||||
"y": nx_y,
|
||||
"width": 180,
|
||||
@@ -836,7 +969,7 @@ def to_canvas(
|
||||
})
|
||||
|
||||
canvas_data = {"nodes": canvas_nodes, "edges": canvas_edges}
|
||||
Path(output_path).write_text(json.dumps(canvas_data, indent=2), encoding="utf-8")
|
||||
Path(output_path).write_text(json.dumps(canvas_data, indent=2), encoding="utf-8") # nosec
|
||||
|
||||
|
||||
def push_to_neo4j(
|
||||
@@ -953,7 +1086,7 @@ 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()]
|
||||
|
||||
+1489
-150
File diff suppressed because it is too large.
Load diff
+85
-31
@@ -1,6 +1,7 @@
|
||||
# git hook integration - install/uninstall graphify post-commit and post-checkout hooks
|
||||
from __future__ import annotations
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
_HOOK_MARKER = "# graphify-hook-start"
|
||||
@@ -12,7 +13,10 @@ _PYTHON_DETECT = """\
|
||||
# Detect the correct Python interpreter (handles pipx, venv, system installs)
|
||||
GRAPHIFY_BIN=$(command -v graphify 2>/dev/null)
|
||||
if [ -n "$GRAPHIFY_BIN" ]; then
|
||||
_SHEBANG=$(head -1 "$GRAPHIFY_BIN" | sed 's/^#![[:space:]]*//')
|
||||
case "$GRAPHIFY_BIN" in
|
||||
*.exe) _SHEBANG="" ;;
|
||||
*) _SHEBANG=$(head -1 "$GRAPHIFY_BIN" | sed 's/^#![[:space:]]*//') ;;
|
||||
esac
|
||||
case "$_SHEBANG" in
|
||||
*/env\\ *) GRAPHIFY_PYTHON="${_SHEBANG#*/env }" ;;
|
||||
*) GRAPHIFY_PYTHON="$_SHEBANG" ;;
|
||||
@@ -20,13 +24,21 @@ if [ -n "$GRAPHIFY_BIN" ]; then
|
||||
# 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="python3" ;;
|
||||
*[!a-zA-Z0-9/_.@-]*) GRAPHIFY_PYTHON="" ;;
|
||||
esac
|
||||
if ! "$GRAPHIFY_PYTHON" -c "import graphify" 2>/dev/null; then
|
||||
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
|
||||
else
|
||||
GRAPHIFY_PYTHON="python3"
|
||||
fi
|
||||
"""
|
||||
|
||||
@@ -35,6 +47,13 @@ _HOOK_SCRIPT = """\
|
||||
# Auto-rebuilds the knowledge graph after each commit (code files only, no LLM needed).
|
||||
# Installed by: graphify hook install
|
||||
|
||||
# Skip during rebase/merge/cherry-pick to avoid blocking --continue with unstaged changes
|
||||
GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
|
||||
[ -d "$GIT_DIR/rebase-merge" ] && exit 0
|
||||
[ -d "$GIT_DIR/rebase-apply" ] && exit 0
|
||||
[ -f "$GIT_DIR/MERGE_HEAD" ] && exit 0
|
||||
[ -f "$GIT_DIR/CHERRY_PICK_HEAD" ] && exit 0
|
||||
|
||||
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
|
||||
@@ -42,31 +61,34 @@ fi
|
||||
|
||||
""" + _PYTHON_DETECT + """
|
||||
export GRAPHIFY_CHANGED="$CHANGED"
|
||||
$GRAPHIFY_PYTHON -c "
|
||||
|
||||
# Run rebuild detached so git commit returns immediately.
|
||||
# Full repo rebuilds can take hours; blocking the post-commit hook stalls the shell.
|
||||
_GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
|
||||
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
|
||||
echo "[graphify hook] launching background rebuild (log: $_GRAPHIFY_LOG)"
|
||||
nohup $GRAPHIFY_PYTHON -c "
|
||||
import os, sys
|
||||
from pathlib import Path
|
||||
|
||||
CODE_EXTS = {
|
||||
'.py', '.ts', '.js', '.go', '.rs', '.java', '.cpp', '.c', '.rb', '.swift',
|
||||
'.kt', '.cs', '.scala', '.php', '.cc', '.cxx', '.hpp', '.h', '.kts',
|
||||
}
|
||||
|
||||
changed_raw = os.environ.get('GRAPHIFY_CHANGED', '')
|
||||
changed = [Path(f.strip()) for f in changed_raw.strip().splitlines() if f.strip()]
|
||||
code_changed = [f for f in changed if f.suffix.lower() in CODE_EXTS and f.exists()]
|
||||
|
||||
if not code_changed:
|
||||
if not changed:
|
||||
sys.exit(0)
|
||||
|
||||
print(f'[graphify hook] {len(code_changed)} code file(s) changed - rebuilding graph...')
|
||||
print(f'[graphify hook] {len(changed)} file(s) changed - rebuilding graph...')
|
||||
|
||||
try:
|
||||
import os as _os
|
||||
from graphify.watch import _rebuild_code
|
||||
_rebuild_code(Path('.'))
|
||||
_force = _os.environ.get('GRAPHIFY_FORCE', '').lower() in ('1', 'true', 'yes')
|
||||
_rebuild_code(Path('.'), force=_force)
|
||||
except Exception as exc:
|
||||
print(f'[graphify hook] Rebuild failed: {exc}')
|
||||
sys.exit(1)
|
||||
"
|
||||
" > "$_GRAPHIFY_LOG" 2>&1 < /dev/null &
|
||||
disown 2>/dev/null || true
|
||||
# graphify-hook-end
|
||||
"""
|
||||
|
||||
@@ -90,18 +112,29 @@ if [ ! -d "graphify-out" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Skip during rebase/merge/cherry-pick
|
||||
GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
|
||||
[ -d "$GIT_DIR/rebase-merge" ] && exit 0
|
||||
[ -d "$GIT_DIR/rebase-apply" ] && exit 0
|
||||
[ -f "$GIT_DIR/MERGE_HEAD" ] && exit 0
|
||||
[ -f "$GIT_DIR/CHERRY_PICK_HEAD" ] && exit 0
|
||||
|
||||
""" + _PYTHON_DETECT + """
|
||||
echo "[graphify] Branch switched - rebuilding knowledge graph (code files)..."
|
||||
$GRAPHIFY_PYTHON -c "
|
||||
_GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
|
||||
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
|
||||
echo "[graphify] Branch switched - launching background rebuild (log: $_GRAPHIFY_LOG)"
|
||||
nohup $GRAPHIFY_PYTHON -c "
|
||||
from graphify.watch import _rebuild_code
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import os, sys
|
||||
try:
|
||||
_rebuild_code(Path('.'))
|
||||
_force = os.environ.get('GRAPHIFY_FORCE', '').lower() in ('1', 'true', 'yes')
|
||||
_rebuild_code(Path('.'), force=_force)
|
||||
except Exception as exc:
|
||||
print(f'[graphify] Rebuild failed: {exc}')
|
||||
sys.exit(1)
|
||||
"
|
||||
" > "$_GRAPHIFY_LOG" 2>&1 < /dev/null &
|
||||
disown 2>/dev/null || true
|
||||
# graphify-checkout-hook-end
|
||||
"""
|
||||
|
||||
@@ -115,16 +148,38 @@ def _git_root(path: Path) -> Path | None:
|
||||
return None
|
||||
|
||||
|
||||
def _hooks_dir(root: Path) -> Path:
|
||||
"""Return the git hooks directory, respecting core.hooksPath if set (e.g. Husky)."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["git", "-C", str(root), "config", "core.hooksPath"],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
if result.returncode == 0:
|
||||
custom = result.stdout.strip()
|
||||
if custom:
|
||||
p = Path(custom).expanduser()
|
||||
if not p.is_absolute():
|
||||
p = root / p
|
||||
p.mkdir(parents=True, exist_ok=True)
|
||||
return p
|
||||
except (OSError, FileNotFoundError):
|
||||
pass
|
||||
d = root / ".git" / "hooks"
|
||||
d.mkdir(exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
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()
|
||||
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)
|
||||
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)
|
||||
hook_path.write_text("#!/bin/sh\n" + script, encoding="utf-8", newline="\n")
|
||||
hook_path.chmod(0o755)
|
||||
return f"installed at {hook_path}"
|
||||
|
||||
@@ -134,7 +189,7 @@ def _uninstall_hook(hooks_dir: Path, name: str, marker: str, marker_end: str) ->
|
||||
hook_path = hooks_dir / name
|
||||
if not hook_path.exists():
|
||||
return f"no {name} hook found - nothing to remove."
|
||||
content = hook_path.read_text()
|
||||
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(
|
||||
@@ -146,7 +201,7 @@ def _uninstall_hook(hooks_dir: Path, name: str, marker: str, marker_end: str) ->
|
||||
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")
|
||||
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)"
|
||||
|
||||
|
||||
@@ -156,8 +211,7 @@ def install(path: Path = Path(".")) -> str:
|
||||
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)
|
||||
hooks_dir = _hooks_dir(root)
|
||||
|
||||
commit_msg = _install_hook(hooks_dir, "post-commit", _HOOK_SCRIPT, _HOOK_MARKER)
|
||||
checkout_msg = _install_hook(hooks_dir, "post-checkout", _CHECKOUT_SCRIPT, _CHECKOUT_MARKER)
|
||||
@@ -171,7 +225,7 @@ def uninstall(path: Path = Path(".")) -> str:
|
||||
if root is None:
|
||||
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
|
||||
|
||||
hooks_dir = root / ".git" / "hooks"
|
||||
hooks_dir = _hooks_dir(root)
|
||||
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)
|
||||
|
||||
@@ -183,13 +237,13 @@ def status(path: Path = Path(".")) -> str:
|
||||
root = _git_root(path)
|
||||
if root is None:
|
||||
return "Not in a git repository."
|
||||
hooks_dir = root / ".git" / "hooks"
|
||||
hooks_dir = _hooks_dir(root)
|
||||
|
||||
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() else "not installed (hook exists but graphify not found)"
|
||||
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)
|
||||
|
||||
+19
-22
@@ -49,19 +49,16 @@ def _fetch_html(url: str) -> str:
|
||||
|
||||
|
||||
def _html_to_markdown(html: str, url: str) -> str:
|
||||
"""Convert HTML to clean markdown. Uses html2text if available, else basic strip."""
|
||||
"""Convert HTML to clean markdown. Uses markdownify if available, else basic strip."""
|
||||
# Always pre-strip script/style so their text content never leaks into output
|
||||
html = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
|
||||
html = re.sub(r"<style[^>]*>.*?</style>", "", html, flags=re.DOTALL | re.IGNORECASE)
|
||||
try:
|
||||
import html2text
|
||||
h = html2text.HTML2Text()
|
||||
h.ignore_links = False
|
||||
h.ignore_images = True
|
||||
h.body_width = 0
|
||||
return h.handle(html)
|
||||
from markdownify import markdownify
|
||||
return markdownify(html, heading_style="ATX", bullets="-", strip=["img"])
|
||||
except ImportError:
|
||||
# Fallback: strip tags
|
||||
text = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
|
||||
text = re.sub(r"<style[^>]*>.*?</style>", "", text, flags=re.DOTALL | re.IGNORECASE)
|
||||
text = re.sub(r"<[^>]+>", " ", text)
|
||||
# Fallback: basic tag strip
|
||||
text = re.sub(r"<[^>]+>", " ", html)
|
||||
text = re.sub(r"\s+", " ", text).strip()
|
||||
return text[:8000]
|
||||
|
||||
@@ -82,11 +79,11 @@ def _fetch_tweet(url: str, author: str | None, contributor: str | None) -> tuple
|
||||
|
||||
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}
|
||||
@@ -109,11 +106,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: "{_yaml_str(title)}"
|
||||
captured_at: {now}
|
||||
contributor: {contributor or author or 'unknown'}
|
||||
contributor: "{_yaml_str(contributor or author or 'unknown')}"
|
||||
---
|
||||
|
||||
# {title}
|
||||
@@ -149,13 +146,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}
|
||||
@@ -225,7 +222,7 @@ def ingest(url: str, target_dir: Path, author: str | None = None, contributor: s
|
||||
out_path = target_dir / filename
|
||||
# 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
|
||||
|
||||
+478
@@ -0,0 +1,478 @@
|
||||
# Direct LLM backend for semantic extraction — supports Claude and Kimi K2.6.
|
||||
# Used by `graphify . --backend kimi` and the benchmark scripts.
|
||||
# The default graphify pipeline uses Claude Code subagents via skill.md;
|
||||
# this module provides a direct API path for non-Claude-Code environments.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from pathlib import Path
|
||||
|
||||
# `_read_files` truncates each file at this many characters before joining into
|
||||
# the user message. Token estimates use the same cap so packing matches reality.
|
||||
_FILE_CHAR_CAP = 20_000
|
||||
# `_read_files` also wraps each file in a `=== {rel} ===\n...\n\n` separator;
|
||||
# this is roughly the per-file overhead in characters that the prompt adds.
|
||||
_PER_FILE_OVERHEAD_CHARS = 80
|
||||
# Coarse fallback used only when `tiktoken` is not installed. 1 token ≈ 4 chars
|
||||
# is the standard heuristic for English/code on BPE tokenizers.
|
||||
_CHARS_PER_TOKEN = 4
|
||||
|
||||
|
||||
def _get_tokenizer():
|
||||
"""Return a tiktoken encoder for accurate token counts, or None if tiktoken
|
||||
is not installed. We use `cl100k_base` (GPT-4 / GPT-3.5-turbo) as a proxy:
|
||||
Kimi-K2 ships a tiktoken-based tokenizer with very similar BPE behaviour,
|
||||
and Claude's tokenizer has a comparable token-to-char ratio for prose/code.
|
||||
Estimates only need to be within ~5%, not exact.
|
||||
"""
|
||||
try:
|
||||
import tiktoken
|
||||
except ImportError:
|
||||
return None
|
||||
try:
|
||||
return tiktoken.get_encoding("cl100k_base")
|
||||
except Exception: # network failure on first-use download, etc.
|
||||
return None
|
||||
|
||||
|
||||
# Cached at import time. None if tiktoken is unavailable; consumers must handle.
|
||||
_TOKENIZER = _get_tokenizer()
|
||||
|
||||
BACKENDS: dict[str, dict] = {
|
||||
"claude": {
|
||||
"base_url": "https://api.anthropic.com",
|
||||
"default_model": "claude-sonnet-4-6",
|
||||
"env_key": "ANTHROPIC_API_KEY",
|
||||
"pricing": {"input": 3.0, "output": 15.0}, # USD per 1M tokens
|
||||
"temperature": 0,
|
||||
},
|
||||
"kimi": {
|
||||
"base_url": "https://api.moonshot.ai/v1",
|
||||
"default_model": "kimi-k2.6",
|
||||
"env_key": "MOONSHOT_API_KEY",
|
||||
"pricing": {"input": 0.74, "output": 4.66}, # USD per 1M tokens
|
||||
"temperature": None, # kimi-k2.6 enforces its own fixed temperature; sending any value raises 400
|
||||
},
|
||||
}
|
||||
|
||||
_EXTRACTION_SYSTEM = """\
|
||||
You are a graphify semantic extraction agent. Extract a knowledge graph fragment from the files provided.
|
||||
Output ONLY valid JSON — no explanation, no markdown fences, no preamble.
|
||||
|
||||
Rules:
|
||||
- EXTRACTED: relationship explicit in source (import, call, citation, reference)
|
||||
- INFERRED: reasonable inference (shared data structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain — flag for review, do not omit
|
||||
|
||||
Node ID format: lowercase, only [a-z0-9_], no dots or slashes.
|
||||
Format: {stem}_{entity} where stem = filename without extension, entity = symbol name (both normalised).
|
||||
|
||||
Output exactly this schema:
|
||||
{"nodes":[{"id":"stem_entity","label":"Human Readable Name","file_type":"code|document|paper|image|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[],"input_tokens":0,"output_tokens":0}
|
||||
"""
|
||||
|
||||
|
||||
def _read_files(paths: list[Path], root: Path) -> str:
|
||||
"""Return file contents formatted for the extraction prompt."""
|
||||
parts: list[str] = []
|
||||
for p in paths:
|
||||
try:
|
||||
rel = p.relative_to(root)
|
||||
except ValueError:
|
||||
rel = p
|
||||
try:
|
||||
content = p.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
continue
|
||||
parts.append(f"=== {rel} ===\n{content[:20000]}")
|
||||
return "\n\n".join(parts)
|
||||
|
||||
|
||||
def _parse_llm_json(raw: str) -> dict:
|
||||
"""Strip optional markdown fences and parse JSON. Returns empty fragment on failure."""
|
||||
if raw.startswith("```"):
|
||||
raw = raw.split("```", 2)[1]
|
||||
if raw.startswith("json"):
|
||||
raw = raw[4:]
|
||||
raw = raw.rsplit("```", 1)[0]
|
||||
try:
|
||||
return json.loads(raw.strip())
|
||||
except json.JSONDecodeError as exc:
|
||||
print(f"[graphify] LLM returned invalid JSON, skipping chunk: {exc}", file=sys.stderr)
|
||||
return {"nodes": [], "edges": [], "hyperedges": []}
|
||||
|
||||
|
||||
def _call_openai_compat(
|
||||
base_url: str,
|
||||
api_key: str,
|
||||
model: str,
|
||||
user_message: str,
|
||||
temperature: float | None = 0,
|
||||
) -> dict:
|
||||
"""Call any OpenAI-compatible API (Kimi, OpenAI, etc.) and return parsed JSON."""
|
||||
try:
|
||||
from openai import OpenAI
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Kimi/OpenAI-compatible extraction requires the openai package. "
|
||||
"Run: pip install openai"
|
||||
) from exc
|
||||
|
||||
client = OpenAI(api_key=api_key, base_url=base_url)
|
||||
kwargs: dict = {
|
||||
"model": model,
|
||||
"messages": [
|
||||
{"role": "system", "content": _EXTRACTION_SYSTEM},
|
||||
{"role": "user", "content": user_message},
|
||||
],
|
||||
"max_completion_tokens": 8192,
|
||||
}
|
||||
if temperature is not None:
|
||||
kwargs["temperature"] = temperature
|
||||
# Kimi-k2.6 is a reasoning model — disable thinking so content isn't empty
|
||||
if "moonshot" in base_url:
|
||||
kwargs["extra_body"] = {"thinking": {"type": "disabled"}}
|
||||
resp = client.chat.completions.create(**kwargs)
|
||||
result = _parse_llm_json(resp.choices[0].message.content or "{}")
|
||||
result["input_tokens"] = resp.usage.prompt_tokens if resp.usage else 0
|
||||
result["output_tokens"] = resp.usage.completion_tokens if resp.usage else 0
|
||||
result["model"] = model
|
||||
# `finish_reason == "length"` means the model hit max_completion_tokens
|
||||
# mid-generation. The JSON we got back is truncated; callers should
|
||||
# treat this as a signal to retry with smaller input.
|
||||
result["finish_reason"] = resp.choices[0].finish_reason
|
||||
return result
|
||||
|
||||
|
||||
def _call_claude(api_key: str, model: str, user_message: str) -> dict:
|
||||
"""Call Anthropic Claude directly (not via OpenAI compat layer)."""
|
||||
try:
|
||||
import anthropic
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Claude direct extraction requires the anthropic package. "
|
||||
"Run: pip install anthropic"
|
||||
) from exc
|
||||
|
||||
client = anthropic.Anthropic(api_key=api_key)
|
||||
resp = client.messages.create(
|
||||
model=model,
|
||||
max_tokens=8192,
|
||||
system=_EXTRACTION_SYSTEM,
|
||||
messages=[{"role": "user", "content": user_message}],
|
||||
)
|
||||
result = _parse_llm_json(resp.content[0].text if resp.content else "{}")
|
||||
result["input_tokens"] = resp.usage.input_tokens if resp.usage else 0
|
||||
result["output_tokens"] = resp.usage.output_tokens if resp.usage else 0
|
||||
result["model"] = model
|
||||
# Normalise Anthropic's `stop_reason` to the OpenAI-compat `finish_reason`
|
||||
# vocabulary so the adaptive-retry layer doesn't have to know which
|
||||
# backend produced the result.
|
||||
result["finish_reason"] = "length" if resp.stop_reason == "max_tokens" else "stop"
|
||||
return result
|
||||
|
||||
|
||||
def extract_files_direct(
|
||||
files: list[Path],
|
||||
backend: str = "kimi",
|
||||
api_key: str | None = None,
|
||||
model: str | None = None,
|
||||
root: Path = Path("."),
|
||||
) -> dict:
|
||||
"""Extract semantic nodes/edges from a list of files using the given backend.
|
||||
|
||||
Returns dict with nodes, edges, hyperedges, input_tokens, output_tokens.
|
||||
Raises ValueError for unknown backends. Raises ImportError if SDK missing.
|
||||
"""
|
||||
if backend not in BACKENDS:
|
||||
raise ValueError(f"Unknown backend {backend!r}. Available: {sorted(BACKENDS)}")
|
||||
|
||||
cfg = BACKENDS[backend]
|
||||
key = api_key or os.environ.get(cfg["env_key"], "")
|
||||
if not key:
|
||||
raise ValueError(
|
||||
f"No API key for backend '{backend}'. "
|
||||
f"Set {cfg['env_key']} or pass api_key=."
|
||||
)
|
||||
mdl = model or cfg["default_model"]
|
||||
user_msg = _read_files(files, root)
|
||||
|
||||
if backend == "claude":
|
||||
return _call_claude(key, mdl, user_msg)
|
||||
else:
|
||||
return _call_openai_compat(cfg["base_url"], key, mdl, user_msg, temperature=cfg.get("temperature", 0))
|
||||
|
||||
|
||||
def _estimate_file_tokens(path: Path) -> int:
|
||||
"""Estimate the prompt-token cost of a single file under `_read_files` rules.
|
||||
|
||||
Uses tiktoken (`cl100k_base`) when available for accurate counts. Falls back
|
||||
to the chars/4 heuristic if tiktoken is not installed. Both paths cap at
|
||||
`_FILE_CHAR_CAP` to match `_read_files`'s truncation, plus a constant for
|
||||
the `=== rel ===` separator. Returns 0 for unreadable paths so they don't
|
||||
blow up packing.
|
||||
"""
|
||||
if _TOKENIZER is None:
|
||||
try:
|
||||
size = path.stat().st_size
|
||||
except OSError:
|
||||
return 0
|
||||
chars = min(size, _FILE_CHAR_CAP) + _PER_FILE_OVERHEAD_CHARS
|
||||
return chars // _CHARS_PER_TOKEN
|
||||
|
||||
try:
|
||||
content = path.read_text(encoding="utf-8", errors="replace")[:_FILE_CHAR_CAP]
|
||||
except OSError:
|
||||
return 0
|
||||
return len(_TOKENIZER.encode(content)) + (_PER_FILE_OVERHEAD_CHARS // _CHARS_PER_TOKEN)
|
||||
|
||||
|
||||
def _pack_chunks_by_tokens(
|
||||
files: list[Path],
|
||||
token_budget: int,
|
||||
) -> list[list[Path]]:
|
||||
"""Greedily pack files into chunks that fit a token budget.
|
||||
|
||||
Files are first grouped by parent directory so related artifacts share a
|
||||
chunk (cross-file edges are more likely to be extracted within a chunk
|
||||
than across chunks). Within each directory, files are added one at a
|
||||
time; a chunk is closed when adding the next file would exceed the
|
||||
budget. A single file larger than the budget gets its own chunk and the
|
||||
caller is expected to handle the API error if it actually overflows the
|
||||
model's context window — packing can't shrink one big file.
|
||||
"""
|
||||
if token_budget <= 0:
|
||||
raise ValueError(f"token_budget must be positive, got {token_budget}")
|
||||
|
||||
by_dir: dict[Path, list[Path]] = {}
|
||||
for f in files:
|
||||
by_dir.setdefault(f.parent, []).append(f)
|
||||
|
||||
chunks: list[list[Path]] = []
|
||||
current: list[Path] = []
|
||||
current_tokens = 0
|
||||
|
||||
for directory in sorted(by_dir):
|
||||
for path in by_dir[directory]:
|
||||
cost = _estimate_file_tokens(path)
|
||||
if current and current_tokens + cost > token_budget:
|
||||
chunks.append(current)
|
||||
current = []
|
||||
current_tokens = 0
|
||||
current.append(path)
|
||||
current_tokens += cost
|
||||
|
||||
if current:
|
||||
chunks.append(current)
|
||||
return chunks
|
||||
|
||||
|
||||
def _extract_with_adaptive_retry(
|
||||
chunk: list[Path],
|
||||
backend: str,
|
||||
api_key: str | None,
|
||||
model: str | None,
|
||||
root: Path,
|
||||
max_depth: int,
|
||||
_depth: int = 0,
|
||||
) -> dict:
|
||||
"""Extract a chunk; if the response is truncated (`finish_reason="length"`),
|
||||
split the chunk in half and recurse.
|
||||
|
||||
The signal driving the retry is the API's own `finish_reason` — `"length"`
|
||||
means the model hit `max_completion_tokens` mid-output. The truncated JSON
|
||||
has nothing useful in it (parse fails partway through a string or array),
|
||||
so we discard it and re-extract on smaller inputs that produce shorter
|
||||
outputs.
|
||||
|
||||
Recursion is capped at `max_depth` to bound worst-case cost. A chunk of N
|
||||
files can split into up to 2**max_depth pieces — at depth=3 that's 8x. If
|
||||
still truncated at the cap, we surface the (likely empty) result with a
|
||||
warning rather than infinite-loop.
|
||||
|
||||
A single-file chunk that truncates is unrecoverable here — we can't make
|
||||
one file smaller than itself, so we return what we got and warn.
|
||||
"""
|
||||
result = extract_files_direct(
|
||||
chunk, backend=backend, api_key=api_key, model=model, root=root
|
||||
)
|
||||
|
||||
if result.get("finish_reason") != "length":
|
||||
return result
|
||||
|
||||
if len(chunk) <= 1:
|
||||
print(
|
||||
f"[graphify] single-file chunk {chunk[0]} truncated at "
|
||||
f"max_completion_tokens — partial result kept",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return result
|
||||
|
||||
if _depth >= max_depth:
|
||||
print(
|
||||
f"[graphify] chunk of {len(chunk)} still truncated at recursion "
|
||||
f"depth {_depth} (max {max_depth}) — partial result kept",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return result
|
||||
|
||||
print(
|
||||
f"[graphify] chunk of {len(chunk)} truncated at depth {_depth}, "
|
||||
f"splitting into halves of {len(chunk) // 2} and "
|
||||
f"{len(chunk) - len(chunk) // 2}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
mid = len(chunk) // 2
|
||||
left = _extract_with_adaptive_retry(
|
||||
chunk[:mid], backend, api_key, model, root, max_depth, _depth + 1
|
||||
)
|
||||
right = _extract_with_adaptive_retry(
|
||||
chunk[mid:], backend, api_key, model, root, max_depth, _depth + 1
|
||||
)
|
||||
|
||||
return {
|
||||
"nodes": left.get("nodes", []) + right.get("nodes", []),
|
||||
"edges": left.get("edges", []) + right.get("edges", []),
|
||||
"hyperedges": left.get("hyperedges", []) + right.get("hyperedges", []),
|
||||
"input_tokens": left.get("input_tokens", 0) + right.get("input_tokens", 0),
|
||||
"output_tokens": left.get("output_tokens", 0) + right.get("output_tokens", 0),
|
||||
"model": result.get("model"),
|
||||
# Both halves either succeeded or have already surfaced their own
|
||||
# truncation warning; the merged result is no longer truncated as a
|
||||
# logical unit.
|
||||
"finish_reason": "stop",
|
||||
}
|
||||
|
||||
|
||||
def extract_corpus_parallel(
|
||||
files: list[Path],
|
||||
backend: str = "kimi",
|
||||
api_key: str | None = None,
|
||||
model: str | None = None,
|
||||
root: Path = Path("."),
|
||||
chunk_size: int = 20,
|
||||
on_chunk_done: Callable | None = None,
|
||||
token_budget: int | None = 60_000,
|
||||
max_concurrency: int = 4,
|
||||
max_retry_depth: int = 3,
|
||||
) -> dict:
|
||||
"""Extract a corpus in chunks, merging results.
|
||||
|
||||
Chunking strategy:
|
||||
- If `token_budget` is set (default 60_000), files are packed to fit
|
||||
the budget and grouped by parent directory. This avoids the worst
|
||||
case where 20 randomly-grouped files exceed a model's context
|
||||
window in a single request.
|
||||
- If `token_budget=None`, falls back to the legacy fixed-count
|
||||
`chunk_size` packing for backwards compatibility.
|
||||
|
||||
Concurrency:
|
||||
- Chunks run in parallel via a thread pool capped at `max_concurrency`
|
||||
(default 4 — conservative to stay under provider rate limits).
|
||||
- Set `max_concurrency=1` to force sequential execution.
|
||||
|
||||
Adaptive retry on truncation:
|
||||
- When the LLM returns `finish_reason="length"` (output truncated at
|
||||
`max_completion_tokens`), the chunk is split in half and each half
|
||||
re-extracted recursively, up to `max_retry_depth` levels deep
|
||||
(default 3 → max 8x expansion of one chunk).
|
||||
- This is signal-driven: chunks too dense to fit in one response
|
||||
self-heal by splitting until they do, while well-sized chunks pay
|
||||
no extra cost. Set `max_retry_depth=0` to disable retries.
|
||||
|
||||
`on_chunk_done(idx, total, chunk_result)` fires once per chunk as it
|
||||
completes (in completion order, not submission order). `idx` is the
|
||||
chunk's submission index so callers can correlate progress. The
|
||||
callback fires once per top-level chunk; recursive splits are merged
|
||||
transparently before the callback is invoked.
|
||||
|
||||
Returns merged dict with nodes, edges, hyperedges, input_tokens,
|
||||
output_tokens. Failed chunks are logged to stderr and skipped — one bad
|
||||
chunk does not abort the run.
|
||||
"""
|
||||
if token_budget is not None:
|
||||
chunks = _pack_chunks_by_tokens(files, token_budget=token_budget)
|
||||
else:
|
||||
chunks = [files[i:i + chunk_size] for i in range(0, len(files), chunk_size)]
|
||||
|
||||
merged: dict = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
total = len(chunks)
|
||||
|
||||
def _run_one(idx: int, chunk: list[Path]) -> tuple[int, dict | None, Exception | None]:
|
||||
t0 = time.time()
|
||||
try:
|
||||
result = _extract_with_adaptive_retry(
|
||||
chunk,
|
||||
backend=backend,
|
||||
api_key=api_key,
|
||||
model=model,
|
||||
root=root,
|
||||
max_depth=max_retry_depth,
|
||||
)
|
||||
result["elapsed_seconds"] = round(time.time() - t0, 2)
|
||||
return idx, result, None
|
||||
except Exception as exc: # noqa: BLE001 — caller-facing surface, log + continue
|
||||
return idx, None, exc
|
||||
|
||||
workers = max(1, min(max_concurrency, total))
|
||||
if workers == 1:
|
||||
# Avoid thread pool overhead for single-worker runs (and keep
|
||||
# callback ordering identical to the pre-refactor sequential path).
|
||||
for idx, chunk in enumerate(chunks):
|
||||
_, result, exc = _run_one(idx, chunk)
|
||||
if exc is not None:
|
||||
print(f"[graphify] chunk {idx + 1}/{total} failed: {exc}", file=sys.stderr)
|
||||
continue
|
||||
assert result is not None
|
||||
_merge_into(merged, result)
|
||||
if callable(on_chunk_done):
|
||||
on_chunk_done(idx, total, result)
|
||||
return merged
|
||||
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
futures = [pool.submit(_run_one, idx, chunk) for idx, chunk in enumerate(chunks)]
|
||||
for future in as_completed(futures):
|
||||
idx, result, exc = future.result()
|
||||
if exc is not None:
|
||||
print(f"[graphify] chunk {idx + 1}/{total} failed: {exc}", file=sys.stderr)
|
||||
continue
|
||||
assert result is not None
|
||||
_merge_into(merged, result)
|
||||
if callable(on_chunk_done):
|
||||
on_chunk_done(idx, total, result)
|
||||
return merged
|
||||
|
||||
|
||||
def _merge_into(merged: dict, result: dict) -> None:
|
||||
"""Append a chunk result into the running merged accumulator."""
|
||||
merged["nodes"].extend(result.get("nodes", []))
|
||||
merged["edges"].extend(result.get("edges", []))
|
||||
merged["hyperedges"].extend(result.get("hyperedges", []))
|
||||
merged["input_tokens"] += result.get("input_tokens", 0)
|
||||
merged["output_tokens"] += result.get("output_tokens", 0)
|
||||
|
||||
|
||||
def estimate_cost(backend: str, input_tokens: int, output_tokens: int) -> float:
|
||||
"""Estimate USD cost for a given token count using published pricing."""
|
||||
if backend not in BACKENDS:
|
||||
return 0.0
|
||||
p = BACKENDS[backend]["pricing"]
|
||||
return (input_tokens * p["input"] + output_tokens * p["output"]) / 1_000_000
|
||||
|
||||
|
||||
def detect_backend() -> str | None:
|
||||
"""Return the name of whichever backend has an API key set, or None.
|
||||
|
||||
Kimi is checked first (opt-in). Falls back to Claude if ANTHROPIC_API_KEY is set.
|
||||
Claude is the default for the skill.md subagent pipeline and is never forced here.
|
||||
"""
|
||||
if os.environ.get("MOONSHOT_API_KEY"):
|
||||
return "kimi"
|
||||
if os.environ.get("ANTHROPIC_API_KEY"):
|
||||
return "claude"
|
||||
return None
|
||||
+39
-10
@@ -1,9 +1,17 @@
|
||||
# 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]],
|
||||
@@ -15,6 +23,7 @@ def generate(
|
||||
token_cost: dict,
|
||||
root: str,
|
||||
suggested_questions: list[dict] | None = None,
|
||||
min_community_size: int = 3,
|
||||
) -> str:
|
||||
today = date.today().isoformat()
|
||||
|
||||
@@ -41,18 +50,34 @@ def generate(
|
||||
"- Verdict: corpus is large enough that graph structure adds value.",
|
||||
]
|
||||
|
||||
from .analyze import _is_file_node as _ifn
|
||||
non_empty = {cid: nodes for cid, nodes in communities.items()
|
||||
if any(not _ifn(G, n) for n in nodes)}
|
||||
|
||||
lines += [
|
||||
"",
|
||||
"## Summary",
|
||||
f"- {G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(communities)} communities detected",
|
||||
f"- {G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(non_empty)} communities detected",
|
||||
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 non_empty:
|
||||
lines += ["", "## Community Hubs (Navigation)"]
|
||||
for cid in non_empty:
|
||||
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)",
|
||||
]
|
||||
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:
|
||||
@@ -84,13 +109,20 @@ def generate(
|
||||
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
|
||||
thin_count = sum(
|
||||
1 for nodes in communities.values()
|
||||
if 0 < sum(1 for n in nodes if not _ifn(G, n)) < min_community_size
|
||||
)
|
||||
lines += ["", f"## Communities ({len(communities)} total, {thin_count} thin omitted)"]
|
||||
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
|
||||
real_nodes = [n for n in nodes if not _ifn(G, n)]
|
||||
if not real_nodes:
|
||||
continue
|
||||
if len(real_nodes) < min_community_size:
|
||||
continue
|
||||
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 += [
|
||||
@@ -119,7 +151,8 @@ def generate(
|
||||
if G.degree(n) <= 1 and not _is_file_node(G, n) and not _is_concept_node(G, n)
|
||||
]
|
||||
thin_communities = {
|
||||
cid: nodes for cid, nodes in communities.items() if len(nodes) < 3
|
||||
cid: nodes for cid, nodes in communities.items()
|
||||
if 0 < sum(1 for n in nodes if not _is_file_node(G, n)) < 3
|
||||
}
|
||||
gap_count = len(isolated) + len(thin_communities)
|
||||
|
||||
@@ -131,11 +164,7 @@ def generate(
|
||||
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.")
|
||||
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(f"- **{len(thin_communities)} thin communities (<{min_community_size} nodes) omitted from report** — run `graphify query` to explore isolated nodes.")
|
||||
if amb_pct > 20:
|
||||
lines.append(f"- **High ambiguity: {amb_pct}% of edges are AMBIGUOUS.** Review the Ambiguous Edges section above.")
|
||||
|
||||
|
||||
+48
-6
@@ -1,6 +1,7 @@
|
||||
# Security helpers - URL validation, safe fetch, path guards, label sanitisation
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import html
|
||||
import re
|
||||
import urllib.error
|
||||
@@ -58,12 +59,45 @@ def validate_url(url: str) -> str:
|
||||
f"Blocked private/internal IP {addr} (resolved from '{hostname}'). "
|
||||
f"Got: {url!r}"
|
||||
)
|
||||
except socket.gaierror:
|
||||
pass # DNS failure will surface later during fetch
|
||||
except socket.gaierror as exc:
|
||||
raise ValueError(
|
||||
f"DNS resolution failed for '{hostname}': {exc}. Got: {url!r}"
|
||||
) from exc
|
||||
|
||||
return url
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _ssrf_guarded_socket():
|
||||
"""Patch socket.getaddrinfo for the duration of a fetch to catch DNS rebinding.
|
||||
|
||||
Validates every IP that urllib resolves so a DNS server cannot return a public IP
|
||||
for validate_url and swap to a private IP for the actual connection (TOCTOU fix).
|
||||
Not thread-safe, but graphify is a single-threaded CLI tool.
|
||||
"""
|
||||
original = socket.getaddrinfo
|
||||
|
||||
def _guarded(host, port, *args, **kwargs):
|
||||
results = original(host, port, *args, **kwargs)
|
||||
for info in results:
|
||||
addr = info[4][0]
|
||||
try:
|
||||
ip = ipaddress.ip_address(addr)
|
||||
except ValueError:
|
||||
continue
|
||||
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local:
|
||||
raise OSError(
|
||||
f"SSRF blocked: IP {addr} resolved from '{host}' is private/reserved"
|
||||
)
|
||||
return results
|
||||
|
||||
socket.getaddrinfo = _guarded
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
socket.getaddrinfo = original
|
||||
|
||||
|
||||
class _NoFileRedirectHandler(urllib.request.HTTPRedirectHandler):
|
||||
"""Redirect handler that re-validates every redirect target.
|
||||
|
||||
@@ -104,7 +138,7 @@ def safe_fetch(url: str, max_bytes: int = _MAX_FETCH_BYTES, timeout: int = 30) -
|
||||
opener = _build_opener()
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 graphify/1.0"})
|
||||
|
||||
with opener.open(req, timeout=timeout) as resp:
|
||||
with _ssrf_guarded_socket(), opener.open(req, timeout=timeout) as resp:
|
||||
# urllib raises HTTPError for non-2xx when using urlopen directly;
|
||||
# with a custom opener we check manually to be safe.
|
||||
status = getattr(resp, "status", None) or getattr(resp, "code", None)
|
||||
@@ -153,7 +187,13 @@ def validate_graph_path(path: str | Path, base: Path | None = None) -> Path:
|
||||
FileNotFoundError - resolved path does not exist
|
||||
"""
|
||||
if base is None:
|
||||
base = Path("graphify-out").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():
|
||||
@@ -185,13 +225,15 @@ _CONTROL_CHAR_RE = re.compile(r"[\x00-\x1f\x7f]")
|
||||
_MAX_LABEL_LEN = 256
|
||||
|
||||
|
||||
def sanitize_label(text: str) -> str:
|
||||
def sanitize_label(text: str | None) -> str:
|
||||
"""Strip control characters and cap length.
|
||||
|
||||
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 text is None:
|
||||
return ""
|
||||
text = _CONTROL_CHAR_RE.sub("", str(text))
|
||||
if len(text) > _MAX_LABEL_LEN:
|
||||
text = text[:_MAX_LABEL_LEN]
|
||||
return text
|
||||
+177
-22
@@ -16,7 +16,7 @@ def _load_graph(graph_path: str) -> nx.Graph:
|
||||
if not resolved.exists():
|
||||
raise FileNotFoundError(f"Graph file not found: {resolved}")
|
||||
safe = resolved
|
||||
data = json.loads(safe.read_text())
|
||||
data = json.loads(safe.read_text(encoding="utf-8"))
|
||||
try:
|
||||
return json_graph.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
@@ -39,17 +39,92 @@ 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))
|
||||
|
||||
|
||||
_EXACT_MATCH_BONUS = 100.0
|
||||
|
||||
|
||||
def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
|
||||
scored = []
|
||||
norm_terms = [_strip_diacritics(t).lower() for t in terms]
|
||||
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)
|
||||
# Exact match: single term equals the full label (strip trailing () for functions)
|
||||
if any(t == norm_label or t == norm_label.rstrip("()") for t in norm_terms):
|
||||
score += _EXACT_MATCH_BONUS
|
||||
if score > 0:
|
||||
scored.append((score, nid))
|
||||
return sorted(scored, reverse=True)
|
||||
|
||||
|
||||
_CONTEXT_HINTS: tuple[tuple[str, tuple[str, ...]], ...] = (
|
||||
("call", ("call", "calls", "called", "invoke", "invokes", "invoked")),
|
||||
("import", ("import", "imports", "imported", "module", "modules")),
|
||||
("field", ("field", "fields", "member", "members", "property", "properties")),
|
||||
("parameter_type", ("parameter", "parameters", "param", "params", "argument", "arguments")),
|
||||
("return_type", ("return", "returns", "returned")),
|
||||
("generic_arg", ("generic", "generics", "template", "templates")),
|
||||
)
|
||||
|
||||
|
||||
def _normalize_context_filters(filters: list[str] | None) -> list[str]:
|
||||
if not filters:
|
||||
return []
|
||||
normalized: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for value in filters:
|
||||
key = _strip_diacritics(str(value)).strip().lower()
|
||||
if key and key not in seen:
|
||||
seen.add(key)
|
||||
normalized.append(key)
|
||||
return normalized
|
||||
|
||||
|
||||
def _infer_context_filters(question: str) -> list[str]:
|
||||
lowered = {
|
||||
_strip_diacritics(token).lower()
|
||||
for token in question.replace("?", " ").replace(",", " ").split()
|
||||
}
|
||||
inferred: list[str] = []
|
||||
for context, hints in _CONTEXT_HINTS:
|
||||
if any(hint in lowered for hint in hints):
|
||||
inferred.append(context)
|
||||
return inferred
|
||||
|
||||
|
||||
def _resolve_context_filters(question: str, explicit_filters: list[str] | None = None) -> tuple[list[str], str | None]:
|
||||
normalized = _normalize_context_filters(explicit_filters)
|
||||
if normalized:
|
||||
return normalized, "explicit"
|
||||
inferred = _infer_context_filters(question)
|
||||
if inferred:
|
||||
return inferred, "heuristic"
|
||||
return [], None
|
||||
|
||||
|
||||
def _filter_graph_by_context(G: nx.Graph, context_filters: list[str] | None) -> nx.Graph:
|
||||
filters = set(_normalize_context_filters(context_filters))
|
||||
if not filters:
|
||||
return G
|
||||
H = G.__class__()
|
||||
H.add_nodes_from(G.nodes(data=True))
|
||||
if isinstance(G, (nx.MultiGraph, nx.MultiDiGraph)):
|
||||
for u, v, key, data in G.edges(keys=True, data=True):
|
||||
if data.get("context") in filters:
|
||||
H.add_edge(u, v, key=key, **data)
|
||||
else:
|
||||
for u, v, data in G.edges(data=True):
|
||||
if data.get("context") in filters:
|
||||
H.add_edge(u, v, **data)
|
||||
return H
|
||||
|
||||
|
||||
def _bfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], list[tuple]]:
|
||||
visited: set[str] = set(start_nodes)
|
||||
frontier = set(start_nodes)
|
||||
@@ -82,18 +157,32 @@ def _dfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], lis
|
||||
return visited, edges_seen
|
||||
|
||||
|
||||
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000) -> str:
|
||||
"""Render subgraph as text, cutting at token_budget (approx 3 chars/token)."""
|
||||
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000, *, seeds: list[str] | None = None) -> str:
|
||||
"""Render subgraph as text, cutting at token_budget (approx 3 chars/token).
|
||||
|
||||
seeds: exact-match nodes rendered first before the degree-sorted expansion,
|
||||
so the queried symbol always appears at the top of the output.
|
||||
"""
|
||||
char_budget = token_budget * 3
|
||||
lines = []
|
||||
for nid in sorted(nodes, key=lambda n: G.degree(n), reverse=True):
|
||||
seed_set = set(seeds or [])
|
||||
ordered = [n for n in (seeds or []) if n in nodes] + \
|
||||
sorted(nodes - seed_set, key=lambda n: G.degree(n), reverse=True)
|
||||
for nid in ordered:
|
||||
d = G.nodes[nid]
|
||||
line = f"NODE {sanitize_label(d.get('label', nid))} [src={d.get('source_file', '')} loc={d.get('source_location', '')} community={d.get('community', '')}]"
|
||||
lines.append(line)
|
||||
for u, v in edges:
|
||||
if u in nodes and v in nodes:
|
||||
d = G.edges[u, v]
|
||||
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))}"
|
||||
raw = G[u][v]
|
||||
d = next(iter(raw.values()), {}) if isinstance(G, (nx.MultiGraph, nx.MultiDiGraph)) else raw
|
||||
context = d.get("context")
|
||||
context_suffix = f" context={context}" if context else ""
|
||||
line = (
|
||||
f"EDGE {sanitize_label(G.nodes[u].get('label', u))} "
|
||||
f"--{d.get('relation', '')} [{d.get('confidence', '')}{context_suffix}]--> "
|
||||
f"{sanitize_label(G.nodes[v].get('label', v))}"
|
||||
)
|
||||
lines.append(line)
|
||||
output = "\n".join(lines)
|
||||
if len(output) > char_budget:
|
||||
@@ -101,11 +190,70 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
|
||||
return output
|
||||
|
||||
|
||||
def _query_graph_text(
|
||||
G: nx.Graph,
|
||||
question: str,
|
||||
*,
|
||||
mode: str = "bfs",
|
||||
depth: int = 3,
|
||||
token_budget: int = 2000,
|
||||
context_filters: list[str] | None = None,
|
||||
) -> str:
|
||||
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."
|
||||
resolved_filters, filter_source = _resolve_context_filters(question, context_filters)
|
||||
traversal_graph = _filter_graph_by_context(G, resolved_filters)
|
||||
nodes, edges = _dfs(traversal_graph, start_nodes, depth) if mode == "dfs" else _bfs(traversal_graph, start_nodes, depth)
|
||||
header_parts = [
|
||||
f"Traversal: {mode.upper()} depth={depth}",
|
||||
f"Start: {[G.nodes[n].get('label', n) for n in start_nodes]}",
|
||||
]
|
||||
if resolved_filters:
|
||||
header_parts.append(f"Context: {', '.join(resolved_filters)} ({filter_source})")
|
||||
header_parts.append(f"{len(nodes)} nodes found")
|
||||
header = " | ".join(header_parts) + "\n\n"
|
||||
return header + _subgraph_to_text(traversal_graph, nodes, edges, token_budget)
|
||||
|
||||
|
||||
def _find_node(G: nx.Graph, label: str) -> list[str]:
|
||||
"""Return node IDs whose label or ID matches the search term (case-insensitive)."""
|
||||
term = label.lower()
|
||||
"""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("label", "").lower() or term == nid.lower()]
|
||||
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:
|
||||
@@ -136,6 +284,11 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
|
||||
"description": "bfs=broad context, dfs=trace a specific path"},
|
||||
"depth": {"type": "integer", "default": 3, "description": "Traversal depth (1-6)"},
|
||||
"token_budget": {"type": "integer", "default": 2000, "description": "Max output tokens"},
|
||||
"context_filter": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Optional explicit edge-context filter, e.g. ['call', 'field']",
|
||||
},
|
||||
},
|
||||
"required": ["question"],
|
||||
},
|
||||
@@ -200,19 +353,20 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
|
||||
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)
|
||||
context_filter = arguments.get("context_filter")
|
||||
return _query_graph_text(
|
||||
G,
|
||||
question,
|
||||
mode=mode,
|
||||
depth=depth,
|
||||
token_budget=budget,
|
||||
context_filters=context_filter,
|
||||
)
|
||||
|
||||
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", "").lower() or label == nid.lower()]
|
||||
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]
|
||||
@@ -256,7 +410,7 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
|
||||
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['edges']} edges" for i, n in enumerate(nodes, 1)]
|
||||
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:
|
||||
@@ -325,6 +479,7 @@ def serve(graph_path: str = "graphify-out/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())
|
||||
|
||||
|
||||
|
||||
+30
-6
@@ -38,7 +38,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
|
||||
|
||||
Three things it does that Claude alone cannot:
|
||||
Three things it does that your AI assistant alone cannot:
|
||||
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
|
||||
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
|
||||
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
|
||||
@@ -157,7 +157,7 @@ After transcription:
|
||||
|
||||
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
|
||||
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
@@ -235,7 +235,7 @@ Process each file one at a time. For each file:
|
||||
- INFERRED: reasonable inference (shared structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain — flag it, do not omit
|
||||
- Code files: semantic edges AST cannot find. Do not re-extract imports.
|
||||
- Doc/paper files: named concepts, entities, citations, and rationale nodes (WHY decisions were made → `rationale_for` edges)
|
||||
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms). Do NOT invent file_types like `concept`. When adding `calls` edges: source is caller, target is callee.
|
||||
- Image files: use vision — understand what the image IS, not just OCR
|
||||
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
|
||||
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
|
||||
@@ -244,7 +244,7 @@ Process each file one at a time. For each file:
|
||||
3. Accumulate results across all files
|
||||
|
||||
Schema for each file's output:
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image|rationale","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
|
||||
After processing all files, write the accumulated result to `.graphify_semantic_new.json`.
|
||||
|
||||
@@ -254,6 +254,30 @@ For the accumulated result:
|
||||
|
||||
If more than half the chunks failed, stop and tell the user.
|
||||
|
||||
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
|
||||
all_nodes, all_edges, all_hyperedges = [], [], []
|
||||
total_in, total_out = 0, 0
|
||||
for c in chunks:
|
||||
d = json.loads(Path(c).read_text())
|
||||
all_nodes += d.get('nodes', [])
|
||||
all_edges += d.get('edges', [])
|
||||
all_hyperedges += d.get('hyperedges', [])
|
||||
total_in += d.get('input_tokens', 0)
|
||||
total_out += d.get('output_tokens', 0)
|
||||
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
|
||||
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
|
||||
'input_tokens': total_in, 'output_tokens': total_out,
|
||||
}, indent=2))
|
||||
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
|
||||
"
|
||||
```
|
||||
|
||||
Save new results to cache:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
@@ -641,7 +665,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
|
||||
"
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_chunk_*.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -1117,7 +1141,7 @@ Supported URL types (auto-detected):
|
||||
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
|
||||
- arXiv → abstract + metadata saved as `.md`
|
||||
- PDF → downloaded as `.pdf`
|
||||
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
|
||||
- Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
|
||||
- Any webpage → converted to markdown via html2text
|
||||
|
||||
---
|
||||
|
||||
+30
-6
@@ -38,7 +38,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
|
||||
|
||||
Three things it does that Claude alone cannot:
|
||||
Three things it does that your AI assistant alone cannot:
|
||||
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
|
||||
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
|
||||
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
|
||||
@@ -157,7 +157,7 @@ After transcription:
|
||||
|
||||
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
|
||||
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
@@ -235,7 +235,7 @@ Process each file one at a time. For each file:
|
||||
- INFERRED: reasonable inference (shared structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain — flag it, do not omit
|
||||
- Code files: semantic edges AST cannot find. Do not re-extract imports.
|
||||
- Doc/paper files: named concepts, entities, citations, and rationale nodes (WHY decisions were made → `rationale_for` edges)
|
||||
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms). Do NOT invent file_types like `concept`. When adding `calls` edges: source is caller, target is callee.
|
||||
- Image files: use vision — understand what the image IS, not just OCR
|
||||
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
|
||||
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
|
||||
@@ -244,7 +244,7 @@ Process each file one at a time. For each file:
|
||||
3. Accumulate results across all files
|
||||
|
||||
Schema for each file's output:
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image|rationale","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
|
||||
After processing all files, write the accumulated result to `.graphify_semantic_new.json`.
|
||||
|
||||
@@ -254,6 +254,30 @@ For the accumulated result:
|
||||
|
||||
If more than half the chunks failed, stop and tell the user.
|
||||
|
||||
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
|
||||
all_nodes, all_edges, all_hyperedges = [], [], []
|
||||
total_in, total_out = 0, 0
|
||||
for c in chunks:
|
||||
d = json.loads(Path(c).read_text())
|
||||
all_nodes += d.get('nodes', [])
|
||||
all_edges += d.get('edges', [])
|
||||
all_hyperedges += d.get('hyperedges', [])
|
||||
total_in += d.get('input_tokens', 0)
|
||||
total_out += d.get('output_tokens', 0)
|
||||
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
|
||||
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
|
||||
'input_tokens': total_in, 'output_tokens': total_out,
|
||||
}, indent=2))
|
||||
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
|
||||
"
|
||||
```
|
||||
|
||||
Save new results to cache:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
@@ -641,7 +665,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
|
||||
"
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_chunk_*.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -1117,7 +1141,7 @@ Supported URL types (auto-detected):
|
||||
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
|
||||
- arXiv → abstract + metadata saved as `.md`
|
||||
- PDF → downloaded as `.pdf`
|
||||
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
|
||||
- Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
|
||||
- Any webpage → converted to markdown via html2text
|
||||
|
||||
---
|
||||
|
||||
+37
-10
@@ -38,7 +38,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
|
||||
|
||||
Three things it does that Claude alone cannot:
|
||||
Three things it does that your AI assistant alone cannot:
|
||||
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
|
||||
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
|
||||
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
|
||||
@@ -156,7 +156,7 @@ After transcription:
|
||||
|
||||
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
|
||||
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
@@ -230,7 +230,7 @@ Load files from `.graphify_uncached.txt`. Split into chunks of 20-25 files each.
|
||||
|
||||
**Step B2 - Dispatch ALL subagents in a single message (Codex)**
|
||||
|
||||
> **Codex platform:** Uses `spawn_agent` + `wait` + `close_agent` instead of the Agent tool.
|
||||
> **Codex platform:** Uses `spawn_agent` + `wait_agent` + `close_agent` instead of the Agent tool.
|
||||
> Requires `multi_agent = true` under `[features]` in `~/.codex/config.toml`.
|
||||
> If `spawn_agent` is unavailable, tell the user to add that config and restart Codex.
|
||||
|
||||
@@ -242,7 +242,7 @@ spawn_agent(agent_type="worker", message="Your task is to perform the following.
|
||||
|
||||
After all agents are dispatched, collect results sequentially:
|
||||
```
|
||||
result = wait(handle); close_agent(handle) # repeat per handle
|
||||
result = wait_agent(handle); close_agent(handle) # repeat per handle
|
||||
```
|
||||
|
||||
Parse each result as JSON. Accumulate nodes/edges/hyperedges across all results and write to `.graphify_semantic_new.json`.
|
||||
@@ -263,7 +263,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
@@ -299,16 +300,42 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image|rationale","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
```
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
|
||||
Wait for all subagents. For each result:
|
||||
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
|
||||
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
|
||||
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
|
||||
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
|
||||
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
|
||||
|
||||
If more than half the chunks failed, stop and tell the user.
|
||||
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
|
||||
|
||||
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
|
||||
all_nodes, all_edges, all_hyperedges = [], [], []
|
||||
total_in, total_out = 0, 0
|
||||
for c in chunks:
|
||||
d = json.loads(Path(c).read_text())
|
||||
all_nodes += d.get('nodes', [])
|
||||
all_edges += d.get('edges', [])
|
||||
all_hyperedges += d.get('hyperedges', [])
|
||||
total_in += d.get('input_tokens', 0)
|
||||
total_out += d.get('output_tokens', 0)
|
||||
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
|
||||
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
|
||||
'input_tokens': total_in, 'output_tokens': total_out,
|
||||
}, indent=2))
|
||||
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
|
||||
"
|
||||
```
|
||||
|
||||
Save new results to cache:
|
||||
```bash
|
||||
@@ -697,7 +724,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
|
||||
"
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_chunk_*.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -1173,7 +1200,7 @@ Supported URL types (auto-detected):
|
||||
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
|
||||
- arXiv → abstract + metadata saved as `.md`
|
||||
- PDF → downloaded as `.pdf`
|
||||
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
|
||||
- Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
|
||||
- Any webpage → converted to markdown via html2text
|
||||
|
||||
---
|
||||
|
||||
@@ -40,7 +40,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
|
||||
|
||||
Three things it does that Claude alone cannot:
|
||||
Three things it does that your AI assistant alone cannot:
|
||||
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
|
||||
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
|
||||
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
|
||||
@@ -159,7 +159,7 @@ After transcription:
|
||||
|
||||
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
|
||||
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
@@ -259,7 +259,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
@@ -295,16 +296,42 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image|rationale","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
```
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
|
||||
Wait for all subagents. For each result:
|
||||
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
|
||||
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
|
||||
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
|
||||
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
|
||||
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
|
||||
|
||||
If more than half the chunks failed, stop and tell the user.
|
||||
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
|
||||
|
||||
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
|
||||
all_nodes, all_edges, all_hyperedges = [], [], []
|
||||
total_in, total_out = 0, 0
|
||||
for c in chunks:
|
||||
d = json.loads(Path(c).read_text())
|
||||
all_nodes += d.get('nodes', [])
|
||||
all_edges += d.get('edges', [])
|
||||
all_hyperedges += d.get('hyperedges', [])
|
||||
total_in += d.get('input_tokens', 0)
|
||||
total_out += d.get('output_tokens', 0)
|
||||
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
|
||||
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
|
||||
'input_tokens': total_in, 'output_tokens': total_out,
|
||||
}, indent=2))
|
||||
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
|
||||
"
|
||||
```
|
||||
|
||||
Save new results to cache:
|
||||
```bash
|
||||
@@ -697,7 +724,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
|
||||
"
|
||||
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_labels.json
|
||||
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_labels.json graphify-out/.graphify_chunk_*.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -1199,7 +1226,7 @@ Supported URL types (auto-detected):
|
||||
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
|
||||
- arXiv → abstract + metadata saved as `.md`
|
||||
- PDF → downloaded as `.pdf`
|
||||
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
|
||||
- Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
|
||||
- Any webpage → converted to markdown via html2text
|
||||
|
||||
---
|
||||
|
||||
+35
-8
@@ -38,7 +38,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
|
||||
|
||||
Three things it does that Claude alone cannot:
|
||||
Three things it does that your AI assistant alone cannot:
|
||||
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
|
||||
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
|
||||
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
|
||||
@@ -157,7 +157,7 @@ After transcription:
|
||||
|
||||
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
|
||||
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
@@ -260,7 +260,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
@@ -296,16 +297,42 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image|rationale","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
```
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
|
||||
Wait for all subagents. For each result:
|
||||
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
|
||||
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
|
||||
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
|
||||
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
|
||||
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
|
||||
|
||||
If more than half the chunks failed, stop and tell the user.
|
||||
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
|
||||
|
||||
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
|
||||
all_nodes, all_edges, all_hyperedges = [], [], []
|
||||
total_in, total_out = 0, 0
|
||||
for c in chunks:
|
||||
d = json.loads(Path(c).read_text())
|
||||
all_nodes += d.get('nodes', [])
|
||||
all_edges += d.get('edges', [])
|
||||
all_hyperedges += d.get('hyperedges', [])
|
||||
total_in += d.get('input_tokens', 0)
|
||||
total_out += d.get('output_tokens', 0)
|
||||
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
|
||||
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
|
||||
'input_tokens': total_in, 'output_tokens': total_out,
|
||||
}, indent=2))
|
||||
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
|
||||
"
|
||||
```
|
||||
|
||||
Save new results to cache:
|
||||
```bash
|
||||
@@ -694,7 +721,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
|
||||
"
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_chunk_*.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -1170,7 +1197,7 @@ Supported URL types (auto-detected):
|
||||
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
|
||||
- arXiv → abstract + metadata saved as `.md`
|
||||
- PDF → downloaded as `.pdf`
|
||||
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
|
||||
- Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
|
||||
- Any webpage → converted to markdown via html2text
|
||||
|
||||
---
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+177
-96
@@ -38,7 +38,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
|
||||
|
||||
Three things it does that Claude alone cannot:
|
||||
Three things it does that your AI assistant alone cannot:
|
||||
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
|
||||
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
|
||||
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
|
||||
@@ -72,22 +72,24 @@ fi
|
||||
# Write interpreter path for all subsequent steps
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
# Force UTF-8 I/O on Windows (prevents garbled CJK/non-ASCII output)
|
||||
export PYTHONUTF8=1
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
|
||||
**In every subsequent bash block, replace `python3` with `$(cat .graphify_python)` to use the correct interpreter.**
|
||||
**In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
|
||||
|
||||
### Step 2 - Detect files
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
result = detect(Path('INPUT_PATH'))
|
||||
print(json.dumps(result))
|
||||
" > .graphify_detect.json
|
||||
" > graphify-out/.graphify_detect.json
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
@@ -157,7 +159,7 @@ After transcription:
|
||||
|
||||
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
|
||||
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
@@ -168,23 +170,23 @@ Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is determin
|
||||
For any code files detected, run AST extraction in parallel with Part B subagents:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.extract import collect_files, extract
|
||||
from pathlib import Path
|
||||
import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
if code_files:
|
||||
result = extract(code_files)
|
||||
Path('.graphify_ast.json').write_text(json.dumps(result, indent=2))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2))
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
Path('.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
|
||||
print('No code files - skipping AST extraction')
|
||||
"
|
||||
```
|
||||
@@ -196,7 +198,7 @@ else:
|
||||
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
|
||||
|
||||
Before dispatching subagents, print a timing estimate:
|
||||
- Load `total_words` and file counts from `.graphify_detect.json`
|
||||
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
|
||||
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
|
||||
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
|
||||
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
|
||||
@@ -206,28 +208,28 @@ Before dispatching subagents, print a timing estimate:
|
||||
Before dispatching any subagents, check which files already have cached extraction results:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.cache import check_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
all_files = [f for files in detect['files'].values() for f in files]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
|
||||
|
||||
if cached_nodes or cached_edges or cached_hyperedges:
|
||||
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
|
||||
Path('.graphify_uncached.txt').write_text('\n'.join(uncached))
|
||||
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
|
||||
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached))
|
||||
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
|
||||
"
|
||||
```
|
||||
|
||||
Only dispatch subagents for files listed in `.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
|
||||
Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
|
||||
|
||||
**Step B1 - Split into chunks**
|
||||
|
||||
Load files from `.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
|
||||
Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
|
||||
|
||||
**Step B2 - Dispatch ALL subagents in a single message (OpenCode)**
|
||||
|
||||
@@ -241,7 +243,7 @@ Dispatch one `@mention` per chunk — ALL in the same response:
|
||||
@agent Chunk 2 of TOTAL_CHUNKS: [next chunk]
|
||||
```
|
||||
|
||||
Wait for all agents to return. Parse each response as JSON. Accumulate nodes/edges/hyperedges across all results and write to `.graphify_semantic_new.json`.
|
||||
Wait for all agents to return. Parse each response as JSON. Accumulate nodes/edges/hyperedges across all results and write to `graphify-out/.graphify_semantic_new.json`.
|
||||
|
||||
The extraction prompt each agent receives (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE):
|
||||
|
||||
@@ -259,7 +261,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
@@ -295,38 +298,64 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image|rationale","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
```
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
|
||||
Wait for all subagents. For each result:
|
||||
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
|
||||
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
|
||||
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
|
||||
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
|
||||
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
|
||||
|
||||
If more than half the chunks failed, stop and tell the user.
|
||||
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
|
||||
|
||||
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
|
||||
all_nodes, all_edges, all_hyperedges = [], [], []
|
||||
total_in, total_out = 0, 0
|
||||
for c in chunks:
|
||||
d = json.loads(Path(c).read_text())
|
||||
all_nodes += d.get('nodes', [])
|
||||
all_edges += d.get('edges', [])
|
||||
all_hyperedges += d.get('hyperedges', [])
|
||||
total_in += d.get('input_tokens', 0)
|
||||
total_out += d.get('output_tokens', 0)
|
||||
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
|
||||
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
|
||||
'input_tokens': total_in, 'output_tokens': total_out,
|
||||
}, indent=2))
|
||||
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
|
||||
"
|
||||
```
|
||||
|
||||
Save new results to cache:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.cache import save_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text()) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
|
||||
print(f'Cached {saved} files')
|
||||
"
|
||||
```
|
||||
|
||||
Merge cached + new results into `.graphify_semantic.json`:
|
||||
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
cached = json.loads(Path('.graphify_cached.json').read_text()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text()) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text()) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
|
||||
all_nodes = cached['nodes'] + new.get('nodes', [])
|
||||
all_edges = cached['edges'] + new.get('edges', [])
|
||||
@@ -345,21 +374,21 @@ merged = {
|
||||
'input_tokens': new.get('input_tokens', 0),
|
||||
'output_tokens': new.get('output_tokens', 0),
|
||||
}
|
||||
Path('.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
|
||||
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
|
||||
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
|
||||
"
|
||||
```
|
||||
Clean up temp files: `rm -f .graphify_cached.json .graphify_uncached.txt .graphify_semantic_new.json`
|
||||
Clean up temp files: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json`
|
||||
|
||||
#### Part C - Merge AST + semantic into final extraction
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from pathlib import Path
|
||||
|
||||
ast = json.loads(Path('.graphify_ast.json').read_text())
|
||||
sem = json.loads(Path('.graphify_semantic.json').read_text())
|
||||
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text())
|
||||
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text())
|
||||
|
||||
# Merge: AST nodes first, semantic nodes deduplicated by id
|
||||
seen = {n['id'] for n in ast['nodes']}
|
||||
@@ -378,7 +407,7 @@ merged = {
|
||||
'input_tokens': sem.get('input_tokens', 0),
|
||||
'output_tokens': sem.get('output_tokens', 0),
|
||||
}
|
||||
Path('.graphify_extract.json').write_text(json.dumps(merged, indent=2))
|
||||
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2))
|
||||
total = len(merged_nodes)
|
||||
edges = len(merged_edges)
|
||||
print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
|
||||
@@ -389,7 +418,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
@@ -398,8 +427,8 @@ from graphify.report import generate
|
||||
from graphify.export import to_json
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = cluster(G)
|
||||
@@ -422,7 +451,7 @@ analysis = {
|
||||
'surprises': surprises,
|
||||
'questions': questions,
|
||||
}
|
||||
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
if G.number_of_nodes() == 0:
|
||||
print('ERROR: Graph is empty - extraction produced no nodes.')
|
||||
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
|
||||
@@ -437,12 +466,12 @@ Replace INPUT_PATH with the actual path.
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
Read `.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
|
||||
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
|
||||
|
||||
Then regenerate the report and save the labels for the visualizer:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import score_all
|
||||
@@ -450,9 +479,9 @@ from graphify.analyze import god_nodes, surprising_connections, suggest_question
|
||||
from graphify.report import generate
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -467,7 +496,7 @@ questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
|
||||
print('Report updated with community labels')
|
||||
"
|
||||
```
|
||||
@@ -482,15 +511,15 @@ Replace INPUT_PATH with the actual path.
|
||||
If `--obsidian` was given:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_obsidian, to_canvas
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -513,40 +542,92 @@ print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries
|
||||
Generate the HTML graph (always, unless `--no-viz`):
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_html
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
labels = {int(k): v for k, v in labels_raw.items()}
|
||||
|
||||
if G.number_of_nodes() > 5000:
|
||||
print(f'Graph has {G.number_of_nodes()} nodes - too large for HTML viz. Use Obsidian vault instead.')
|
||||
NODE_LIMIT = 5000
|
||||
if G.number_of_nodes() > NODE_LIMIT:
|
||||
from collections import Counter
|
||||
print(f'Graph has {G.number_of_nodes()} nodes (above {NODE_LIMIT} limit). Building aggregated community view...')
|
||||
node_to_community = {nid: cid for cid, members in communities.items() for nid in members}
|
||||
import networkx as nx_meta
|
||||
meta = nx_meta.Graph()
|
||||
for cid, members in communities.items():
|
||||
meta.add_node(str(cid), label=labels.get(cid, f'Community {cid}'))
|
||||
edge_counts = Counter()
|
||||
for u, v in G.edges():
|
||||
cu, cv = node_to_community.get(u), node_to_community.get(v)
|
||||
if cu is not None and cv is not None and cu != cv:
|
||||
edge_counts[(min(cu, cv), max(cu, cv))] += 1
|
||||
for (cu, cv), w in edge_counts.items():
|
||||
meta.add_edge(str(cu), str(cv), weight=w, relation=f'{w} cross-community edges', confidence='AGGREGATED')
|
||||
if meta.number_of_nodes() > 1:
|
||||
meta_communities = {cid: [str(cid)] for cid in communities}
|
||||
member_counts = {cid: len(members) for cid, members in communities.items()}
|
||||
to_html(meta, meta_communities, 'graphify-out/graph.html', community_labels=labels or None, member_counts=member_counts)
|
||||
print(f'graph.html written (aggregated: {meta.number_of_nodes()} community nodes, {meta.number_of_edges()} cross-community edges)')
|
||||
print('Tip: run with --obsidian for full node-level detail.')
|
||||
else:
|
||||
print('Single community — aggregated view not useful. Skipping graph.html.')
|
||||
else:
|
||||
to_html(G, communities, 'graphify-out/graph.html', community_labels=labels or None)
|
||||
print('graph.html written - open in any browser, no server needed')
|
||||
"
|
||||
```
|
||||
|
||||
### Step 6b - Wiki (only if --wiki flag)
|
||||
|
||||
**Only run this step if `--wiki` was explicitly given in the original command.**
|
||||
|
||||
Run this before Step 9 (cleanup) so `graphify-out/.graphify_labels.json` is still available.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.wiki import to_wiki
|
||||
from graphify.analyze import god_nodes
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
labels = {int(k): v for k, v in labels_raw.items()}
|
||||
gods = god_nodes(G)
|
||||
|
||||
n = to_wiki(G, communities, 'graphify-out/wiki', community_labels=labels or None, cohesion=cohesion, god_nodes_data=gods)
|
||||
print(f'Wiki: {n} articles written to graphify-out/wiki/')
|
||||
print(' graphify-out/wiki/index.md -> agent entry point')
|
||||
"
|
||||
```
|
||||
|
||||
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
|
||||
|
||||
**If `--neo4j`** - generate a Cypher file for manual import:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_cypher
|
||||
from pathlib import Path
|
||||
|
||||
G = build_from_json(json.loads(Path('.graphify_extract.json').read_text()))
|
||||
G = build_from_json(json.loads(Path('graphify-out/.graphify_extract.json').read_text()))
|
||||
to_cypher(G, 'graphify-out/cypher.txt')
|
||||
print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt')
|
||||
"
|
||||
@@ -555,15 +636,15 @@ print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt'
|
||||
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster
|
||||
from graphify.export import push_to_neo4j
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
|
||||
@@ -577,15 +658,15 @@ Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default
|
||||
### Step 7b - SVG export (only if --svg flag)
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_svg
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -599,14 +680,14 @@ print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
|
||||
### Step 7c - GraphML export (only if --graphml flag)
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_graphml
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -638,15 +719,15 @@ To configure in Claude Desktop, add to `claude_desktop_config.json`:
|
||||
|
||||
### Step 8 - Token reduction benchmark (only if total_words > 5000)
|
||||
|
||||
If `total_words` from `.graphify_detect.json` is greater than 5,000, run:
|
||||
If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.benchmark import run_benchmark, print_benchmark
|
||||
from pathlib import Path
|
||||
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
result = run_benchmark('graphify-out/graph.json', corpus_words=detection['total_words'])
|
||||
print_benchmark(result)
|
||||
"
|
||||
@@ -659,18 +740,18 @@ Print the output directly in chat. If `total_words <= 5000`, skip silently - the
|
||||
### Step 9 - Save manifest, update cost tracker, clean up, and report
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
from graphify.detect import save_manifest
|
||||
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
save_manifest(detect['files'])
|
||||
|
||||
# Update cumulative cost tracker
|
||||
extract = json.loads(Path('.graphify_extract.json').read_text())
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
output_tok = extract.get('output_tokens', 0)
|
||||
|
||||
@@ -693,7 +774,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
|
||||
"
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json
|
||||
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_labels.json graphify-out/.graphify_chunk_*.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -733,7 +814,7 @@ The graph is the map. Your job after the pipeline is to be the guide.
|
||||
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.detect import detect_incremental, save_manifest
|
||||
from pathlib import Path
|
||||
@@ -741,7 +822,7 @@ from pathlib import Path
|
||||
result = detect_incremental(Path('INPUT_PATH'))
|
||||
new_total = result.get('new_total', 0)
|
||||
print(json.dumps(result, indent=2))
|
||||
Path('.graphify_incremental.json').write_text(json.dumps(result))
|
||||
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result))
|
||||
if new_total == 0:
|
||||
print('No files changed since last run. Nothing to update.')
|
||||
raise SystemExit(0)
|
||||
@@ -752,11 +833,11 @@ print(f'{new_total} new/changed file(s) to re-extract.')
|
||||
If new files exist, first check whether all changed files are code files:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
result = json.loads(open('.graphify_incremental.json').read()) if Path('.graphify_incremental.json').exists() else {}
|
||||
result = json.loads(open('graphify-out/.graphify_incremental.json').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {}
|
||||
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts'}
|
||||
new_files = result.get('new_files', {})
|
||||
all_changed = [f for files in new_files.values() for f in files]
|
||||
@@ -772,7 +853,7 @@ If `code_only` is False (any changed file is a doc/paper/image): run the full St
|
||||
Then:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_json
|
||||
@@ -785,7 +866,7 @@ existing_data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
G_existing = json_graph.node_link_graph(existing_data, edges='links')
|
||||
|
||||
# Load new extraction
|
||||
new_extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
G_new = build_from_json(new_extraction)
|
||||
|
||||
# Merge: new nodes/edges into existing graph
|
||||
@@ -799,7 +880,7 @@ Then run Steps 4–8 on the merged graph as normal.
|
||||
After Step 4, show the graph diff:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.analyze import graph_diff
|
||||
from graphify.build import build_from_json
|
||||
@@ -808,8 +889,8 @@ import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
# Load old graph (before update) from backup written before merge
|
||||
old_data = json.loads(Path('.graphify_old.json').read_text()) if Path('.graphify_old.json').exists() else None
|
||||
new_extract = json.loads(Path('.graphify_extract.json').read_text())
|
||||
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text()) if Path('graphify-out/.graphify_old.json').exists() else None
|
||||
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
G_new = build_from_json(new_extract)
|
||||
|
||||
if old_data:
|
||||
@@ -823,8 +904,8 @@ if old_data:
|
||||
"
|
||||
```
|
||||
|
||||
Before the merge step, save the old graph: `cp graphify-out/graph.json .graphify_old.json`
|
||||
Clean up after: `rm -f .graphify_old.json`
|
||||
Before the merge step, save the old graph: `cp graphify-out/graph.json graphify-out/.graphify_old.json`
|
||||
Clean up after: `rm -f graphify-out/.graphify_old.json`
|
||||
|
||||
---
|
||||
|
||||
@@ -833,7 +914,7 @@ Clean up after: `rm -f .graphify_old.json`
|
||||
Skip Steps 1–3. Load the existing graph from `graphify-out/graph.json` and re-run clustering:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections
|
||||
@@ -866,7 +947,7 @@ analysis = {
|
||||
'gods': gods,
|
||||
'surprises': surprises,
|
||||
}
|
||||
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
print(f'Re-clustered: {len(communities)} communities')
|
||||
"
|
||||
```
|
||||
@@ -886,7 +967,7 @@ Two traversal modes - choose based on the question:
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -904,7 +985,7 @@ Load `graphify-out/graph.json`, then:
|
||||
5. If the graph lacks enough information, say so - do not hallucinate edges.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
@@ -995,7 +1076,7 @@ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`,
|
||||
After writing the answer, save it back into the graph so it improves future queries:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
|
||||
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
|
||||
```
|
||||
|
||||
Replace `QUESTION` with the question, `ANSWER` with your full answer text, `SOURCE_NODES` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
|
||||
@@ -1008,7 +1089,7 @@ Find the shortest path between two named concepts in the graph.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -1018,7 +1099,7 @@ if not Path('graphify-out/graph.json').exists():
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
@@ -1070,7 +1151,7 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
|
||||
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1081,7 +1162,7 @@ Give a plain-language explanation of a single node - everything connected to it.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -1091,7 +1172,7 @@ if not Path('graphify-out/graph.json').exists():
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
@@ -1136,7 +1217,7 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
|
||||
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1146,7 +1227,7 @@ $(cat .graphify_python) -m graphify save-result --question "Explain NODE_NAME" -
|
||||
Fetch a URL and add it to the corpus, then update the graph.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys
|
||||
from graphify.ingest import ingest
|
||||
from pathlib import Path
|
||||
@@ -1169,7 +1250,7 @@ Supported URL types (auto-detected):
|
||||
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
|
||||
- arXiv → abstract + metadata saved as `.md`
|
||||
- PDF → downloaded as `.pdf`
|
||||
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
|
||||
- Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
|
||||
- Any webpage → converted to markdown via html2text
|
||||
|
||||
---
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+32
-5
@@ -250,7 +250,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
@@ -286,7 +287,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image|rationale","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
```
|
||||
|
||||
After all subagents complete, collect their results. For each result:
|
||||
@@ -298,10 +299,36 @@ Accumulate nodes/edges/hyperedges across all results and write to `.graphify_sem
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
|
||||
Wait for all subagents. For each result:
|
||||
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
|
||||
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
|
||||
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
|
||||
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
|
||||
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
|
||||
|
||||
If more than half the chunks failed, stop and tell the user.
|
||||
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
|
||||
|
||||
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
|
||||
all_nodes, all_edges, all_hyperedges = [], [], []
|
||||
total_in, total_out = 0, 0
|
||||
for c in chunks:
|
||||
d = json.loads(Path(c).read_text())
|
||||
all_nodes += d.get('nodes', [])
|
||||
all_edges += d.get('edges', [])
|
||||
all_hyperedges += d.get('hyperedges', [])
|
||||
total_in += d.get('input_tokens', 0)
|
||||
total_out += d.get('output_tokens', 0)
|
||||
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
|
||||
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
|
||||
'input_tokens': total_in, 'output_tokens': total_out,
|
||||
}, indent=2))
|
||||
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
|
||||
"
|
||||
```
|
||||
|
||||
Save new results to cache:
|
||||
```bash
|
||||
@@ -672,7 +699,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
|
||||
"
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_chunk_*.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
---
|
||||
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.
|
||||
total_in, total_out = 0, 0
|
||||
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', []))
|
||||
total_in += chunk.get('input_tokens', 0)
|
||||
total_out += chunk.get('output_tokens', 0)
|
||||
|
||||
merged = {'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges, 'input_tokens': total_in, 'output_tokens': total_out}
|
||||
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.
|
||||
+63
-11
@@ -41,7 +41,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
|
||||
|
||||
Three things it does that Claude alone cannot:
|
||||
Three things it does that your AI assistant alone cannot:
|
||||
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
|
||||
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
|
||||
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
|
||||
@@ -149,7 +149,7 @@ After transcription:
|
||||
|
||||
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
|
||||
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (your AI model, costs tokens).
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
@@ -249,7 +249,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
@@ -278,23 +279,55 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image|rationale","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
```
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
|
||||
Wait for all subagents. For each result:
|
||||
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
|
||||
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
|
||||
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
|
||||
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
|
||||
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
|
||||
|
||||
If more than half the chunks failed, stop and tell the user.
|
||||
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
|
||||
|
||||
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
|
||||
all_nodes, all_edges, all_hyperedges = [], [], []
|
||||
total_in, total_out = 0, 0
|
||||
for c in chunks:
|
||||
d = json.loads(Path(c).read_text())
|
||||
all_nodes += d.get('nodes', [])
|
||||
all_edges += d.get('edges', [])
|
||||
all_hyperedges += d.get('hyperedges', [])
|
||||
total_in += d.get('input_tokens', 0)
|
||||
total_out += d.get('output_tokens', 0)
|
||||
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
|
||||
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
|
||||
'input_tokens': total_in, 'output_tokens': total_out,
|
||||
}, indent=2))
|
||||
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
|
||||
"
|
||||
```
|
||||
|
||||
Save new results to cache:
|
||||
```powershell
|
||||
@@ -782,9 +815,28 @@ G_existing = json_graph.node_link_graph(existing_data, edges='links')
|
||||
new_extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
G_new = build_from_json(new_extraction)
|
||||
|
||||
# Prune nodes from deleted files
|
||||
incremental = json.loads(Path('.graphify_incremental.json').read_text())
|
||||
deleted = set(incremental.get('deleted_files', []))
|
||||
if deleted:
|
||||
to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted]
|
||||
G_existing.remove_nodes_from(to_remove)
|
||||
if to_remove:
|
||||
print(f'Pruned {len(to_remove)} ghost node(s) from {len(deleted)} deleted file(s) — drift detected and corrected.')
|
||||
else:
|
||||
print(f'{len(deleted)} file(s) deleted since last run, but no ghost nodes were present in the graph — no drift.')
|
||||
|
||||
# Merge: new nodes/edges into existing graph
|
||||
G_existing.update(G_new)
|
||||
print(f'Merged: {G_existing.number_of_nodes()} nodes, {G_existing.number_of_edges()} edges')
|
||||
|
||||
# Save manifest with the CURRENT full file list so the next --update
|
||||
# diffs against today's filesystem state, not the prior --update's
|
||||
# baseline. Without this, deleted files get reported as ghosts again
|
||||
# on every subsequent --update until a full rebuild runs.
|
||||
from graphify.detect import save_manifest
|
||||
save_manifest(incremental['files'])
|
||||
print('[graphify update] Manifest saved.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -1163,7 +1215,7 @@ Supported URL types (auto-detected):
|
||||
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
|
||||
- arXiv → abstract + metadata saved as `.md`
|
||||
- PDF → downloaded as `.pdf`
|
||||
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
|
||||
- Images (.png/.jpg/.webp) → downloaded, vision extraction runs on next build
|
||||
- Any webpage → converted to markdown via html2text
|
||||
|
||||
---
|
||||
|
||||
+180
-26
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: graphify
|
||||
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
|
||||
description: "any input (code, docs, papers, images, videos) to knowledge graph. Use when user asks any question about a codebase, documents, or project content - especially if graphify-out/ exists, treat the question as a /graphify query."
|
||||
trigger: /graphify
|
||||
---
|
||||
|
||||
@@ -13,6 +13,9 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
```
|
||||
/graphify # full pipeline on current directory → Obsidian vault
|
||||
/graphify <path> # full pipeline on specific path
|
||||
/graphify https://github.com/<owner>/<repo> # clone repo then run full pipeline on it
|
||||
/graphify https://github.com/<owner>/<repo> --branch <branch> # clone a specific branch
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
@@ -57,25 +60,60 @@ Use it for:
|
||||
|
||||
If no path was given, use `.` (current directory). Do not ask the user for a path.
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL — run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
|
||||
### Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given)
|
||||
|
||||
**Single repo:**
|
||||
```bash
|
||||
LOCAL_PATH=$(graphify clone <github-url> [--branch <branch>])
|
||||
# Use LOCAL_PATH as the target for all subsequent steps
|
||||
```
|
||||
|
||||
**Multiple repos (cross-repo graph):**
|
||||
```bash
|
||||
# Clone each repo, run the full pipeline on each, then merge
|
||||
graphify clone <url1> # → ~/.graphify/repos/<owner1>/<repo1>
|
||||
graphify clone <url2> # → ~/.graphify/repos/<owner2>/<repo2>
|
||||
# Run /graphify on each local path to produce their graph.json files
|
||||
# Then merge:
|
||||
graphify merge-graphs \
|
||||
~/.graphify/repos/<owner1>/<repo1>/graphify-out/graph.json \
|
||||
~/.graphify/repos/<owner2>/<repo2>/graphify-out/graph.json \
|
||||
--out graphify-out/cross-repo-graph.json
|
||||
```
|
||||
|
||||
Graphify clones into `~/.graphify/repos/<owner>/<repo>` and reuses existing clones on repeat runs. Each node in the merged graph carries a `repo` attribute so you can filter by origin.
|
||||
|
||||
### Step 1 - Ensure graphify is installed
|
||||
|
||||
```bash
|
||||
# Detect the correct Python interpreter (handles pipx, venv, system installs)
|
||||
# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs)
|
||||
PYTHON=""
|
||||
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
|
||||
if [ -n "$GRAPHIFY_BIN" ]; then
|
||||
PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
|
||||
case "$PYTHON" in
|
||||
*[!a-zA-Z0-9/_.-]*) PYTHON="python3" ;;
|
||||
esac
|
||||
else
|
||||
PYTHON="python3"
|
||||
# 1. uv tool installs — most reliable on modern Mac/Linux
|
||||
if [ -z "$PYTHON" ] && command -v uv >/dev/null 2>&1; then
|
||||
_UV_PY=$(uv tool run graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
|
||||
if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
|
||||
fi
|
||||
# 2. Read shebang from graphify binary (pipx and direct pip installs)
|
||||
if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then
|
||||
_SHEBANG=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
|
||||
case "$_SHEBANG" in
|
||||
*[!a-zA-Z0-9/_.-]*) ;;
|
||||
*) "$_SHEBANG" -c "import graphify" 2>/dev/null && PYTHON="$_SHEBANG" ;;
|
||||
esac
|
||||
fi
|
||||
# 3. Fall back to python3
|
||||
if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
|
||||
"$PYTHON" -c "import graphify" 2>/dev/null || "$PYTHON" -m pip install graphifyy -q 2>/dev/null || "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
# Write interpreter path for all subsequent steps (persists across invocations)
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
# Save scan root so `graphify update` (no args) knows where to look next time
|
||||
echo "$(cd INPUT_PATH && pwd)" > graphify-out/.graphify_root
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
@@ -162,7 +200,12 @@ After transcription:
|
||||
|
||||
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
|
||||
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (Claude, costs tokens).
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens).
|
||||
|
||||
**Before dispatching subagents:** check whether `MOONSHOT_API_KEY` is set. If it is NOT set, print this one-liner to the user:
|
||||
> Tip: set `MOONSHOT_API_KEY` to use Kimi K2.6 for semantic extraction — 3x cheaper, richer graphs (`pip install 'graphifyy[kimi]'`).
|
||||
|
||||
Print it once, then continue. If `MOONSHOT_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="kimi")` for semantic extraction instead of dispatching Claude subagents.
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
@@ -185,7 +228,7 @@ for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
if code_files:
|
||||
result = extract(code_files)
|
||||
result = extract(code_files, cache_root=Path('.'))
|
||||
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:
|
||||
@@ -238,11 +281,13 @@ Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-2
|
||||
|
||||
Call the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.
|
||||
|
||||
**IMPORTANT - subagent type:** Always use `subagent_type="general-purpose"`. Do NOT use `Explore` - it is read-only and cannot write chunk files to disk, which silently drops extraction results. General-purpose has Write and Bash access which the subagent needs.
|
||||
|
||||
Concrete example for 3 chunks:
|
||||
```
|
||||
[Agent tool call 1: files 1-15]
|
||||
[Agent tool call 2: files 16-30]
|
||||
[Agent tool call 3: files 31-45]
|
||||
[Agent tool call 1: files 1-15, subagent_type="general-purpose"]
|
||||
[Agent tool call 2: files 16-30, subagent_type="general-purpose"]
|
||||
[Agent tool call 3: files 31-45, subagent_type="general-purpose"]
|
||||
```
|
||||
All three in one message. Not three separate messages.
|
||||
|
||||
@@ -262,7 +307,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
@@ -291,23 +337,57 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the filename without extension and entity is the symbol name, both normalized (lowercase, non-alphanumeric chars replaced with `_`). Example: `src/auth/session.py` + `ValidateToken` → `session_validatetoken`. This must match the ID the AST extractor generates so cross-references between code and semantic nodes connect correctly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
```
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
|
||||
Wait for all subagents. For each result:
|
||||
- If a subagent returned valid JSON with `nodes` and `edges`, include it and save each file's nodes/edges to the cache
|
||||
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
|
||||
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
|
||||
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
|
||||
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
|
||||
|
||||
If more than half the chunks failed, stop and tell the user.
|
||||
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
|
||||
|
||||
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
|
||||
all_nodes, all_edges, all_hyperedges = [], [], []
|
||||
total_in, total_out = 0, 0
|
||||
for c in chunks:
|
||||
d = json.loads(Path(c).read_text())
|
||||
all_nodes += d.get('nodes', [])
|
||||
all_edges += d.get('edges', [])
|
||||
all_hyperedges += d.get('hyperedges', [])
|
||||
total_in += d.get('input_tokens', 0)
|
||||
total_out += d.get('output_tokens', 0)
|
||||
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
|
||||
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
|
||||
'input_tokens': total_in, 'output_tokens': total_out,
|
||||
}, indent=2))
|
||||
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
|
||||
"
|
||||
```
|
||||
|
||||
Save new results to cache:
|
||||
```bash
|
||||
@@ -536,14 +616,66 @@ G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
labels = {int(k): v for k, v in labels_raw.items()}
|
||||
|
||||
if G.number_of_nodes() > 5000:
|
||||
print(f'Graph has {G.number_of_nodes()} nodes - too large for HTML viz. Use Obsidian vault instead.')
|
||||
NODE_LIMIT = 5000
|
||||
if G.number_of_nodes() > NODE_LIMIT:
|
||||
from collections import Counter
|
||||
print(f'Graph has {G.number_of_nodes()} nodes (above {NODE_LIMIT} limit). Building aggregated community view...')
|
||||
node_to_community = {nid: cid for cid, members in communities.items() for nid in members}
|
||||
import networkx as nx_meta
|
||||
meta = nx_meta.Graph()
|
||||
for cid, members in communities.items():
|
||||
meta.add_node(str(cid), label=labels.get(cid, f'Community {cid}'))
|
||||
edge_counts = Counter()
|
||||
for u, v in G.edges():
|
||||
cu, cv = node_to_community.get(u), node_to_community.get(v)
|
||||
if cu is not None and cv is not None and cu != cv:
|
||||
edge_counts[(min(cu, cv), max(cu, cv))] += 1
|
||||
for (cu, cv), w in edge_counts.items():
|
||||
meta.add_edge(str(cu), str(cv), weight=w, relation=f'{w} cross-community edges', confidence='AGGREGATED')
|
||||
if meta.number_of_nodes() > 1:
|
||||
meta_communities = {cid: [str(cid)] for cid in communities}
|
||||
member_counts = {cid: len(members) for cid, members in communities.items()}
|
||||
to_html(meta, meta_communities, 'graphify-out/graph.html', community_labels=labels or None, member_counts=member_counts)
|
||||
print(f'graph.html written (aggregated: {meta.number_of_nodes()} community nodes, {meta.number_of_edges()} cross-community edges)')
|
||||
print('Tip: run with --obsidian for full node-level detail.')
|
||||
else:
|
||||
print('Single community — aggregated view not useful. Skipping graph.html.')
|
||||
else:
|
||||
to_html(G, communities, 'graphify-out/graph.html', community_labels=labels or None)
|
||||
print('graph.html written - open in any browser, no server needed')
|
||||
"
|
||||
```
|
||||
|
||||
### Step 6b - Wiki (only if --wiki flag)
|
||||
|
||||
**Only run this step if `--wiki` was explicitly given in the original command.**
|
||||
|
||||
Run this before Step 9 (cleanup) so `.graphify_labels.json` is still available.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.wiki import to_wiki
|
||||
from graphify.analyze import god_nodes
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
labels = {int(k): v for k, v in labels_raw.items()}
|
||||
gods = god_nodes(G)
|
||||
|
||||
n = to_wiki(G, communities, 'graphify-out/wiki', community_labels=labels or None, cohesion=cohesion, god_nodes_data=gods)
|
||||
print(f'Wiki: {n} articles written to graphify-out/wiki/')
|
||||
print(' graphify-out/wiki/index.md -> agent entry point')
|
||||
"
|
||||
```
|
||||
|
||||
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
|
||||
|
||||
**If `--neo4j`** - generate a Cypher file for manual import:
|
||||
@@ -702,7 +834,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
|
||||
"
|
||||
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_labels.json
|
||||
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -821,11 +953,33 @@ deleted = set(incremental.get('deleted_files', []))
|
||||
if deleted:
|
||||
to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted]
|
||||
G_existing.remove_nodes_from(to_remove)
|
||||
print(f'Pruned {len(to_remove)} ghost nodes from {len(deleted)} deleted file(s)')
|
||||
if to_remove:
|
||||
print(f'Pruned {len(to_remove)} ghost node(s) from {len(deleted)} deleted file(s) — drift detected and corrected.')
|
||||
else:
|
||||
print(f'{len(deleted)} file(s) deleted since last run, but no ghost nodes were present in the graph — no drift.')
|
||||
|
||||
# Merge: new nodes/edges into existing graph
|
||||
G_existing.update(G_new)
|
||||
print(f'Merged: {G_existing.number_of_nodes()} nodes, {G_existing.number_of_edges()} edges')
|
||||
|
||||
# Write merged result back to .graphify_extract.json so Step 4 sees the full graph
|
||||
merged_out = {
|
||||
'nodes': [{'id': n, **d} for n, d in G_existing.nodes(data=True)],
|
||||
'edges': [{'source': u, 'target': v, **d} for u, v, d in G_existing.edges(data=True)],
|
||||
'hyperedges': new_extraction.get('hyperedges', []),
|
||||
'input_tokens': new_extraction.get('input_tokens', 0),
|
||||
'output_tokens': new_extraction.get('output_tokens', 0),
|
||||
}
|
||||
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out))
|
||||
print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)')
|
||||
|
||||
# Save manifest with the CURRENT full file list so the next --update
|
||||
# diffs against today's filesystem state, not the prior --update's
|
||||
# baseline. Without this, deleted files get reported as ghosts again
|
||||
# on every subsequent --update until a full rebuild runs.
|
||||
from graphify.detect import save_manifest
|
||||
save_manifest(incremental['files'])
|
||||
print('[graphify update] Manifest saved.')
|
||||
"
|
||||
```
|
||||
|
||||
|
||||
@@ -51,12 +51,14 @@ def download_audio(url: str, output_dir: Path) -> Path:
|
||||
Returns the path to the downloaded audio file (.m4a or .opus).
|
||||
Uses cached file if already downloaded.
|
||||
"""
|
||||
from graphify.security import validate_url
|
||||
validate_url(url) # blocks private IPs, bad schemes before yt-dlp runs
|
||||
yt_dlp = _get_yt_dlp()
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 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]
|
||||
url_hash = hashlib.sha1(url.encode(), usedforsecurity=False).hexdigest()[:12]
|
||||
out_template = str(output_dir / f"yt_{url_hash}.%(ext)s")
|
||||
|
||||
# Check for already-downloaded file
|
||||
|
||||
@@ -0,0 +1,580 @@
|
||||
"""tree_html — emit a D3 v7 collapsible-tree HTML view of a graph.
|
||||
|
||||
A self-contained printable / browseable tree-of-modules view
|
||||
intended to complement the existing force-directed ``graph.html``.
|
||||
Key visual elements:
|
||||
|
||||
* Expand-all / collapse-all / reset-view buttons.
|
||||
* Multi-line label wrapping (``wrapText``) with separately-coloured
|
||||
name and descendant-count.
|
||||
* Depth-based colour palette (top-level directories get distinct
|
||||
accent colours; deeper levels follow a level-specific palette).
|
||||
* Click-to-toggle subtree.
|
||||
|
||||
Tree-data shape:
|
||||
|
||||
{
|
||||
"name": "<root label>",
|
||||
"total_count": <int>,
|
||||
"children": [ { "name", "total_count", "children": [...] }, ... ]
|
||||
}
|
||||
|
||||
CLI: ``graphify tree [--graph PATH] [--output HTML] [--root PATH]
|
||||
[--max-children N] [--label NAME]``.
|
||||
|
||||
Implementation notes:
|
||||
- ``total_count`` is the descendant leaf count, so collapsed nodes
|
||||
can show ``(Total Count: 95)`` without needing the children loaded.
|
||||
- ``--max-children`` (default 200) caps how many children render
|
||||
under any one node; a synthetic ``(+N more)`` leaf appears when the
|
||||
cap fires so very wide directories stay usable.
|
||||
- The first-level palette is auto-populated from the live top-level
|
||||
directories so each gets a stable accent colour.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html as _html
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
DEFAULT_MAX_CHILDREN = 200
|
||||
|
||||
|
||||
# ── Tree builder (filesystem hierarchy → JSON) ──────────────────
|
||||
|
||||
|
||||
def _common_root(paths: List[str]) -> str:
|
||||
if not paths:
|
||||
return ""
|
||||
parts = [Path(p).parts for p in paths if p]
|
||||
if not parts:
|
||||
return ""
|
||||
common = parts[0]
|
||||
for p in parts[1:]:
|
||||
i = 0
|
||||
while i < len(common) and i < len(p) and common[i] == p[i]:
|
||||
i += 1
|
||||
common = common[:i]
|
||||
return str(Path(*common)) if common else ""
|
||||
|
||||
|
||||
def _make_truncation_leaf(extra: int) -> Dict[str, Any]:
|
||||
return {"name": f"(+{extra} more)", "total_count": extra, "children": []}
|
||||
|
||||
|
||||
def build_tree(
|
||||
graph: Dict[str, Any],
|
||||
*,
|
||||
root: Optional[str] = None,
|
||||
max_children: int = DEFAULT_MAX_CHILDREN,
|
||||
project_label: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Build a ``{name, total_count, children}`` hierarchy.
|
||||
|
||||
Each leaf is either a code symbol (class / top-level function) or
|
||||
a synthetic "(+N more)" placeholder for truncated wide directories.
|
||||
Each interior node carries ``total_count = sum of leaf counts``.
|
||||
"""
|
||||
nodes: List[Dict[str, Any]] = list(graph.get("nodes", []))
|
||||
file_nodes = [n for n in nodes if n.get("source_file")]
|
||||
if not file_nodes:
|
||||
return {"name": "(empty graph)", "total_count": 0, "children": []}
|
||||
|
||||
if root is None:
|
||||
root = _common_root([n["source_file"] for n in file_nodes])
|
||||
root_path = Path(root)
|
||||
|
||||
by_file: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
|
||||
for n in file_nodes:
|
||||
by_file[n["source_file"]].append(n)
|
||||
|
||||
# Build dir tree.
|
||||
dir_index: Dict[str, Dict[str, Any]] = {}
|
||||
label_root = project_label or root_path.name or root or "/"
|
||||
root_node: Dict[str, Any] = {
|
||||
"name": label_root, "total_count": 0, "children": [],
|
||||
}
|
||||
dir_index[str(root_path)] = root_node
|
||||
|
||||
def _ensure_dir(abs_path: Path) -> Dict[str, Any]:
|
||||
key = str(abs_path)
|
||||
if key in dir_index:
|
||||
return dir_index[key]
|
||||
if abs_path == abs_path.parent:
|
||||
return root_node
|
||||
parent = (_ensure_dir(abs_path.parent)
|
||||
if abs_path.parent != abs_path else root_node)
|
||||
node = {"name": abs_path.name, "total_count": 0, "children": []}
|
||||
dir_index[key] = node
|
||||
parent["children"].append(node)
|
||||
return node
|
||||
|
||||
for src_file, syms in sorted(by_file.items()):
|
||||
src_path = Path(src_file)
|
||||
try:
|
||||
rel = src_path.relative_to(root_path)
|
||||
parent_path = (root_path / rel).parent
|
||||
except ValueError:
|
||||
parent_path = root_path
|
||||
parent_dir = _ensure_dir(parent_path)
|
||||
|
||||
# File node — children are the symbols.
|
||||
sym_children: List[Dict[str, Any]] = []
|
||||
for n in syms:
|
||||
label = n.get("label", n.get("id", "?"))
|
||||
# Skip the redundant file-name node graphify emits.
|
||||
if label == src_path.name and n.get("file_type") == "code":
|
||||
continue
|
||||
sym_children.append({
|
||||
"name": label,
|
||||
"total_count": 1,
|
||||
"children": [],
|
||||
})
|
||||
# Sort: code symbols first by name, then anything else.
|
||||
sym_children.sort(key=lambda c: (
|
||||
c["name"].startswith("_"),
|
||||
c["name"].lower(),
|
||||
))
|
||||
if len(sym_children) > max_children:
|
||||
extra = len(sym_children) - max_children
|
||||
sym_children = sym_children[:max_children] + [
|
||||
_make_truncation_leaf(extra),
|
||||
]
|
||||
file_node = {
|
||||
"name": src_path.name,
|
||||
"total_count": len(sym_children) or 1,
|
||||
"children": sym_children,
|
||||
}
|
||||
parent_dir["children"].append(file_node)
|
||||
|
||||
# Sort each dir's children + propagate total_count up.
|
||||
def _finalise(d: Dict[str, Any]) -> int:
|
||||
kids = d.get("children") or []
|
||||
kids.sort(key=lambda c: (
|
||||
0 if (c.get("children") and len(c["children"]) > 0) else 1,
|
||||
c["name"].lower(),
|
||||
))
|
||||
if not kids:
|
||||
return d.get("total_count") or 1
|
||||
n = 0
|
||||
for c in kids:
|
||||
n += _finalise(c)
|
||||
d["total_count"] = n or 1
|
||||
return d["total_count"]
|
||||
|
||||
_finalise(root_node)
|
||||
return root_node
|
||||
|
||||
|
||||
# ── HTML emitter (single-data-blob substitution) ──────────────────
|
||||
|
||||
|
||||
# We emit a Python f-string with literal CSS/JS braces escaped as {{ }}.
|
||||
_HTML_TEMPLATE = r"""<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>{title}</title>
|
||||
<style>
|
||||
body {{
|
||||
font-family: 'Segoe UI', sans-serif;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: #f9f9f9;
|
||||
color: #333;
|
||||
}}
|
||||
h1 {{
|
||||
margin: 20px 0 0 24px;
|
||||
font-size: 2.2rem;
|
||||
font-weight: bold;
|
||||
color: #1e3a56;
|
||||
}}
|
||||
.controls {{
|
||||
margin: 20px 0 15px 24px;
|
||||
}}
|
||||
button {{
|
||||
margin-right: 10px;
|
||||
padding: 8px 18px;
|
||||
background: #007bff;
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
font-size: 0.95rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s ease-in-out;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}}
|
||||
button:hover {{
|
||||
background: #0056b3;
|
||||
}}
|
||||
button:active {{
|
||||
background: #004085;
|
||||
}}
|
||||
#tree-container {{
|
||||
width: calc(100vw - 48px); /* Adjust for body margin/padding */
|
||||
height: 85vh;
|
||||
overflow: auto;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
margin-left: 24px;
|
||||
margin-right: 24px;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.08);
|
||||
border: 1px solid #ddd;
|
||||
}}
|
||||
svg {{
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
display: block; /* Important for D3 */
|
||||
}}
|
||||
.node circle {{
|
||||
stroke-width: 2.5px;
|
||||
}}
|
||||
.node text {{ /* Base style for the <text> container */
|
||||
font: 13px 'Segoe UI', sans-serif;
|
||||
paint-order: stroke fill; /* Ensures text is readable over lines */
|
||||
stroke: #fff; /* White halo */
|
||||
stroke-width: 3px; /* Halo thickness */
|
||||
stroke-linejoin: round;
|
||||
stroke-opacity: 0.85; /* Halo opacity */
|
||||
}}
|
||||
.link {{
|
||||
fill: none;
|
||||
stroke-opacity: 0.7;
|
||||
stroke-width: 2px;
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>{header}</h1>
|
||||
<div class="controls">
|
||||
<button onclick="expandAll()">Expand All</button>
|
||||
<button onclick="collapseAll()">Collapse All</button>
|
||||
<button onclick="resetView()">Reset View</button>
|
||||
</div>
|
||||
<div id="tree-container">
|
||||
<svg id="tree-svg" width="{svg_width}" height="{svg_height}"></svg>
|
||||
</div>
|
||||
|
||||
<script src="https://d3js.org/d3.v7.min.js"></script>
|
||||
<script>
|
||||
const initialJsonData = {data_json};
|
||||
|
||||
function transformData(jsonData) {{
|
||||
// Helper function to recursively build the children structure
|
||||
function processNode(node, parentL1StageName) {{
|
||||
let displayName = node.name;
|
||||
// Append total_count if it exists and is not already in the name
|
||||
if (node.total_count !== undefined) {{
|
||||
if (!/\(Total Count: \d+\)$/.test(displayName)) {{
|
||||
displayName += ` (Total Count: ${{node.total_count}})`;
|
||||
}}
|
||||
}}
|
||||
|
||||
const newNode = {{ name: displayName }};
|
||||
|
||||
if (parentL1StageName === "Root") {{
|
||||
newNode.originalStageName = node.name;
|
||||
}} else {{
|
||||
newNode.originalStageName = parentL1StageName;
|
||||
}}
|
||||
|
||||
if (node.children && node.children.length > 0) {{
|
||||
const stageNameToPass = (parentL1StageName === "Root") ? node.name : parentL1StageName;
|
||||
newNode.children = node.children.map(child => processNode(child, stageNameToPass));
|
||||
}}
|
||||
|
||||
return newNode;
|
||||
}}
|
||||
|
||||
let rootDisplayName = jsonData.name;
|
||||
if (jsonData.total_count !== undefined && !/\(Total Count: \d+\)$/.test(rootDisplayName)) {{
|
||||
rootDisplayName += ` (Total Count: ${{jsonData.total_count}})`;
|
||||
}}
|
||||
|
||||
return {{
|
||||
name: rootDisplayName,
|
||||
originalStageName: "Root",
|
||||
children: (jsonData.children || []).map(child => processNode(child, "Root"))
|
||||
}};
|
||||
}}
|
||||
|
||||
const treeData = transformData(initialJsonData);
|
||||
|
||||
// Auto-populated phaseColors: every depth-1 child of the root gets
|
||||
// a stable colour from a bigger palette so all top-level dirs are
|
||||
// distinguishable.
|
||||
const PALETTE = [
|
||||
["#3498DB","#2980B9","#AED6F1"], ["#2ECC71","#27AE60","#A9DFBF"],
|
||||
["#E74C3C","#C0392B","#F5B7B1"], ["#9B59B6","#8E44AD","#D7BDE2"],
|
||||
["#F39C12","#D68910","#FAD7A0"], ["#1ABC9C","#117864","#A2D9CE"],
|
||||
["#34495E","#1B2631","#ABB2B9"], ["#E67E22","#BA4A00","#F5CBA7"],
|
||||
["#16A085","#0E6655","#A2D9CE"], ["#D35400","#A04000","#EDBB99"],
|
||||
["#7F8C8D","#566573","#D5DBDB"], ["#C0392B","#7B241C","#F5B7B1"],
|
||||
["#2E86C1","#1B4F72","#A9CCE3"], ["#28B463","#196F3D","#A9DFBF"],
|
||||
["#AF7AC5","#6C3483","#D2B4DE"],
|
||||
];
|
||||
const phaseColors = {{ "Root": {{ fill: "#4A4A4A", stroke: "#333333", collapsedFill: "#6C757D" }},
|
||||
"Default": {{ fill: "#BDC3C7", stroke: "#95A5A6", collapsedFill: "#ECF0F1" }} }};
|
||||
(initialJsonData.children || []).forEach((c, i) => {{
|
||||
const pal = PALETTE[i % PALETTE.length];
|
||||
phaseColors[c.name] = {{ fill: pal[0], stroke: pal[1], collapsedFill: pal[2] }};
|
||||
}});
|
||||
|
||||
const levelSpecificPalettes = {{
|
||||
0: {{ fill: "#4A4A4A", stroke: "#333333", collapsedFill: "#6C757D" }},
|
||||
2: {{ fill: "#6ab04c", stroke: "#508a38", collapsedFill: "#a3d391" }},
|
||||
3: {{ fill: "#f0932b", stroke: "#d0730f", collapsedFill: "#f6c07e" }},
|
||||
4: {{ fill: "#be2edd", stroke: "#a01cb3", collapsedFill: "#e08bf2" }},
|
||||
5: {{ fill: "#00a8ff", stroke: "#007ac1", collapsedFill: "#74d2ff" }},
|
||||
6: {{ fill: "#e55039", stroke: "#c23620", collapsedFill: "#f09a8d" }},
|
||||
default: {{ fill: "#747d8c", stroke: "#57606f", collapsedFill: "#a4b0be" }}
|
||||
}};
|
||||
|
||||
const svgElement = d3.select("#tree-svg");
|
||||
const initialSvgWidth = +svgElement.attr("width");
|
||||
const initialSvgHeight = +svgElement.attr("height");
|
||||
const margin = {{ top: 40, right: 120, bottom: 80, left: 450 }};
|
||||
let width = initialSvgWidth - margin.left - margin.right;
|
||||
let height = initialSvgHeight - margin.top - margin.bottom;
|
||||
const duration = 500;
|
||||
let nodeCounter = 0;
|
||||
const g = svgElement.append("g").attr("transform", `translate(${{margin.left}},${{margin.top}})`);
|
||||
const treemap = d3.tree().nodeSize([40, 0]);
|
||||
let rootNode = d3.hierarchy(treeData, d => d.children);
|
||||
rootNode.x0 = 0;
|
||||
rootNode.y0 = 0;
|
||||
|
||||
if (rootNode.children) {{
|
||||
rootNode.children.forEach(d_child => {{
|
||||
if (d_child.children) {{ collapseBranch(d_child); }}
|
||||
}});
|
||||
}}
|
||||
updateTree(rootNode);
|
||||
|
||||
function collapseBranch(d) {{ if (d.children) {{ d._children = d.children; d._children.forEach(collapseBranch); d.children = null; }} }}
|
||||
function expandBranch(d) {{ if (d._children) {{ d.children = d._children; d._children = null; }} if (d.children) {{ d.children.forEach(expandBranch); }} }}
|
||||
window.expandAll = () => {{ expandBranch(rootNode); updateTree(rootNode); }};
|
||||
window.collapseAll = () => {{ if (rootNode.children) {{ rootNode.children.forEach(collapseBranch); }} updateTree(rootNode); }};
|
||||
window.resetView = () => {{ if (rootNode.children) {{ rootNode.children.forEach(d_child => {{ if (d_child.children || d_child._children) {{ collapseBranch(d_child); }} }}); }} if (rootNode._children && !rootNode.children) {{ rootNode.children = rootNode._children; rootNode._children = null; }} updateTree(rootNode); }};
|
||||
|
||||
function updateTree(source) {{
|
||||
const treeLayoutData = treemap(rootNode);
|
||||
let nodes = treeLayoutData.descendants();
|
||||
let links = treeLayoutData.descendants().slice(1);
|
||||
|
||||
let minX = 0;
|
||||
let maxX = 0;
|
||||
if (nodes.length > 0) {{
|
||||
minX = d3.min(nodes, d => d.x);
|
||||
maxX = d3.max(nodes, d => d.x);
|
||||
}}
|
||||
|
||||
let neededHeight = Math.max(initialSvgHeight, maxX - minX + margin.top + margin.bottom + 100);
|
||||
svgElement.transition().duration(duration / 2).attr("height", neededHeight);
|
||||
g.transition().duration(duration / 2).attr("transform", `translate(${{margin.left}},${{margin.top - minX + 40}})`);
|
||||
|
||||
nodes.forEach(d => {{ d.y = d.depth * 400; }}); // Adjust horizontal separation if needed
|
||||
|
||||
const node = g.selectAll('g.node').data(nodes, d => d.id || (d.id = ++nodeCounter));
|
||||
const nodeEnter = node.enter().append('g')
|
||||
.attr('class', d => "node" + (d.children || d._children ? " node--internal" : " node--leaf") + (d._children ? " _children" : ""))
|
||||
.attr('transform', d => `translate(${{source.y0}},${{source.x0}})`)
|
||||
.on('click', (event, d) => {{ if (d.children) {{ d._children = d.children; d.children = null; }} else if (d._children) {{ d.children = d._children; d._children = null; }} updateTree(d); }})
|
||||
.style('cursor', d => (d.children || d._children) ? 'pointer' : 'default');
|
||||
|
||||
nodeEnter.append('circle').attr('r', 1e-6);
|
||||
|
||||
nodeEnter.append('text')
|
||||
.attr('dy', '.35em')
|
||||
.attr('x', d => d.children || d._children ? -14 : 14)
|
||||
.attr('text-anchor', d => d.children || d._children ? 'end' : 'start')
|
||||
.style("fill-opacity", 1e-6)
|
||||
.call(wrapText, 380);
|
||||
|
||||
const nodeUpdate = nodeEnter.merge(node);
|
||||
nodeUpdate.transition().duration(duration)
|
||||
.attr('transform', d => `translate(${{d.y}},${{d.x}})`)
|
||||
.attr('class', d => "node" + (d.children ? " node--internal" : " node--leaf") + (d._children ? " node--internal _children" : ""));
|
||||
|
||||
nodeUpdate.select('circle').attr('r', 8.5)
|
||||
.style('fill', d => {{
|
||||
let palette;
|
||||
if (d.depth === 0) {{
|
||||
palette = levelSpecificPalettes[0];
|
||||
}} else if (d.depth === 1) {{
|
||||
palette = phaseColors[d.data.originalStageName] || phaseColors.Default;
|
||||
}} else {{
|
||||
palette = levelSpecificPalettes[d.depth] || levelSpecificPalettes.default;
|
||||
}}
|
||||
if (d._children) return palette.collapsedFill;
|
||||
if (d.children) return palette.fill;
|
||||
return "#fff";
|
||||
}})
|
||||
.style('stroke', d => {{
|
||||
let palette;
|
||||
if (d.depth === 0) {{
|
||||
palette = levelSpecificPalettes[0];
|
||||
}} else if (d.depth === 1) {{
|
||||
palette = phaseColors[d.data.originalStageName] || phaseColors.Default;
|
||||
}} else {{
|
||||
palette = levelSpecificPalettes[d.depth] || levelSpecificPalettes.default;
|
||||
}}
|
||||
return palette.stroke;
|
||||
}});
|
||||
nodeUpdate.select('text').style("fill-opacity", 1).call(wrapText, 380);
|
||||
|
||||
const nodeExit = node.exit().transition().duration(duration).attr('transform', d => `translate(${{source.y}},${{source.x}})`).remove();
|
||||
nodeExit.select('circle').attr('r', 1e-6);
|
||||
nodeExit.select('text').style('fill-opacity', 1e-6);
|
||||
|
||||
const link = g.selectAll('path.link').data(links, d => d.id);
|
||||
const linkEnter = link.enter().insert('path', "g").attr('class', 'link').attr('d', d => {{ const o = {{ x: source.x0, y: source.y0 }}; return diagonal(o, o); }});
|
||||
|
||||
linkEnter.merge(link).transition().duration(duration).attr('d', d => diagonal(d, d.parent))
|
||||
.style('stroke', d => {{
|
||||
const sourceNode = d.parent;
|
||||
if (!sourceNode) return phaseColors.Default.stroke;
|
||||
const l1AncestorName = sourceNode.data.originalStageName;
|
||||
const colorPalette = phaseColors[l1AncestorName] || phaseColors.Default;
|
||||
return colorPalette.stroke;
|
||||
}});
|
||||
link.exit().transition().duration(duration).attr('d', d => {{ const o = {{ x: source.x, y: source.y }}; return diagonal(o, o); }}).remove();
|
||||
nodes.forEach(d => {{ d.x0 = d.x; d.y0 = d.y; }});
|
||||
}}
|
||||
|
||||
function diagonal(s, d) {{ return `M ${{s.y}} ${{s.x}} C ${{(s.y + d.y) / 2}} ${{s.x}}, ${{(s.y + d.y) / 2}} ${{d.x}}, ${{d.y}} ${{d.x}}`; }}
|
||||
|
||||
function wrapText(textElements, maxWidth) {{
|
||||
const textPartColors = {{
|
||||
name: '#343a40',
|
||||
count: '#0056b3'
|
||||
}};
|
||||
const countRegex = /(\s\(Total Count: \d+\))$/;
|
||||
|
||||
textElements.each(function () {{
|
||||
const textD3 = d3.select(this);
|
||||
const originalNodeText = textD3.datum().data.name;
|
||||
const x = parseFloat(textD3.attr("x") || 0);
|
||||
const initialDy = textD3.attr("dy");
|
||||
const textAnchor = textD3.attr("text-anchor");
|
||||
const lineHeight = 1.1;
|
||||
|
||||
textD3.text(null);
|
||||
|
||||
let namePart = originalNodeText;
|
||||
let countPartText = "";
|
||||
|
||||
const countMatch = originalNodeText.match(countRegex);
|
||||
if (countMatch && originalNodeText.endsWith(countMatch[0])) {{
|
||||
namePart = originalNodeText.substring(0, originalNodeText.length - countMatch[0].length).trim();
|
||||
countPartText = countMatch[0].trim();
|
||||
}}
|
||||
|
||||
const tokens = [];
|
||||
namePart.split(/\s+/).filter(Boolean).forEach(word => {{
|
||||
tokens.push({{ text: word, type: 'name' }});
|
||||
}});
|
||||
if (countPartText) {{
|
||||
tokens.push({{ text: countPartText, type: 'count' }});
|
||||
}}
|
||||
|
||||
if (tokens.length === 0 && originalNodeText) {{
|
||||
tokens.push({{ text: originalNodeText, type: 'name' }});
|
||||
}}
|
||||
|
||||
let currentTspan = textD3.append("tspan").attr("x", x).attr("dy", initialDy);
|
||||
if (textAnchor === "end") currentTspan.attr("text-anchor", "end");
|
||||
|
||||
let lineTokens = [];
|
||||
|
||||
for (let i = 0; i < tokens.length; i++) {{
|
||||
const tokenObj = tokens[i];
|
||||
|
||||
lineTokens.push(tokenObj);
|
||||
currentTspan.text(lineTokens.map(t => t.text).join(" "));
|
||||
|
||||
if (currentTspan.node().getComputedTextLength() > maxWidth && lineTokens.length > 1) {{
|
||||
lineTokens.pop();
|
||||
|
||||
currentTspan.text(null);
|
||||
lineTokens.forEach((prevToken, idx) => {{
|
||||
currentTspan.append("tspan")
|
||||
.text((idx > 0 ? " " : "") + prevToken.text)
|
||||
.style("fill", textPartColors[prevToken.type] || textPartColors.name)
|
||||
.style("font-weight", prevToken.type === 'count' ? "bold" : "normal");
|
||||
}});
|
||||
|
||||
lineTokens = [tokenObj];
|
||||
currentTspan = textD3.append("tspan").attr("x", x).attr("dy", lineHeight + "em");
|
||||
if (textAnchor === "end") currentTspan.attr("text-anchor", "end");
|
||||
}}
|
||||
}}
|
||||
|
||||
currentTspan.text(null);
|
||||
lineTokens.forEach((token, idx) => {{
|
||||
currentTspan.append("tspan")
|
||||
.text((idx > 0 ? " " : "") + token.text)
|
||||
.style("fill", textPartColors[token.type] || textPartColors.name)
|
||||
.style("font-weight", token.type === 'count' ? "bold" : "normal");
|
||||
}});
|
||||
|
||||
if (textD3.selectAll("tspan > tspan").empty() && textD3.select("tspan").text().length === 0 && originalNodeText) {{
|
||||
let t = textD3.select("tspan");
|
||||
let displayText = originalNodeText;
|
||||
t.text(displayText).style("fill", textPartColors.name);
|
||||
if (t.node() && t.node().getComputedTextLength() > maxWidth && displayText.length > 20) {{
|
||||
let estimatedChars = Math.floor(maxWidth / (t.node().getComputedTextLength()/displayText.length) );
|
||||
displayText = displayText.substring(0, Math.max(0, estimatedChars - 3)) + "...";
|
||||
t.text(displayText);
|
||||
}}
|
||||
}}
|
||||
}});
|
||||
}}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
def emit_html(
|
||||
tree: Dict[str, Any],
|
||||
*,
|
||||
title: str,
|
||||
header: str,
|
||||
svg_width: int = 6000,
|
||||
svg_height: int = 8000,
|
||||
) -> str:
|
||||
# Escape </script> sequences so embedded JSON cannot break out of the
|
||||
# <script> tag, and HTML-escape values that land in <title>/<h1>.
|
||||
data_json = json.dumps(tree, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
|
||||
return _HTML_TEMPLATE.format(
|
||||
title=_html.escape(title),
|
||||
header=_html.escape(header),
|
||||
svg_width=svg_width,
|
||||
svg_height=svg_height,
|
||||
data_json=data_json,
|
||||
)
|
||||
|
||||
|
||||
def write_tree_html(
|
||||
graph_path: Path,
|
||||
output_path: Path,
|
||||
*,
|
||||
root: Optional[str] = None,
|
||||
max_children: int = DEFAULT_MAX_CHILDREN,
|
||||
project_label: Optional[str] = None,
|
||||
# kept for CLI compatibility with the older signature; ignored now
|
||||
top_k_edges: int = 0,
|
||||
) -> Path:
|
||||
graph = json.loads(graph_path.read_text(encoding="utf-8"))
|
||||
tree = build_tree(graph, root=root, max_children=max_children,
|
||||
project_label=project_label)
|
||||
title = f"{tree['name']} — graphify tree viewer"
|
||||
header = f"{tree['name']} — Knowledge Graph"
|
||||
html = emit_html(tree, title=title, header=header)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
output_path.write_text(html, encoding="utf-8")
|
||||
return output_path
|
||||
@@ -1,7 +1,7 @@
|
||||
# validate extraction JSON against the graphify schema before graph assembly
|
||||
from __future__ import annotations
|
||||
|
||||
VALID_FILE_TYPES = {"code", "document", "paper", "image", "rationale"}
|
||||
VALID_FILE_TYPES = {"code", "document", "paper", "image", "rationale", "concept"}
|
||||
VALID_CONFIDENCES = {"EXTRACTED", "INFERRED", "AMBIGUOUS"}
|
||||
REQUIRED_NODE_FIELDS = {"id", "label", "file_type", "source_file"}
|
||||
REQUIRED_EDGE_FIELDS = {"source", "target", "relation", "confidence", "source_file"}
|
||||
@@ -36,14 +36,15 @@ def validate_extraction(data: dict) -> list[str]:
|
||||
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
|
||||
|
||||
+112
-12
@@ -1,9 +1,13 @@
|
||||
# monitor a folder and auto-trigger --update when files change
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
_GRAPHIFY_OUT = os.environ.get("GRAPHIFY_OUT", "graphify-out")
|
||||
|
||||
|
||||
from graphify.detect import CODE_EXTENSIONS, DOC_EXTENSIONS, PAPER_EXTENSIONS, IMAGE_EXTENSIONS
|
||||
|
||||
@@ -11,11 +15,39 @@ _WATCHED_EXTENSIONS = CODE_EXTENSIONS | DOC_EXTENSIONS | PAPER_EXTENSIONS | IMAG
|
||||
_CODE_EXTENSIONS = CODE_EXTENSIONS
|
||||
|
||||
|
||||
def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
def _report_root_label(watch_path: Path) -> str:
|
||||
if watch_path.is_absolute():
|
||||
return watch_path.name or str(watch_path)
|
||||
return Path.cwd().name if watch_path == Path(".") else str(watch_path)
|
||||
|
||||
|
||||
def _relativize_source_files(payload: dict, root: Path) -> None:
|
||||
for bucket in ("nodes", "edges", "hyperedges"):
|
||||
for item in payload.get(bucket, []):
|
||||
source = item.get("source_file")
|
||||
if not source:
|
||||
continue
|
||||
source_path = Path(source)
|
||||
if not source_path.is_absolute():
|
||||
continue
|
||||
try:
|
||||
item["source_file"] = str(source_path.resolve().relative_to(root))
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
|
||||
def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False, force: bool = False) -> bool:
|
||||
"""Re-run AST extraction + build + cluster + report for code files. No LLM needed.
|
||||
|
||||
When ``force`` is True the node-count safety check in ``to_json`` is bypassed
|
||||
so the rebuilt graph overwrites graph.json even if it has fewer nodes.
|
||||
Use this after refactors that legitimately delete code.
|
||||
|
||||
Returns True on success, False on error.
|
||||
"""
|
||||
watch_root = watch_path.resolve()
|
||||
project_root = Path.cwd().resolve() if not watch_path.is_absolute() else watch_root
|
||||
report_root = _report_root_label(watch_path)
|
||||
try:
|
||||
from graphify.extract import extract
|
||||
from graphify.detect import detect
|
||||
@@ -23,7 +55,7 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
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
|
||||
from graphify.export import to_json, to_html
|
||||
|
||||
detected = detect(watch_path, follow_symlinks=follow_symlinks)
|
||||
code_files = [Path(f) for f in detected['files']['code']]
|
||||
@@ -32,7 +64,36 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
print("[graphify watch] No code files found - nothing to rebuild.")
|
||||
return False
|
||||
|
||||
result = extract(code_files)
|
||||
result = extract(code_files, cache_root=watch_root)
|
||||
|
||||
# Preserve semantic nodes/edges from a previous full run.
|
||||
# AST-only rebuild replaces nodes for changed files; everything else is kept.
|
||||
# Filter by node ID membership in the new AST output, not by file_type —
|
||||
# INFERRED/AMBIGUOUS nodes extracted from code files also carry file_type="code"
|
||||
# and would be wrongly dropped by a file_type-based filter.
|
||||
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"))
|
||||
new_ast_ids = {n["id"] for n in result["nodes"]}
|
||||
preserved_nodes = [n for n in existing.get("nodes", []) if n["id"] not in new_ast_ids]
|
||||
all_ids = new_ast_ids | {n["id"] for n in preserved_nodes}
|
||||
preserved_edges = [
|
||||
e for e in existing.get("links", existing.get("edges", []))
|
||||
if e.get("source") in all_ids and e.get("target") in all_ids
|
||||
]
|
||||
result = {
|
||||
"nodes": result["nodes"] + preserved_nodes,
|
||||
"edges": result["edges"] + preserved_edges,
|
||||
"hyperedges": existing.get("hyperedges", []),
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0,
|
||||
}
|
||||
except Exception:
|
||||
pass # corrupt graph.json - proceed with AST-only
|
||||
|
||||
_relativize_source_files(result, project_root)
|
||||
|
||||
detection = {
|
||||
"files": {"code": [str(f) for f in code_files], "document": [], "paper": [], "image": []},
|
||||
@@ -48,13 +109,34 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
labels = {cid: "Community " + str(cid) for cid in communities}
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
out = watch_path / "graphify-out"
|
||||
out.mkdir(exist_ok=True)
|
||||
(out / ".graphify_root").write_text(str(watch_root), encoding="utf-8")
|
||||
|
||||
json_written = to_json(G, communities, str(out / "graph.json"), force=force)
|
||||
if not json_written:
|
||||
return False
|
||||
|
||||
try:
|
||||
from graphify.detect import save_manifest
|
||||
save_manifest(detected["files"])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection,
|
||||
{"input": 0, "output": 0}, str(watch_path), suggested_questions=questions)
|
||||
(out / "GRAPH_REPORT.md").write_text(report)
|
||||
to_json(G, communities, str(out / "graph.json"))
|
||||
{"input": 0, "output": 0}, report_root, suggested_questions=questions)
|
||||
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
|
||||
|
||||
# to_html raises ValueError for graphs > MAX_NODES_FOR_VIZ (5000).
|
||||
# Wrap so core outputs (graph.json + GRAPH_REPORT.md) always land.
|
||||
html_written = False
|
||||
try:
|
||||
to_html(G, communities, str(out / "graph.html"), community_labels=labels or None)
|
||||
html_written = True
|
||||
except ValueError as viz_err:
|
||||
print(f"[graphify watch] Skipped graph.html: {viz_err}")
|
||||
stale = out / "graph.html"
|
||||
if stale.exists():
|
||||
stale.unlink()
|
||||
|
||||
# clear stale needs_update flag if present
|
||||
flag = out / "needs_update"
|
||||
@@ -63,7 +145,8 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
|
||||
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}")
|
||||
products = "graph.json" + (", graph.html" if html_written else "") + " and GRAPH_REPORT.md"
|
||||
print(f"[graphify watch] {products} updated in {out}")
|
||||
return True
|
||||
|
||||
except Exception as exc:
|
||||
@@ -71,11 +154,26 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def check_update(watch_path: Path) -> bool:
|
||||
"""Check for pending semantic update flag and notify the user if set.
|
||||
|
||||
Cron-safe: always returns True so cron jobs do not alarm.
|
||||
Non-code file changes (docs, papers, images) require LLM-backed
|
||||
re-extraction via `/graphify --update` — this function only signals
|
||||
that the update is needed.
|
||||
"""
|
||||
flag = Path(watch_path) / _GRAPHIFY_OUT / "needs_update"
|
||||
if flag.exists():
|
||||
print(f"[graphify check-update] Pending non-code changes in {watch_path}.")
|
||||
print("[graphify check-update] Run `/graphify --update` to apply semantic re-extraction.")
|
||||
return True
|
||||
|
||||
|
||||
def _notify_only(watch_path: Path) -> None:
|
||||
"""Write a flag file and print a notification (fallback for non-code-only corpora)."""
|
||||
flag = watch_path / "graphify-out" / "needs_update"
|
||||
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.")
|
||||
@@ -99,6 +197,7 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
|
||||
"""
|
||||
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
|
||||
@@ -117,14 +216,15 @@ 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:
|
||||
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()
|
||||
|
||||
|
||||
+38
-5
@@ -7,7 +7,18 @@ import networkx as nx
|
||||
|
||||
|
||||
def _safe_filename(name: str) -> str:
|
||||
return name.replace("/", "-").replace(" ", "_").replace(":", "-")
|
||||
"""Make a label safe for use as a filename across platforms.
|
||||
|
||||
Substitutes characters that Windows reserves in filenames
|
||||
(< > : " / \\ | ? *) and strips trailing dots/spaces, also reserved.
|
||||
Falls back to 'unnamed' for empty results and caps length at 200
|
||||
chars to stay well under common filesystem limits.
|
||||
"""
|
||||
import re
|
||||
s = name.replace("/", "-").replace(" ", "_").replace(":", "-")
|
||||
s = re.sub(r'[<>:"/\\|?*]', '_', s)
|
||||
s = s.strip('. ')
|
||||
return s[:200] if s else 'unnamed'
|
||||
|
||||
|
||||
def _cross_community_links(G: nx.Graph, nodes: list[str], own_cid: int, labels: dict[int, str]) -> list[tuple[str, int]]:
|
||||
@@ -154,7 +165,7 @@ def _index_md(
|
||||
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['edges']} connections")
|
||||
lines.append(f"- [[{node['label']}]] — {node['degree']} connections")
|
||||
lines.append("")
|
||||
|
||||
lines += [
|
||||
@@ -185,17 +196,37 @@ def to_wiki(
|
||||
out = Path(output_dir)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Clear stale .md files from previous runs to prevent orphan accumulation.
|
||||
# Community labels are LLM-generated (per skill.md Step 5) and non-deterministic
|
||||
# across runs — the same conceptual community may be named differently each time
|
||||
# (e.g. "AutoAgent Skills" → "AutoAgent Methodology"), leaving the previous file
|
||||
# as an orphan. Since to_wiki() owns wiki/ entirely (always writes the full set),
|
||||
# it can safely clear .md files at the start of each call.
|
||||
for old_article in out.glob("*.md"):
|
||||
old_article.unlink()
|
||||
|
||||
labels = community_labels or {cid: f"Community {cid}" for cid in communities}
|
||||
cohesion = cohesion or {}
|
||||
god_nodes_data = god_nodes_data or []
|
||||
|
||||
count = 0
|
||||
used_slugs: set[str] = set()
|
||||
|
||||
def _unique_slug(base: str) -> str:
|
||||
slug = base
|
||||
n = 2
|
||||
while slug in used_slugs:
|
||||
slug = f"{base}_{n}"
|
||||
n += 1
|
||||
used_slugs.add(slug)
|
||||
return slug
|
||||
|
||||
# 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)
|
||||
slug = _unique_slug(_safe_filename(label))
|
||||
(out / f"{slug}.md").write_text(article, encoding="utf-8")
|
||||
count += 1
|
||||
|
||||
# God node articles
|
||||
@@ -203,12 +234,14 @@ def to_wiki(
|
||||
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)
|
||||
slug = _unique_slug(_safe_filename(node_data['label']))
|
||||
(out / f"{slug}.md").write_text(article, encoding="utf-8")
|
||||
count += 1
|
||||
|
||||
# Index
|
||||
(out / "index.md").write_text(
|
||||
_index_md(communities, labels, god_nodes_data, G.number_of_nodes(), G.number_of_edges())
|
||||
_index_md(communities, labels, god_nodes_data, G.number_of_nodes(), G.number_of_edges()),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
return count
|
||||
+19
-10
@@ -4,11 +4,11 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "graphifyy"
|
||||
version = "0.3.29"
|
||||
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, OpenClaw, Factory Droid, Trae) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
|
||||
version = "0.6.9"
|
||||
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Pi, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
|
||||
readme = "README.md"
|
||||
license = { file = "LICENSE" }
|
||||
keywords = ["claude", "claude-code", "codex", "opencode", "cursor", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
|
||||
keywords = ["claude", "claude-code", "codex", "opencode", "cursor", "gemini", "aider", "kiro", "pi", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"networkx",
|
||||
@@ -33,6 +33,7 @@ dependencies = [
|
||||
"tree-sitter-elixir",
|
||||
"tree-sitter-objc",
|
||||
"tree-sitter-julia",
|
||||
"tree-sitter-verilog",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
@@ -43,19 +44,27 @@ Issues = "https://github.com/safishamsi/graphify/issues"
|
||||
[project.optional-dependencies]
|
||||
mcp = ["mcp"]
|
||||
neo4j = ["neo4j"]
|
||||
pdf = ["pypdf", "html2text"]
|
||||
pdf = ["pypdf", "markdownify"]
|
||||
watch = ["watchdog"]
|
||||
leiden = ["graspologic"]
|
||||
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-docx", "openpyxl", "faster-whisper", "yt-dlp"]
|
||||
kimi = ["openai", "tiktoken"]
|
||||
sql = ["tree-sitter-sql"]
|
||||
all = ["mcp", "neo4j", "pypdf", "markdownify", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper", "yt-dlp", "matplotlib", "openai", "tiktoken", "tree-sitter-sql"]
|
||||
|
||||
[project.scripts]
|
||||
graphify = "graphify.__main__:main"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["."]
|
||||
include = ["graphify*"]
|
||||
[tool.uv]
|
||||
# Install via: uv tool install graphifyy
|
||||
# Run without installing: uvx graphifyy install
|
||||
package = true
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["graphify"]
|
||||
include-package-data = false
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
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"]
|
||||
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", "skill-pi.md"]
|
||||
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Benchmark: sequential vs parallel AST extraction.
|
||||
|
||||
Usage:
|
||||
python tests/bench_extract.py [path-to-repo]
|
||||
|
||||
Defaults to the current directory if no path is given.
|
||||
Clears the AST cache between runs so every file is re-extracted.
|
||||
|
||||
Example output:
|
||||
=== Graphify AST Extraction Benchmark ===
|
||||
Files: 1,247
|
||||
Languages: Python (412), TypeScript (389), Go (201), ...
|
||||
|
||||
Sequential: 4.32s (8,934 nodes, 12,456 edges)
|
||||
Parallel (8): 1.28s (8,934 nodes, 12,456 edges)
|
||||
|
||||
Speedup: 3.38x
|
||||
Results: ✓ identical
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
# Ensure the project root is importable
|
||||
_project_root = Path(__file__).resolve().parent.parent
|
||||
if str(_project_root) not in sys.path:
|
||||
sys.path.insert(0, str(_project_root))
|
||||
|
||||
from graphify.extract import extract, collect_files
|
||||
from graphify.cache import clear_cache
|
||||
|
||||
|
||||
def _count_by_ext(paths: list[Path]) -> dict[str, int]:
|
||||
"""Count files by extension."""
|
||||
counter: Counter[str] = Counter()
|
||||
for p in paths:
|
||||
ext = p.suffix.lower()
|
||||
counter[ext] += 1
|
||||
return dict(counter.most_common())
|
||||
|
||||
|
||||
_EXT_NAMES: dict[str, str] = {
|
||||
".py": "Python",
|
||||
".js": "JavaScript",
|
||||
".jsx": "JSX",
|
||||
".mjs": "MJS",
|
||||
".ts": "TypeScript",
|
||||
".tsx": "TSX",
|
||||
".go": "Go",
|
||||
".rs": "Rust",
|
||||
".java": "Java",
|
||||
".c": "C",
|
||||
".h": "C Header",
|
||||
".cpp": "C++",
|
||||
".cc": "C++",
|
||||
".cxx": "C++",
|
||||
".hpp": "C++ Header",
|
||||
".rb": "Ruby",
|
||||
".cs": "C#",
|
||||
".kt": "Kotlin",
|
||||
".kts": "Kotlin Script",
|
||||
".scala": "Scala",
|
||||
".php": "PHP",
|
||||
".swift": "Swift",
|
||||
".lua": "Lua",
|
||||
".toc": "Lua TOC",
|
||||
".zig": "Zig",
|
||||
".ps1": "PowerShell",
|
||||
".ex": "Elixir",
|
||||
".exs": "Elixir Script",
|
||||
".m": "Obj-C",
|
||||
".mm": "Obj-C++",
|
||||
".jl": "Julia",
|
||||
".vue": "Vue",
|
||||
".svelte": "Svelte",
|
||||
".dart": "Dart",
|
||||
".v": "Verilog",
|
||||
".sv": "SystemVerilog",
|
||||
".sql": "SQL",
|
||||
}
|
||||
|
||||
|
||||
def _format_languages(ext_counts: dict[str, int]) -> str:
|
||||
parts = []
|
||||
for ext, count in ext_counts.items():
|
||||
name = _EXT_NAMES.get(ext, ext)
|
||||
parts.append(f"{name} ({count})")
|
||||
return ", ".join(parts)
|
||||
|
||||
|
||||
def _run_extraction(
|
||||
paths: list[Path],
|
||||
cache_root: Path,
|
||||
parallel: bool,
|
||||
max_workers: int | None = None,
|
||||
) -> tuple[float, int, int]:
|
||||
"""Run extraction, return (elapsed_seconds, node_count, edge_count)."""
|
||||
clear_cache(cache_root)
|
||||
t0 = time.perf_counter()
|
||||
result = extract(
|
||||
paths, cache_root=cache_root, parallel=parallel, max_workers=max_workers
|
||||
)
|
||||
elapsed = time.perf_counter() - t0
|
||||
nodes = len(result.get("nodes", []))
|
||||
edges = len(result.get("edges", []))
|
||||
return elapsed, nodes, edges
|
||||
|
||||
|
||||
def main() -> None:
|
||||
target = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(".")
|
||||
target = target.resolve()
|
||||
|
||||
if not target.exists():
|
||||
print(f"Error: {target} does not exist", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
print("=== Graphify AST Extraction Benchmark ===\n")
|
||||
print(f"Scanning {target} ...", flush=True)
|
||||
|
||||
paths = collect_files(target)
|
||||
if not paths:
|
||||
print("No extractable files found.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
ext_counts = _count_by_ext(paths)
|
||||
print(f"Files: {len(paths):,}")
|
||||
print(f"Languages: {_format_languages(ext_counts)}")
|
||||
print()
|
||||
|
||||
cache_root = target if target.is_dir() else target.parent
|
||||
|
||||
# Workers count (same logic as _extract_parallel)
|
||||
import os
|
||||
|
||||
workers = min(os.cpu_count() or 4, len(paths), 8)
|
||||
|
||||
# Run sequential
|
||||
print("Running sequential extraction...", flush=True)
|
||||
seq_time, seq_nodes, seq_edges = _run_extraction(paths, cache_root, parallel=False)
|
||||
print(f"Sequential: {seq_time:.2f}s ({seq_nodes:,} nodes, {seq_edges:,} edges)")
|
||||
|
||||
# Run parallel
|
||||
print(f"\nRunning parallel extraction ({workers} workers)...", flush=True)
|
||||
par_time, par_nodes, par_edges = _run_extraction(
|
||||
paths, cache_root, parallel=True, max_workers=workers
|
||||
)
|
||||
print(
|
||||
f"Parallel ({workers}): {par_time:.2f}s ({par_nodes:,} nodes, {par_edges:,} edges)"
|
||||
)
|
||||
|
||||
# Results
|
||||
print()
|
||||
if seq_time > 0:
|
||||
speedup = seq_time / par_time if par_time > 0 else float("inf")
|
||||
print(f"Speedup: {speedup:.2f}x")
|
||||
print(f"Workers: {workers} (auto-detected)")
|
||||
|
||||
# Validate correctness
|
||||
if seq_nodes == par_nodes and seq_edges == par_edges:
|
||||
print("Results: ✓ identical (node count, edge count match)")
|
||||
else:
|
||||
print("Results: ✗ MISMATCH!")
|
||||
print(f" Sequential: {seq_nodes} nodes, {seq_edges} edges")
|
||||
print(f" Parallel: {par_nodes} nodes, {par_edges} edges")
|
||||
sys.exit(1)
|
||||
|
||||
# Clean up cache after benchmark
|
||||
clear_cache(cache_root)
|
||||
print("\nCache cleared after benchmark.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Vendored
+32
@@ -0,0 +1,32 @@
|
||||
import { logger } from './logger';
|
||||
|
||||
async function processInbound(orgId: string, phone: string) {
|
||||
const { shouldHandle, processMessage } = await import('./mayaEngine.js');
|
||||
const handle = await shouldHandle(orgId, phone);
|
||||
if (handle.sessionId) {
|
||||
await processMessage({ orgId, phone }, handle.sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
async function pollMessages(orgId: string) {
|
||||
const { commsQueue } = await import('./queue.js');
|
||||
await commsQueue.add('check-inbound', { orgId });
|
||||
}
|
||||
|
||||
async function loadHandler(handlerName: string) {
|
||||
// dynamic template literal — path not statically resolvable, should produce no edge
|
||||
const mod = await import(`./handlers/${handlerName}`);
|
||||
return mod.default;
|
||||
}
|
||||
|
||||
async function loadStatic() {
|
||||
// static template literal (no interpolation) — should resolve like a plain string
|
||||
const { helper } = await import(`./staticHelper`);
|
||||
return helper;
|
||||
}
|
||||
|
||||
function syncOnly() {
|
||||
logger.info('no dynamic imports here');
|
||||
}
|
||||
|
||||
export { processInbound, pollMessages, loadHandler, loadStatic, syncOnly };
|
||||
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
CREATE TABLE organizations (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
email TEXT NOT NULL,
|
||||
org_id INT REFERENCES organizations(id)
|
||||
);
|
||||
|
||||
CREATE VIEW active_users AS
|
||||
SELECT * FROM users WHERE active = true;
|
||||
|
||||
CREATE FUNCTION get_user(user_id INT) RETURNS users AS $$
|
||||
BEGIN
|
||||
RETURN QUERY SELECT * FROM users WHERE id = user_id;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
Vendored
+22
@@ -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
@@ -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);
|
||||
}
|
||||
}
|
||||
Vendored
+22
@@ -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
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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():
|
||||
|
||||
@@ -29,6 +29,42 @@ def test_ambiguous_edge_preserved():
|
||||
data = G.edges["n_layernorm", "n_concept_attn"]
|
||||
assert data["confidence"] == "AMBIGUOUS"
|
||||
|
||||
def test_legacy_node_source_canonicalized():
|
||||
"""Legacy 'source' key on nodes is renamed to 'source_file' before graph build."""
|
||||
ext = {"nodes": [{"id": "n1", "label": "A", "file_type": "code", "source": "a.py"}],
|
||||
"edges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
G = build_from_json(ext)
|
||||
assert "source_file" in G.nodes["n1"]
|
||||
assert G.nodes["n1"]["source_file"] == "a.py"
|
||||
assert "source" not in G.nodes["n1"]
|
||||
|
||||
|
||||
def test_legacy_edge_from_to_canonicalized():
|
||||
"""Legacy 'from'/'to' keys on edges are accepted alongside 'source'/'target'."""
|
||||
ext = {"nodes": [{"id": "n1", "label": "A", "file_type": "code", "source_file": "a.py"},
|
||||
{"id": "n2", "label": "B", "file_type": "code", "source_file": "b.py"}],
|
||||
"edges": [{"from": "n1", "to": "n2", "relation": "calls",
|
||||
"confidence": "EXTRACTED", "source_file": "a.py", "weight": 1.0}],
|
||||
"input_tokens": 0, "output_tokens": 0}
|
||||
G = build_from_json(ext)
|
||||
assert G.number_of_edges() == 1
|
||||
|
||||
|
||||
def test_source_file_backslash_normalized():
|
||||
"""Windows backslash paths and POSIX paths for the same file must produce one node."""
|
||||
extraction = {
|
||||
"nodes": [
|
||||
{"id": "n1", "label": "A", "file_type": "code", "source_file": "src\\middleware\\auth.py"},
|
||||
{"id": "n2", "label": "B", "file_type": "code", "source_file": "src/middleware/auth.py"},
|
||||
],
|
||||
"edges": [],
|
||||
"input_tokens": 0, "output_tokens": 0,
|
||||
}
|
||||
G = build_from_json(extraction)
|
||||
sources = {G.nodes[n]["source_file"] for n in G.nodes()}
|
||||
assert sources == {"src/middleware/auth.py"}
|
||||
|
||||
|
||||
def test_build_merges_multiple_extractions():
|
||||
ext1 = {"nodes": [{"id": "n1", "label": "A", "file_type": "code", "source_file": "a.py"}],
|
||||
"edges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
|
||||
+7
-5
@@ -62,16 +62,18 @@ 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-out/cache/."""
|
||||
"""clear_cache removes all .json files from graphify-out/cache/ (all subdirs)."""
|
||||
save_cached(tmp_file, {"nodes": [], "edges": []}, root=cache_root)
|
||||
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) > 0
|
||||
# Since v0.5.3 entries go into cache/ast/, not the flat cache/ dir
|
||||
cache_base = cache_root / "graphify-out" / "cache"
|
||||
assert len(list(cache_base.rglob("*.json"))) > 0
|
||||
clear_cache(cache_root)
|
||||
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) == 0
|
||||
assert len(list(cache_base.rglob("*.json"))) == 0
|
||||
|
||||
|
||||
def test_md_frontmatter_only_change_same_hash(tmp_path):
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
"""Tests for token-aware chunking and parallel chunk execution in graphify.llm."""
|
||||
import time
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=False)
|
||||
def no_tokenizer():
|
||||
"""Force the chars/4 fallback so packing math is deterministic regardless
|
||||
of whether tiktoken is installed in the test environment. tiktoken's BPE
|
||||
compresses repeated/synthetic content heavily, which would make pack-size
|
||||
assertions tied to specific input sizes flaky."""
|
||||
from graphify import llm
|
||||
with patch.object(llm, "_TOKENIZER", None):
|
||||
yield
|
||||
|
||||
|
||||
# ---- Token-aware packing -----------------------------------------------------
|
||||
|
||||
def test_pack_chunks_packs_small_files_together(tmp_path):
|
||||
"""Many small files should land in a single chunk, not one chunk per file."""
|
||||
from graphify.llm import _pack_chunks_by_tokens
|
||||
|
||||
files = []
|
||||
for i in range(20):
|
||||
f = tmp_path / f"small_{i}.py"
|
||||
f.write_text("x = 1\n") # ~6 bytes => ~1 token
|
||||
files.append(f)
|
||||
|
||||
chunks = _pack_chunks_by_tokens(files, token_budget=10_000)
|
||||
assert len(chunks) == 1
|
||||
assert sorted(chunks[0]) == sorted(files)
|
||||
|
||||
|
||||
def test_pack_chunks_starts_new_chunk_when_budget_would_overflow(tmp_path, no_tokenizer):
|
||||
"""When the next file would push the chunk past the budget, start a new chunk.
|
||||
|
||||
With chars/4 fallback: each 10,000-char file = (10000+80)/4 = 2520 tokens.
|
||||
Budget 6000 fits two (5040 < 6000) but not three (7560 > 6000).
|
||||
Five files → 2/2/1 = three chunks.
|
||||
"""
|
||||
from graphify.llm import _pack_chunks_by_tokens
|
||||
|
||||
files = []
|
||||
for i in range(5):
|
||||
f = tmp_path / f"file_{i}.py"
|
||||
f.write_text("x" * 10_000)
|
||||
files.append(f)
|
||||
|
||||
chunks = _pack_chunks_by_tokens(files, token_budget=6_000)
|
||||
sizes = [len(c) for c in chunks]
|
||||
assert sizes == [2, 2, 1], f"expected [2, 2, 1], got {sizes}"
|
||||
assert sum(sizes) == 5 # all files accounted for
|
||||
|
||||
|
||||
def test_pack_chunks_groups_by_directory(tmp_path):
|
||||
"""Files in the same directory should land in the same chunk when they fit."""
|
||||
from graphify.llm import _pack_chunks_by_tokens
|
||||
|
||||
dir_a = tmp_path / "a"
|
||||
dir_b = tmp_path / "b"
|
||||
dir_a.mkdir()
|
||||
dir_b.mkdir()
|
||||
|
||||
a1 = dir_a / "x.py"; a1.write_text("a")
|
||||
a2 = dir_a / "y.py"; a2.write_text("a")
|
||||
b1 = dir_b / "x.py"; b1.write_text("b")
|
||||
b2 = dir_b / "y.py"; b2.write_text("b")
|
||||
|
||||
# Big budget — everything fits in one chunk in principle, but the order
|
||||
# within the chunk should keep dir_a's files contiguous and dir_b's
|
||||
# contiguous (not interleaved).
|
||||
chunks = _pack_chunks_by_tokens([a1, b1, a2, b2], token_budget=1_000_000)
|
||||
assert len(chunks) == 1
|
||||
chunk = chunks[0]
|
||||
a_indices = [i for i, p in enumerate(chunk) if p.parent == dir_a]
|
||||
b_indices = [i for i, p in enumerate(chunk) if p.parent == dir_b]
|
||||
assert a_indices == sorted(a_indices)
|
||||
assert b_indices == sorted(b_indices)
|
||||
# all of one directory comes before all of the other
|
||||
assert max(a_indices) < min(b_indices) or max(b_indices) < min(a_indices)
|
||||
|
||||
|
||||
def test_pack_chunks_oversized_file_gets_its_own_chunk(tmp_path, no_tokenizer):
|
||||
"""A file larger than the budget can't be split — it goes alone in a chunk."""
|
||||
from graphify.llm import _pack_chunks_by_tokens
|
||||
|
||||
big = tmp_path / "big.py"; big.write_text("x" * 200_000) # ~50k tokens (cap-bound)
|
||||
small = tmp_path / "small.py"; small.write_text("x")
|
||||
|
||||
chunks = _pack_chunks_by_tokens([big, small], token_budget=1_000)
|
||||
sizes = [len(c) for c in chunks]
|
||||
# big should be alone in its own chunk; small in its own (no other file
|
||||
# to share with)
|
||||
assert sizes == [1, 1]
|
||||
|
||||
|
||||
def test_pack_chunks_rejects_non_positive_budget(tmp_path):
|
||||
from graphify.llm import _pack_chunks_by_tokens
|
||||
|
||||
f = tmp_path / "x.py"; f.write_text("a")
|
||||
with pytest.raises(ValueError):
|
||||
_pack_chunks_by_tokens([f], token_budget=0)
|
||||
|
||||
|
||||
# ---- Tokenizer fallback ------------------------------------------------------
|
||||
|
||||
def test_estimate_file_tokens_uses_tiktoken_when_available(tmp_path):
|
||||
"""When tiktoken is installed, the estimator should call into it for
|
||||
accurate counts rather than the chars/4 heuristic."""
|
||||
from graphify import llm
|
||||
|
||||
f = tmp_path / "sample.py"
|
||||
text = "def hello():\n return 'world'\n" * 50 # ~1500 chars
|
||||
f.write_text(text)
|
||||
|
||||
# Force the tokenizer to be a mock that records calls and returns a known
|
||||
# token list, so we can assert the tiktoken path is taken.
|
||||
fake_encoder = type("E", (), {"encode": staticmethod(lambda s: [0] * 999)})()
|
||||
with patch.object(llm, "_TOKENIZER", fake_encoder):
|
||||
n = llm._estimate_file_tokens(f)
|
||||
assert n == 999 + (llm._PER_FILE_OVERHEAD_CHARS // llm._CHARS_PER_TOKEN)
|
||||
|
||||
|
||||
def test_estimate_file_tokens_falls_back_to_chars_when_no_tokenizer(tmp_path):
|
||||
"""Without tiktoken installed, the estimator falls back to chars/4."""
|
||||
from graphify import llm
|
||||
|
||||
f = tmp_path / "sample.py"
|
||||
f.write_text("x" * 1_000) # 1000 bytes
|
||||
|
||||
with patch.object(llm, "_TOKENIZER", None):
|
||||
n = llm._estimate_file_tokens(f)
|
||||
# 1000 chars + 80 overhead = 1080 / 4 = 270 tokens
|
||||
assert n == (1000 + llm._PER_FILE_OVERHEAD_CHARS) // llm._CHARS_PER_TOKEN
|
||||
|
||||
|
||||
# ---- Parallel execution ------------------------------------------------------
|
||||
|
||||
def _stub_chunk_result(file_count: int, idx: int) -> dict:
|
||||
"""Build a deterministic fake extraction result for a chunk."""
|
||||
return {
|
||||
"nodes": [{"id": f"chunk_{idx}_node_{i}"} for i in range(file_count)],
|
||||
"edges": [],
|
||||
"hyperedges": [],
|
||||
"input_tokens": 100 * file_count,
|
||||
"output_tokens": 50 * file_count,
|
||||
}
|
||||
|
||||
|
||||
def test_corpus_parallel_runs_chunks_concurrently(tmp_path):
|
||||
"""With max_concurrency > 1, total wall time should be ~max(chunk times),
|
||||
not the sum. Each stub extraction sleeps; we assert wall time."""
|
||||
from graphify.llm import extract_corpus_parallel
|
||||
|
||||
files = []
|
||||
for i in range(8):
|
||||
f = tmp_path / f"f{i}.py"; f.write_text("x")
|
||||
files.append(f)
|
||||
|
||||
def slow_extract(chunk, **kwargs):
|
||||
time.sleep(0.3)
|
||||
return _stub_chunk_result(len(chunk), 0)
|
||||
|
||||
with patch("graphify.llm.extract_files_direct", side_effect=slow_extract):
|
||||
t0 = time.time()
|
||||
# Force 4 chunks of 2 files each by setting a tight token budget.
|
||||
result = extract_corpus_parallel(
|
||||
files, backend="kimi", token_budget=None, chunk_size=2, max_concurrency=4
|
||||
)
|
||||
elapsed = time.time() - t0
|
||||
|
||||
# 4 chunks × 0.3s sequential = 1.2s. Parallel with 4 workers should land near 0.3-0.5s.
|
||||
assert elapsed < 1.0, f"expected parallel speedup, took {elapsed:.2f}s"
|
||||
assert len(result["nodes"]) == 8
|
||||
|
||||
|
||||
def test_corpus_parallel_sequential_when_max_concurrency_is_one(tmp_path):
|
||||
"""max_concurrency=1 should run sequentially (no thread pool)."""
|
||||
from graphify.llm import extract_corpus_parallel
|
||||
|
||||
files = []
|
||||
for i in range(3):
|
||||
f = tmp_path / f"f{i}.py"; f.write_text("x")
|
||||
files.append(f)
|
||||
|
||||
call_order = []
|
||||
|
||||
def record(chunk, **kwargs):
|
||||
call_order.append(tuple(p.name for p in chunk))
|
||||
return _stub_chunk_result(len(chunk), len(call_order))
|
||||
|
||||
with patch("graphify.llm.extract_files_direct", side_effect=record):
|
||||
extract_corpus_parallel(
|
||||
files, backend="kimi", token_budget=None, chunk_size=1, max_concurrency=1
|
||||
)
|
||||
|
||||
# Sequential => we see calls in submission order
|
||||
assert call_order == [("f0.py",), ("f1.py",), ("f2.py",)]
|
||||
|
||||
|
||||
def test_corpus_parallel_continues_after_chunk_failure(tmp_path, capsys):
|
||||
"""A single chunk raising should be logged but not abort the run.
|
||||
Other chunks' results should still be merged."""
|
||||
from graphify.llm import extract_corpus_parallel
|
||||
|
||||
files = []
|
||||
for i in range(4):
|
||||
f = tmp_path / f"f{i}.py"; f.write_text("x")
|
||||
files.append(f)
|
||||
|
||||
call_count = {"n": 0}
|
||||
|
||||
def maybe_fail(chunk, **kwargs):
|
||||
call_count["n"] += 1
|
||||
if call_count["n"] == 2:
|
||||
raise RuntimeError("simulated API error")
|
||||
return _stub_chunk_result(len(chunk), call_count["n"])
|
||||
|
||||
with patch("graphify.llm.extract_files_direct", side_effect=maybe_fail):
|
||||
result = extract_corpus_parallel(
|
||||
files, backend="kimi", token_budget=None, chunk_size=1, max_concurrency=1
|
||||
)
|
||||
|
||||
# 4 chunks dispatched, 1 failed → 3 chunks contributed nodes
|
||||
assert len(result["nodes"]) == 3
|
||||
err = capsys.readouterr().err
|
||||
assert "failed" in err and "simulated API error" in err
|
||||
|
||||
|
||||
def test_corpus_parallel_legacy_mode_when_token_budget_is_none(tmp_path):
|
||||
"""token_budget=None should fall back to legacy fixed-count chunking."""
|
||||
from graphify.llm import extract_corpus_parallel
|
||||
|
||||
files = []
|
||||
for i in range(45):
|
||||
f = tmp_path / f"f{i}.py"; f.write_text("x")
|
||||
files.append(f)
|
||||
|
||||
chunks_seen = []
|
||||
|
||||
def record(chunk, **kwargs):
|
||||
chunks_seen.append(len(chunk))
|
||||
return _stub_chunk_result(len(chunk), len(chunks_seen))
|
||||
|
||||
with patch("graphify.llm.extract_files_direct", side_effect=record):
|
||||
extract_corpus_parallel(
|
||||
files, backend="kimi", token_budget=None, chunk_size=20, max_concurrency=1
|
||||
)
|
||||
|
||||
# 45 files / chunk_size=20 = 3 chunks of 20, 20, 5
|
||||
assert chunks_seen == [20, 20, 5]
|
||||
|
||||
|
||||
def test_corpus_parallel_token_budget_default_packs_files(tmp_path):
|
||||
"""With the default token_budget, many tiny files pack into one chunk."""
|
||||
from graphify.llm import extract_corpus_parallel
|
||||
|
||||
files = []
|
||||
for i in range(50):
|
||||
f = tmp_path / f"f{i}.py"; f.write_text("x = 1\n")
|
||||
files.append(f)
|
||||
|
||||
chunks_seen = []
|
||||
|
||||
def record(chunk, **kwargs):
|
||||
chunks_seen.append(len(chunk))
|
||||
return _stub_chunk_result(len(chunk), len(chunks_seen))
|
||||
|
||||
with patch("graphify.llm.extract_files_direct", side_effect=record):
|
||||
extract_corpus_parallel(files, backend="kimi", max_concurrency=1)
|
||||
|
||||
# 50 tiny files at default 60k token budget should pack into 1 chunk
|
||||
assert len(chunks_seen) == 1
|
||||
assert chunks_seen[0] == 50
|
||||
|
||||
|
||||
# ---- Adaptive retry on truncation -------------------------------------------
|
||||
|
||||
def _stub_with_finish(file_count: int, finish_reason: str = "stop") -> dict:
|
||||
"""Build a stub extraction result with a controllable finish_reason."""
|
||||
return {
|
||||
"nodes": [{"id": f"n_{i}"} for i in range(file_count)],
|
||||
"edges": [],
|
||||
"hyperedges": [],
|
||||
"input_tokens": 100 * file_count,
|
||||
"output_tokens": 50 * file_count,
|
||||
"finish_reason": finish_reason,
|
||||
}
|
||||
|
||||
|
||||
def test_adaptive_retry_returns_directly_when_not_truncated(tmp_path):
|
||||
"""No retry when finish_reason='stop' — single call, result passes through."""
|
||||
from graphify.llm import _extract_with_adaptive_retry
|
||||
|
||||
files = [tmp_path / f"f{i}.py" for i in range(4)]
|
||||
for f in files:
|
||||
f.write_text("x")
|
||||
|
||||
calls = []
|
||||
|
||||
def stub(chunk, **kwargs):
|
||||
calls.append(len(chunk))
|
||||
return _stub_with_finish(len(chunk), finish_reason="stop")
|
||||
|
||||
with patch("graphify.llm.extract_files_direct", side_effect=stub):
|
||||
result = _extract_with_adaptive_retry(
|
||||
files, backend="kimi", api_key=None, model=None, root=tmp_path, max_depth=3
|
||||
)
|
||||
|
||||
assert calls == [4], f"expected 1 call of 4 files, got {calls}"
|
||||
assert len(result["nodes"]) == 4
|
||||
|
||||
|
||||
def test_adaptive_retry_splits_when_finish_reason_length(tmp_path):
|
||||
"""finish_reason='length' triggers split-in-half. Both halves succeed
|
||||
on the second try (mocked) and results merge."""
|
||||
from graphify.llm import _extract_with_adaptive_retry
|
||||
|
||||
files = [tmp_path / f"f{i}.py" for i in range(4)]
|
||||
for f in files:
|
||||
f.write_text("x")
|
||||
|
||||
calls = []
|
||||
|
||||
def stub(chunk, **kwargs):
|
||||
calls.append(len(chunk))
|
||||
finish = "length" if len(chunk) == 4 else "stop"
|
||||
return _stub_with_finish(len(chunk), finish_reason=finish)
|
||||
|
||||
with patch("graphify.llm.extract_files_direct", side_effect=stub):
|
||||
result = _extract_with_adaptive_retry(
|
||||
files, backend="kimi", api_key=None, model=None, root=tmp_path, max_depth=3
|
||||
)
|
||||
|
||||
assert calls == [4, 2, 2], f"expected [4, 2, 2], got {calls}"
|
||||
assert len(result["nodes"]) == 4
|
||||
assert result["finish_reason"] == "stop"
|
||||
|
||||
|
||||
def test_adaptive_retry_recurses_for_persistent_truncation(tmp_path):
|
||||
"""When even the half-chunk truncates, split again. With 8 files and a
|
||||
truncation cutoff at >2 files, splits 8 → 4 → 2 (4 leaves of 2)."""
|
||||
from graphify.llm import _extract_with_adaptive_retry
|
||||
|
||||
files = [tmp_path / f"f{i}.py" for i in range(8)]
|
||||
for f in files:
|
||||
f.write_text("x")
|
||||
|
||||
calls = []
|
||||
|
||||
def stub(chunk, **kwargs):
|
||||
calls.append(len(chunk))
|
||||
finish = "length" if len(chunk) > 2 else "stop"
|
||||
return _stub_with_finish(len(chunk), finish_reason=finish)
|
||||
|
||||
with patch("graphify.llm.extract_files_direct", side_effect=stub):
|
||||
result = _extract_with_adaptive_retry(
|
||||
files, backend="kimi", api_key=None, model=None, root=tmp_path, max_depth=3
|
||||
)
|
||||
|
||||
# Tree: 8 (trunc) → 4 + 4 (both trunc) → 2+2+2+2 (all stop)
|
||||
# Total calls: 1 + 2 + 4 = 7
|
||||
assert sorted(calls) == [2, 2, 2, 2, 4, 4, 8]
|
||||
assert len(result["nodes"]) == 8
|
||||
|
||||
|
||||
def test_adaptive_retry_caps_at_max_depth(tmp_path, capsys):
|
||||
"""If everything truncates, retries stop at max_depth — partial result
|
||||
kept with a warning, no infinite loop."""
|
||||
from graphify.llm import _extract_with_adaptive_retry
|
||||
|
||||
files = [tmp_path / f"f{i}.py" for i in range(8)]
|
||||
for f in files:
|
||||
f.write_text("x")
|
||||
|
||||
calls = []
|
||||
|
||||
def always_truncate(chunk, **kwargs):
|
||||
calls.append(len(chunk))
|
||||
return _stub_with_finish(len(chunk), finish_reason="length")
|
||||
|
||||
with patch("graphify.llm.extract_files_direct", side_effect=always_truncate):
|
||||
_extract_with_adaptive_retry(
|
||||
files, backend="kimi", api_key=None, model=None, root=tmp_path, max_depth=2
|
||||
)
|
||||
|
||||
# max_depth=2 bounds the tree: root + 2 + 4 = 7 calls maximum
|
||||
assert len(calls) <= 7, f"recursion not bounded — {len(calls)} calls"
|
||||
err = capsys.readouterr().err
|
||||
assert "still truncated" in err
|
||||
|
||||
|
||||
def test_adaptive_retry_single_file_truncation_does_not_recurse(tmp_path, capsys):
|
||||
"""A single file that truncates can't be split further — surface a
|
||||
warning and return what we got. No infinite loop."""
|
||||
from graphify.llm import _extract_with_adaptive_retry
|
||||
|
||||
f = tmp_path / "huge.py"; f.write_text("x")
|
||||
|
||||
calls = []
|
||||
|
||||
def stub(chunk, **kwargs):
|
||||
calls.append(len(chunk))
|
||||
return _stub_with_finish(len(chunk), finish_reason="length")
|
||||
|
||||
with patch("graphify.llm.extract_files_direct", side_effect=stub):
|
||||
_extract_with_adaptive_retry(
|
||||
[f], backend="kimi", api_key=None, model=None, root=tmp_path, max_depth=3
|
||||
)
|
||||
|
||||
assert calls == [1], f"single-file chunk recursed; calls = {calls}"
|
||||
err = capsys.readouterr().err
|
||||
assert "single-file chunk" in err and "truncated" in err
|
||||
|
||||
|
||||
def test_corpus_parallel_uses_adaptive_retry(tmp_path):
|
||||
"""End-to-end: extract_corpus_parallel routes through adaptive retry,
|
||||
so a chunk that truncates gets split and merged transparently before
|
||||
on_chunk_done fires."""
|
||||
from graphify.llm import extract_corpus_parallel
|
||||
|
||||
files = [tmp_path / f"f{i}.py" for i in range(4)]
|
||||
for f in files:
|
||||
f.write_text("x")
|
||||
|
||||
calls = []
|
||||
|
||||
def stub(chunk, **kwargs):
|
||||
calls.append(len(chunk))
|
||||
finish = "length" if len(chunk) == 4 else "stop"
|
||||
return _stub_with_finish(len(chunk), finish_reason=finish)
|
||||
|
||||
chunk_done_args = []
|
||||
with patch("graphify.llm.extract_files_direct", side_effect=stub):
|
||||
result = extract_corpus_parallel(
|
||||
files,
|
||||
backend="kimi",
|
||||
token_budget=None,
|
||||
chunk_size=4,
|
||||
max_concurrency=1,
|
||||
on_chunk_done=lambda i, t, r: chunk_done_args.append((i, t, len(r["nodes"]))),
|
||||
)
|
||||
|
||||
# Adaptive retry runs INSIDE _run_one: 4 → 2 + 2 = 3 underlying API calls
|
||||
assert calls == [4, 2, 2]
|
||||
# User-visible: 1 chunk completion (the merged result)
|
||||
assert len(chunk_done_args) == 1
|
||||
assert chunk_done_args[0] == (0, 1, 4)
|
||||
assert len(result["nodes"]) == 4
|
||||
@@ -22,7 +22,7 @@ def test_install_contains_expected_rules(tmp_path):
|
||||
content = (tmp_path / "CLAUDE.md").read_text()
|
||||
assert "GRAPH_REPORT.md" in content
|
||||
assert "wiki/index.md" in content
|
||||
assert "_rebuild_code" in content
|
||||
assert "graphify update" in content
|
||||
|
||||
|
||||
def test_install_appends_to_existing_claude_md(tmp_path):
|
||||
@@ -109,7 +109,7 @@ def test_install_creates_settings_json(tmp_path):
|
||||
assert settings_path.exists()
|
||||
settings = json.loads(settings_path.read_text())
|
||||
hooks = settings.get("hooks", {}).get("PreToolUse", [])
|
||||
assert any("Glob|Grep" in h.get("matcher", "") for h in hooks)
|
||||
assert any(h.get("matcher") == "Bash" for h in hooks)
|
||||
|
||||
|
||||
def test_install_settings_json_idempotent(tmp_path):
|
||||
@@ -120,8 +120,8 @@ def test_install_settings_json_idempotent(tmp_path):
|
||||
settings_path = tmp_path / ".claude" / "settings.json"
|
||||
settings = json.loads(settings_path.read_text())
|
||||
hooks = settings.get("hooks", {}).get("PreToolUse", [])
|
||||
glob_grep_hooks = [h for h in hooks if "Glob|Grep" in h.get("matcher", "")]
|
||||
assert len(glob_grep_hooks) == 1
|
||||
bash_hooks = [h for h in hooks if h.get("matcher") == "Bash" and "graphify" in str(h)]
|
||||
assert len(bash_hooks) == 1
|
||||
|
||||
|
||||
def test_uninstall_removes_settings_hook(tmp_path):
|
||||
@@ -133,4 +133,4 @@ def test_uninstall_removes_settings_hook(tmp_path):
|
||||
if settings_path.exists():
|
||||
settings = json.loads(settings_path.read_text())
|
||||
hooks = settings.get("hooks", {}).get("PreToolUse", [])
|
||||
assert not any("Glob|Grep" in h.get("matcher", "") for h in hooks)
|
||||
assert not any(h.get("matcher") == "Bash" and "graphify" in str(h) for h in hooks)
|
||||
+21
-2
@@ -138,8 +138,27 @@ def test_detect_follows_symlinked_file(tmp_path):
|
||||
assert any("link.py" in f for f in code)
|
||||
|
||||
|
||||
def test_graphifyignore_discovered_from_parent(tmp_path):
|
||||
"""A .graphifyignore in a parent directory applies to subdirectory scans."""
|
||||
def test_graphifyignore_hermetic_without_vcs(tmp_path):
|
||||
"""Without a VCS root, parent .graphifyignore does NOT apply (hermetic)."""
|
||||
(tmp_path / ".graphifyignore").write_text("vendor/\n")
|
||||
sub = tmp_path / "packages" / "mylib"
|
||||
sub.mkdir(parents=True)
|
||||
(sub / "main.py").write_text("x = 1")
|
||||
vendor = sub / "vendor"
|
||||
vendor.mkdir()
|
||||
(vendor / "dep.py").write_text("y = 2")
|
||||
|
||||
result = detect(sub)
|
||||
code_files = result["files"]["code"]
|
||||
assert any("main.py" in f for f in code_files)
|
||||
# parent .graphifyignore must NOT leak into a non-VCS scan
|
||||
assert any("vendor" in f for f in code_files)
|
||||
assert result["graphifyignore_patterns"] == 0
|
||||
|
||||
|
||||
def test_graphifyignore_discovered_from_parent_in_vcs(tmp_path):
|
||||
"""Inside a VCS repo, parent .graphifyignore applies to subdirectory scans."""
|
||||
(tmp_path / ".git").mkdir()
|
||||
(tmp_path / ".graphifyignore").write_text("vendor/\n")
|
||||
sub = tmp_path / "packages" / "mylib"
|
||||
sub.mkdir(parents=True)
|
||||
|
||||
+27
-1
@@ -3,7 +3,7 @@ import tempfile
|
||||
from pathlib import Path
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster
|
||||
from graphify.export import to_json, to_cypher, to_graphml, to_html
|
||||
from graphify.export import to_json, to_cypher, to_graphml, to_html, to_canvas
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
@@ -125,3 +125,29 @@ def test_to_html_contains_nodes_and_edges():
|
||||
content = out.read_text()
|
||||
assert "RAW_NODES" in content
|
||||
assert "RAW_EDGES" in content
|
||||
|
||||
|
||||
def test_to_html_member_counts_accepted():
|
||||
"""to_html accepts member_counts without raising."""
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
member_counts = {cid: len(members) for cid, members in communities.items()}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.html"
|
||||
to_html(G, communities, str(out), member_counts=member_counts)
|
||||
assert out.exists()
|
||||
|
||||
|
||||
def test_to_canvas_file_paths_relative_to_vault():
|
||||
"""Node file paths in canvas must be vault-root-relative (just fname.md), not hardcoded."""
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.canvas"
|
||||
to_canvas(G, communities, str(out))
|
||||
data = json.loads(out.read_text())
|
||||
file_nodes = [n for n in data["nodes"] if n.get("type") == "file"]
|
||||
assert file_nodes, "canvas should contain file nodes"
|
||||
for node in file_nodes:
|
||||
assert "/" not in node["file"], f"file path should not contain '/': {node['file']}"
|
||||
assert node["file"].endswith(".md")
|
||||
@@ -124,6 +124,13 @@ def test_calls_edges_are_extracted():
|
||||
assert edge["weight"] == 1.0
|
||||
|
||||
|
||||
def test_python_call_edges_have_call_context():
|
||||
result = extract_python(FIXTURES / "sample_calls.py")
|
||||
call_edges = [e for e in result["edges"] if e["relation"] == "calls"]
|
||||
assert call_edges
|
||||
assert all(e.get("context") == "call" for e in call_edges)
|
||||
|
||||
|
||||
def test_calls_no_self_loops():
|
||||
result = extract_python(FIXTURES / "sample_calls.py")
|
||||
for edge in result["edges"]:
|
||||
@@ -168,3 +175,25 @@ def test_calls_deduplication():
|
||||
result = extract_python(FIXTURES / "sample_calls.py")
|
||||
call_pairs = [(e["source"], e["target"]) for e in result["edges"] if e["relation"] == "calls"]
|
||||
assert len(call_pairs) == len(set(call_pairs)), "Duplicate calls edges found"
|
||||
|
||||
|
||||
def test_cross_file_calls_skip_ambiguous_duplicate_labels(tmp_path):
|
||||
"""Unqualified cross-file calls must not guess between duplicate helper names."""
|
||||
caller = tmp_path / "caller.py"
|
||||
helper_a = tmp_path / "a.py"
|
||||
helper_b = tmp_path / "b.py"
|
||||
caller.write_text("def run():\n log()\n")
|
||||
helper_a.write_text("def log():\n return 'a'\n")
|
||||
helper_b.write_text("def log():\n return 'b'\n")
|
||||
|
||||
result = extract([caller, helper_a, helper_b], cache_root=tmp_path)
|
||||
nodes = {n["id"]: n for n in result["nodes"]}
|
||||
calls = [
|
||||
e for e in result["edges"]
|
||||
if e["relation"] == "calls" and e["confidence"] == "INFERRED"
|
||||
]
|
||||
|
||||
assert not any(
|
||||
nodes[e["source"]]["label"] == "run()" and nodes[e["target"]]["label"] == "log()"
|
||||
for e in calls
|
||||
)
|
||||
+34
-2
@@ -1,4 +1,5 @@
|
||||
"""Tests for hooks.py - git hook install/uninstall."""
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
@@ -23,7 +24,10 @@ def test_install_is_executable(tmp_path):
|
||||
repo = _make_git_repo(tmp_path)
|
||||
install(repo)
|
||||
hook = repo / ".git" / "hooks" / "post-commit"
|
||||
assert hook.stat().st_mode & 0o111 # executable bit set
|
||||
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):
|
||||
@@ -92,7 +96,10 @@ def test_install_post_checkout_is_executable(tmp_path):
|
||||
repo = _make_git_repo(tmp_path)
|
||||
install(repo)
|
||||
hook = repo / ".git" / "hooks" / "post-checkout"
|
||||
assert hook.stat().st_mode & 0o111
|
||||
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):
|
||||
@@ -110,3 +117,28 @@ def test_status_shows_both_hooks(tmp_path):
|
||||
assert "post-commit" in result
|
||||
assert "post-checkout" in result
|
||||
assert result.count("installed") >= 2
|
||||
|
||||
|
||||
def test_hook_skips_head_on_exe():
|
||||
"""Hook script must skip shebang extraction for .exe binaries (Windows)."""
|
||||
from graphify.hooks import _PYTHON_DETECT
|
||||
assert "*.exe) _SHEBANG=" in _PYTHON_DETECT or '*.exe)' in _PYTHON_DETECT
|
||||
|
||||
|
||||
def test_hook_check_no_additionalContext(tmp_path):
|
||||
"""graphify hook-check must not emit additionalContext — Codex Desktop rejects it."""
|
||||
import sys
|
||||
out = tmp_path / "graphify-out"
|
||||
out.mkdir()
|
||||
(out / "graph.json").write_text("{}", encoding="utf-8")
|
||||
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "graphify", "hook-check"],
|
||||
cwd=tmp_path,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
assert result.returncode == 0
|
||||
assert result.stdout == ""
|
||||
assert result.stderr == ""
|
||||
@@ -166,7 +166,7 @@ def _make_report(G):
|
||||
communities = {0: list(G.nodes())}
|
||||
cohesion = {0: 1.0}
|
||||
labels = {0: "All"}
|
||||
gods = [{"label": "BasicAuth", "edges": 2}]
|
||||
gods = [{"label": "BasicAuth", "degree": 2}]
|
||||
surprises = []
|
||||
return generate(G, communities, cohesion, labels, gods, surprises, SAMPLE_DETECTION, {"input": 10, "output": 5}, ".")
|
||||
|
||||
|
||||
+11
-10
@@ -8,7 +8,7 @@ PLATFORMS = {
|
||||
"claude": (".claude/skills/graphify/SKILL.md",),
|
||||
"codex": (".agents/skills/graphify/SKILL.md",),
|
||||
"opencode": (".config/opencode/skills/graphify/SKILL.md",),
|
||||
"claw": (".claw/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",),
|
||||
@@ -39,7 +39,7 @@ def test_install_opencode(tmp_path):
|
||||
|
||||
def test_install_claw(tmp_path):
|
||||
_install(tmp_path, "claw")
|
||||
assert (tmp_path / ".claw" / "skills" / "graphify" / "SKILL.md").exists()
|
||||
assert (tmp_path / ".openclaw" / "skills" / "graphify" / "SKILL.md").exists()
|
||||
|
||||
|
||||
def test_install_droid(tmp_path):
|
||||
@@ -116,9 +116,9 @@ def _agents_install(tmp_path, platform):
|
||||
_install_fn(tmp_path, platform)
|
||||
|
||||
|
||||
def _agents_uninstall(tmp_path):
|
||||
def _agents_uninstall(tmp_path, platform=""):
|
||||
from graphify.__main__ import _agents_uninstall as _uninstall_fn
|
||||
_uninstall_fn(tmp_path)
|
||||
_uninstall_fn(tmp_path, platform=platform)
|
||||
|
||||
|
||||
def test_codex_agents_install_writes_agents_md(tmp_path):
|
||||
@@ -194,9 +194,9 @@ def test_opencode_agents_install_writes_plugin(tmp_path):
|
||||
|
||||
|
||||
def test_opencode_agents_install_registers_plugin_in_config(tmp_path):
|
||||
"""opencode install registers the plugin in opencode.json."""
|
||||
"""opencode install registers the plugin in .opencode/opencode.json."""
|
||||
_agents_install(tmp_path, "opencode")
|
||||
config_file = tmp_path / "opencode.json"
|
||||
config_file = tmp_path / ".opencode" / "opencode.json"
|
||||
assert config_file.exists()
|
||||
import json as _json
|
||||
config = _json.loads(config_file.read_text())
|
||||
@@ -204,9 +204,10 @@ def test_opencode_agents_install_registers_plugin_in_config(tmp_path):
|
||||
|
||||
|
||||
def test_opencode_agents_install_merges_existing_config(tmp_path):
|
||||
"""opencode install preserves existing opencode.json keys."""
|
||||
"""opencode install preserves existing .opencode/opencode.json keys."""
|
||||
import json as _json
|
||||
config_file = tmp_path / "opencode.json"
|
||||
config_file = tmp_path / ".opencode" / "opencode.json"
|
||||
config_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
config_file.write_text(_json.dumps({"model": "claude-opus-4-5", "plugin": []}))
|
||||
_agents_install(tmp_path, "opencode")
|
||||
config = _json.loads(config_file.read_text())
|
||||
@@ -218,10 +219,10 @@ 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)
|
||||
_agents_uninstall(tmp_path, platform="opencode")
|
||||
plugin = tmp_path / ".opencode" / "plugins" / "graphify.js"
|
||||
assert not plugin.exists()
|
||||
config_file = tmp_path / "opencode.json"
|
||||
config_file = tmp_path / ".opencode" / "opencode.json"
|
||||
if config_file.exists():
|
||||
config = _json.loads(config_file.read_text())
|
||||
assert not any("graphify.js" in p for p in config.get("plugin", []))
|
||||
|
||||
+278
-2
@@ -1,11 +1,11 @@
|
||||
"""Tests for language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Go, Julia."""
|
||||
"""Tests for language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Go, Julia, JS/TS."""
|
||||
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,
|
||||
extract_swift, extract_go, extract_julia, extract_js,
|
||||
)
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
@@ -25,6 +25,22 @@ def _calls(r):
|
||||
}
|
||||
|
||||
|
||||
def _references(r):
|
||||
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
return [
|
||||
(
|
||||
node_by_id.get(e["source"], e["source"]),
|
||||
node_by_id.get(e["target"], e["target"]),
|
||||
e,
|
||||
)
|
||||
for e in r["edges"] if e["relation"] == "references"
|
||||
]
|
||||
|
||||
|
||||
def _edges_with_relation(r, *relations):
|
||||
return [e for e in r["edges"] if e["relation"] in relations]
|
||||
|
||||
|
||||
# ── Java ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_java_no_error():
|
||||
@@ -49,6 +65,13 @@ def test_java_finds_imports():
|
||||
r = extract_java(FIXTURES / "sample.java")
|
||||
assert "imports" in _relations(r)
|
||||
|
||||
|
||||
def test_java_import_edges_have_import_context():
|
||||
r = extract_java(FIXTURES / "sample.java")
|
||||
import_edges = _edges_with_relation(r, "imports", "imports_from")
|
||||
assert import_edges
|
||||
assert all(e.get("context") == "import" for e in import_edges)
|
||||
|
||||
def test_java_no_dangling_edges():
|
||||
r = extract_java(FIXTURES / "sample.java")
|
||||
node_ids = {n["id"] for n in r["nodes"]}
|
||||
@@ -83,6 +106,20 @@ def test_c_calls_are_extracted():
|
||||
assert e["confidence"] == "EXTRACTED"
|
||||
|
||||
|
||||
def test_c_import_edges_have_import_context():
|
||||
r = extract_c(FIXTURES / "sample.c")
|
||||
import_edges = _edges_with_relation(r, "imports", "imports_from")
|
||||
assert import_edges
|
||||
assert all(e.get("context") == "import" for e in import_edges)
|
||||
|
||||
|
||||
def test_c_call_edges_have_call_context():
|
||||
r = extract_c(FIXTURES / "sample.c")
|
||||
call_edges = _edges_with_relation(r, "calls")
|
||||
assert call_edges
|
||||
assert all(e.get("context") == "call" for e in call_edges)
|
||||
|
||||
|
||||
# ── C++ ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_cpp_no_error():
|
||||
@@ -104,6 +141,13 @@ def test_cpp_finds_includes():
|
||||
assert "imports" in _relations(r)
|
||||
|
||||
|
||||
def test_cpp_import_edges_have_import_context():
|
||||
r = extract_cpp(FIXTURES / "sample.cpp")
|
||||
import_edges = _edges_with_relation(r, "imports", "imports_from")
|
||||
assert import_edges
|
||||
assert all(e.get("context") == "import" for e in import_edges)
|
||||
|
||||
|
||||
# ── Ruby ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_ruby_no_error():
|
||||
@@ -164,6 +208,33 @@ def test_csharp_inherits_iprocessor():
|
||||
assert found, "DataProcessor should have inherits edge to IProcessor"
|
||||
|
||||
|
||||
def test_csharp_field_type_references_have_field_context():
|
||||
r = extract_csharp(FIXTURES / "sample.cs")
|
||||
refs = _references(r)
|
||||
assert any(
|
||||
"DataProcessor" in src and "HttpClient" in tgt and edge.get("context") == "field"
|
||||
for src, tgt, edge in refs
|
||||
), "DataProcessor field declarations should reference HttpClient with field context"
|
||||
|
||||
|
||||
def test_csharp_call_edges_have_call_context():
|
||||
r = extract_csharp(FIXTURES / "sample.cs")
|
||||
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
assert any(
|
||||
"Process" in node_by_id.get(e["source"], "")
|
||||
and "Validate" in node_by_id.get(e["target"], "")
|
||||
and e.get("context") == "call"
|
||||
for e in r["edges"] if e["relation"] == "calls"
|
||||
), "C# call edges should retain call context"
|
||||
|
||||
|
||||
def test_csharp_import_edges_have_import_context():
|
||||
r = extract_csharp(FIXTURES / "sample.cs")
|
||||
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
|
||||
assert import_edges
|
||||
assert all(e.get("context") == "import" for e in import_edges)
|
||||
|
||||
|
||||
# ── Kotlin ───────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_kotlin_no_error():
|
||||
@@ -188,6 +259,18 @@ def test_kotlin_finds_function():
|
||||
r = extract_kotlin(FIXTURES / "sample.kt")
|
||||
assert any("createClient" in l for l in _labels(r))
|
||||
|
||||
def test_kotlin_emits_in_file_calls():
|
||||
"""Regression test for the call-walker `simple_identifier` /
|
||||
`identifier` rename — see graphify-kmp's PythonParityTest."""
|
||||
r = extract_kotlin(FIXTURES / "sample.kt")
|
||||
calls = _calls(r)
|
||||
# In sample.kt: get() and post() both call buildRequest(), and
|
||||
# createClient() invokes Config and HttpClient (constructor calls).
|
||||
assert (".get()", ".buildRequest()") in calls
|
||||
assert (".post()", ".buildRequest()") in calls
|
||||
assert ("createClient()", "Config") in calls
|
||||
assert ("createClient()", "HttpClient") in calls
|
||||
|
||||
|
||||
# ── Scala ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -210,6 +293,20 @@ def test_scala_finds_methods():
|
||||
assert any("post" in l for l in labels)
|
||||
|
||||
|
||||
def test_scala_import_edges_have_import_context():
|
||||
r = extract_scala(FIXTURES / "sample.scala")
|
||||
import_edges = _edges_with_relation(r, "imports", "imports_from")
|
||||
assert import_edges
|
||||
assert all(e.get("context") == "import" for e in import_edges)
|
||||
|
||||
|
||||
def test_scala_call_edges_have_call_context():
|
||||
r = extract_scala(FIXTURES / "sample.scala")
|
||||
call_edges = _edges_with_relation(r, "calls")
|
||||
assert call_edges
|
||||
assert all(e.get("context") == "call" for e in call_edges)
|
||||
|
||||
|
||||
# ── PHP ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_php_no_error():
|
||||
@@ -235,6 +332,72 @@ def test_php_finds_imports():
|
||||
assert "imports" in _relations(r)
|
||||
|
||||
|
||||
def test_php_import_edges_have_import_context():
|
||||
r = extract_php(FIXTURES / "sample.php")
|
||||
import_edges = _edges_with_relation(r, "imports", "imports_from")
|
||||
assert import_edges
|
||||
assert all(e.get("context") == "import" for e in import_edges)
|
||||
|
||||
|
||||
def test_php_call_edges_have_call_context():
|
||||
r = extract_php(FIXTURES / "sample.php")
|
||||
call_edges = _edges_with_relation(r, "calls")
|
||||
assert call_edges
|
||||
assert all(e.get("context") == "call" for e in call_edges)
|
||||
|
||||
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():
|
||||
@@ -267,6 +430,13 @@ def test_swift_finds_imports():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
assert "imports" in _relations(r)
|
||||
|
||||
|
||||
def test_swift_import_edges_have_import_context():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
import_edges = _edges_with_relation(r, "imports", "imports_from")
|
||||
assert import_edges
|
||||
assert all(e.get("context") == "import" for e in import_edges)
|
||||
|
||||
def test_swift_no_dangling_edges():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
node_ids = {n["id"] for n in r["nodes"]}
|
||||
@@ -353,6 +523,12 @@ def test_swift_emits_calls():
|
||||
calls = _calls(r)
|
||||
assert any("process" in src and "validate" in tgt for src, tgt in calls)
|
||||
|
||||
def test_swift_call_edges_have_call_context():
|
||||
r = extract_swift(FIXTURES / "sample.swift")
|
||||
call_edges = _edges_with_relation(r, "calls")
|
||||
assert call_edges
|
||||
assert all(e.get("context") == "call" for e in call_edges)
|
||||
|
||||
|
||||
# ── Elixir ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -376,12 +552,26 @@ def test_elixir_finds_imports():
|
||||
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
|
||||
assert len(import_edges) >= 2
|
||||
|
||||
|
||||
def test_elixir_import_edges_have_import_context():
|
||||
r = extract_elixir(FIXTURES / "sample.ex")
|
||||
import_edges = _edges_with_relation(r, "imports", "imports_from")
|
||||
assert import_edges
|
||||
assert all(e.get("context") == "import" for e in import_edges)
|
||||
|
||||
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_call_edges_have_call_context():
|
||||
r = extract_elixir(FIXTURES / "sample.ex")
|
||||
call_edges = _edges_with_relation(r, "calls")
|
||||
assert call_edges
|
||||
assert all(e.get("context") == "call" for e in call_edges)
|
||||
|
||||
def test_elixir_method_edges():
|
||||
r = extract_elixir(FIXTURES / "sample.ex")
|
||||
methods = [e for e in r["edges"] if e["relation"] == "method"]
|
||||
@@ -416,6 +606,13 @@ def test_objc_finds_imports():
|
||||
assert len(import_edges) >= 1
|
||||
|
||||
|
||||
def test_objc_import_edges_have_import_context():
|
||||
r = extract_objc(FIXTURES / "sample.m")
|
||||
import_edges = _edges_with_relation(r, "imports", "imports_from")
|
||||
assert import_edges
|
||||
assert all(e.get("context") == "import" for e in import_edges)
|
||||
|
||||
|
||||
def test_objc_inherits_edge():
|
||||
r = extract_objc(FIXTURES / "sample.m")
|
||||
inherits = [e for e in r["edges"] if e["relation"] == "inherits"]
|
||||
@@ -491,6 +688,13 @@ def test_julia_finds_imports():
|
||||
assert len(import_edges) >= 1
|
||||
|
||||
|
||||
def test_julia_import_edges_have_import_context():
|
||||
r = extract_julia(FIXTURES / "sample.jl")
|
||||
import_edges = _edges_with_relation(r, "imports", "imports_from")
|
||||
assert import_edges
|
||||
assert all(e.get("context") == "import" for e in import_edges)
|
||||
|
||||
|
||||
def test_julia_finds_inherits():
|
||||
r = extract_julia(FIXTURES / "sample.jl")
|
||||
inherits = [e for e in r["edges"] if e["relation"] == "inherits"]
|
||||
@@ -503,8 +707,80 @@ def test_julia_finds_calls():
|
||||
assert len(call_edges) >= 1
|
||||
|
||||
|
||||
def test_julia_call_edges_have_call_context():
|
||||
r = extract_julia(FIXTURES / "sample.jl")
|
||||
call_edges = _edges_with_relation(r, "calls")
|
||||
assert call_edges
|
||||
assert all(e.get("context") == "call" for e in call_edges)
|
||||
|
||||
|
||||
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}"
|
||||
|
||||
|
||||
# ── TypeScript dynamic imports ───────────────────────────────────────────────
|
||||
|
||||
def test_ts_dynamic_import_no_error():
|
||||
r = extract_js(FIXTURES / "dynamic_import.ts")
|
||||
assert "error" not in r
|
||||
|
||||
def test_ts_dynamic_import_extracts_edges():
|
||||
"""Dynamic import() calls inside functions should produce imports_from edges."""
|
||||
r = extract_js(FIXTURES / "dynamic_import.ts")
|
||||
dyn_edges = [e for e in r["edges"] if e["relation"] == "imports_from"]
|
||||
targets = {e["target"] for e in dyn_edges}
|
||||
# Should find: static ./logger, dynamic ./mayaEngine.js, dynamic ./queue.js
|
||||
assert any("logger" in t for t in targets), f"Missing static import of logger: {targets}"
|
||||
assert any("mayaengine" in t.lower() for t in targets), f"Missing dynamic import of mayaEngine: {targets}"
|
||||
assert any("queue" in t.lower() for t in targets), f"Missing dynamic import of queue: {targets}"
|
||||
|
||||
def test_ts_dynamic_import_confidence():
|
||||
"""Dynamic imports should have EXTRACTED confidence (they are deterministic string literals)."""
|
||||
r = extract_js(FIXTURES / "dynamic_import.ts")
|
||||
dyn_edges = [e for e in r["edges"]
|
||||
if e["relation"] == "imports_from"
|
||||
and "mayaengine" in e["target"].lower()]
|
||||
assert len(dyn_edges) >= 1
|
||||
assert dyn_edges[0]["confidence"] == "EXTRACTED"
|
||||
|
||||
def test_ts_dynamic_import_source_is_function():
|
||||
"""Dynamic import edge source should be the enclosing function, not the file."""
|
||||
r = extract_js(FIXTURES / "dynamic_import.ts")
|
||||
node_labels = {n["id"]: n["label"] for n in r["nodes"]}
|
||||
dyn_edges = [e for e in r["edges"]
|
||||
if e["relation"] == "imports_from"
|
||||
and "mayaengine" in e["target"].lower()]
|
||||
assert len(dyn_edges) >= 1
|
||||
src_label = node_labels.get(dyn_edges[0]["source"], "")
|
||||
assert "processInbound" in src_label, f"Expected processInbound as source, got {src_label}"
|
||||
|
||||
def test_ts_no_dynamic_import_in_sync_fn():
|
||||
"""Functions without dynamic imports should not get spurious imports_from edges."""
|
||||
r = extract_js(FIXTURES / "dynamic_import.ts")
|
||||
node_ids = {n["label"]: n["id"] for n in r["nodes"]}
|
||||
sync_nid = node_ids.get("syncOnly()")
|
||||
if sync_nid:
|
||||
sync_imports = [e for e in r["edges"]
|
||||
if e["source"] == sync_nid and e["relation"] == "imports_from"]
|
||||
assert len(sync_imports) == 0
|
||||
|
||||
def test_ts_dynamic_template_literal_skipped():
|
||||
"""Dynamic template literals (with ${}) must not produce an imports_from edge."""
|
||||
r = extract_js(FIXTURES / "dynamic_import.ts")
|
||||
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
|
||||
# loadHandler uses `./handlers/${handlerName}` — no static path, must be absent
|
||||
assert not any("handler" in t.lower() and "$" in t for t in targets), \
|
||||
f"Garbage edge from dynamic template literal found: {targets}"
|
||||
# More robust: no target should contain a brace character
|
||||
assert not any("{" in t or "}" in t for t in targets), \
|
||||
f"Target contains unresolved template expression: {targets}"
|
||||
|
||||
def test_ts_static_template_literal_resolved():
|
||||
"""Static template literals (no ${}) should resolve the same as a plain string."""
|
||||
r = extract_js(FIXTURES / "dynamic_import.ts")
|
||||
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
|
||||
assert any("statichelper" in t.lower() for t in targets), \
|
||||
f"Static template literal import not resolved: {targets}"
|
||||
+83
-2
@@ -1,9 +1,9 @@
|
||||
"""Tests for multi-language AST extraction: JS/TS, Go, Rust."""
|
||||
"""Tests for multi-language AST extraction: JS/TS, Go, Rust, SQL."""
|
||||
from __future__ import annotations
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from graphify.extract import extract_js, extract_go, extract_rust, extract
|
||||
from graphify.extract import extract_js, extract_go, extract_rust, extract, extract_sql
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
@@ -24,6 +24,10 @@ def _confidences(result):
|
||||
return {e["confidence"] for e in result["edges"]}
|
||||
|
||||
|
||||
def _edges_with_relation(result, *relations):
|
||||
return [e for e in result["edges"] if e["relation"] in relations]
|
||||
|
||||
|
||||
# ── TypeScript ────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_ts_finds_class():
|
||||
@@ -53,6 +57,20 @@ def test_ts_calls_are_extracted():
|
||||
if e["relation"] == "calls":
|
||||
assert e["confidence"] == "EXTRACTED"
|
||||
|
||||
|
||||
def test_ts_import_edges_have_import_context():
|
||||
r = extract_js(FIXTURES / "sample.ts")
|
||||
import_edges = _edges_with_relation(r, "imports", "imports_from")
|
||||
assert import_edges
|
||||
assert all(e.get("context") == "import" for e in import_edges)
|
||||
|
||||
|
||||
def test_ts_call_edges_have_call_context():
|
||||
r = extract_js(FIXTURES / "sample.ts")
|
||||
call_edges = _edges_with_relation(r, "calls")
|
||||
assert call_edges
|
||||
assert all(e.get("context") == "call" for e in call_edges)
|
||||
|
||||
def test_ts_no_dangling_edges():
|
||||
r = extract_js(FIXTURES / "sample.ts")
|
||||
node_ids = {n["id"] for n in r["nodes"]}
|
||||
@@ -87,6 +105,20 @@ def test_go_has_extracted_calls():
|
||||
r = extract_go(FIXTURES / "sample.go")
|
||||
assert "EXTRACTED" in _confidences(r)
|
||||
|
||||
|
||||
def test_go_import_edges_have_import_context():
|
||||
r = extract_go(FIXTURES / "sample.go")
|
||||
import_edges = _edges_with_relation(r, "imports", "imports_from")
|
||||
assert import_edges
|
||||
assert all(e.get("context") == "import" for e in import_edges)
|
||||
|
||||
|
||||
def test_go_call_edges_have_call_context():
|
||||
r = extract_go(FIXTURES / "sample.go")
|
||||
call_edges = _edges_with_relation(r, "calls")
|
||||
assert call_edges
|
||||
assert all(e.get("context") == "call" for e in call_edges)
|
||||
|
||||
def test_go_no_dangling_edges():
|
||||
r = extract_go(FIXTURES / "sample.go")
|
||||
node_ids = {n["id"] for n in r["nodes"]}
|
||||
@@ -123,6 +155,20 @@ def test_rust_calls_are_extracted():
|
||||
if e["relation"] == "calls":
|
||||
assert e["confidence"] == "EXTRACTED"
|
||||
|
||||
|
||||
def test_rust_import_edges_have_import_context():
|
||||
r = extract_rust(FIXTURES / "sample.rs")
|
||||
import_edges = _edges_with_relation(r, "imports", "imports_from")
|
||||
assert import_edges
|
||||
assert all(e.get("context") == "import" for e in import_edges)
|
||||
|
||||
|
||||
def test_rust_call_edges_have_call_context():
|
||||
r = extract_rust(FIXTURES / "sample.rs")
|
||||
call_edges = _edges_with_relation(r, "calls")
|
||||
assert call_edges
|
||||
assert all(e.get("context") == "call" for e in call_edges)
|
||||
|
||||
def test_rust_no_dangling_edges():
|
||||
r = extract_rust(FIXTURES / "sample.rs")
|
||||
node_ids = {n["id"] for n in r["nodes"]}
|
||||
@@ -171,3 +217,38 @@ def test_cache_miss_after_file_change(tmp_path):
|
||||
# bar() should appear in the second result
|
||||
labels2 = [n["label"] for n in r2["nodes"]]
|
||||
assert any("bar" in l for l in labels2)
|
||||
|
||||
|
||||
# ── SQL ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_sql_finds_tables():
|
||||
r = extract_sql(FIXTURES / "sample.sql")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert any("users" in l for l in labels)
|
||||
assert any("organizations" in l for l in labels)
|
||||
|
||||
def test_sql_finds_view():
|
||||
r = extract_sql(FIXTURES / "sample.sql")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert any("active_users" in l for l in labels)
|
||||
|
||||
def test_sql_finds_function():
|
||||
r = extract_sql(FIXTURES / "sample.sql")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert any("get_user" in l for l in labels)
|
||||
|
||||
def test_sql_emits_foreign_key_edge():
|
||||
r = extract_sql(FIXTURES / "sample.sql")
|
||||
relations = {e["relation"] for e in r["edges"]}
|
||||
assert "references" in relations
|
||||
|
||||
def test_sql_emits_reads_from_edge():
|
||||
r = extract_sql(FIXTURES / "sample.sql")
|
||||
relations = {e["relation"] for e in r["edges"]}
|
||||
assert "reads_from" in relations
|
||||
|
||||
def test_sql_no_dangling_edges():
|
||||
r = extract_sql(FIXTURES / "sample.sql")
|
||||
node_ids = {n["id"] for n in r["nodes"]}
|
||||
for e in r["edges"]:
|
||||
assert e["source"] in node_ids, f"dangling source: {e['source']}"
|
||||
@@ -51,7 +51,7 @@ def run_pipeline(tmp_path: Path) -> dict:
|
||||
# Step 5: analyze
|
||||
gods = god_nodes(G)
|
||||
assert len(gods) > 0
|
||||
assert all("id" in g and "edges" in g for g in gods)
|
||||
assert all("id" in g and "degree" in g for g in gods)
|
||||
|
||||
surprises = surprising_connections(G, communities)
|
||||
assert isinstance(surprises, list)
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Tests for graphify query CLI context filtering."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
|
||||
import graphify.__main__ as mainmod
|
||||
|
||||
|
||||
def _write_graph(tmp_path):
|
||||
G = nx.Graph()
|
||||
G.add_node("n1", label="extract", source_file="extract.py", source_location="L10", community=0)
|
||||
G.add_node("n2", label="cluster", source_file="cluster.py", source_location="L5", community=0)
|
||||
G.add_node("n3", label="build", source_file="build.py", source_location="L1", community=1)
|
||||
G.add_edge("n1", "n2", relation="calls", confidence="EXTRACTED", context="call")
|
||||
G.add_edge("n2", "n3", relation="imports", confidence="EXTRACTED", context="import")
|
||||
graph_path = tmp_path / "graph.json"
|
||||
graph_path.write_text(json.dumps(json_graph.node_link_data(G, edges="links")))
|
||||
return graph_path
|
||||
|
||||
|
||||
def test_query_cli_explicit_context_filter(monkeypatch, tmp_path, capsys):
|
||||
graph_path = _write_graph(tmp_path)
|
||||
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
|
||||
monkeypatch.setattr(
|
||||
mainmod.sys,
|
||||
"argv",
|
||||
["graphify", "query", "extract", "--context", "call", "--graph", str(graph_path)],
|
||||
)
|
||||
mainmod.main()
|
||||
out = capsys.readouterr().out
|
||||
assert "Context: call (explicit)" in out
|
||||
assert "cluster" in out
|
||||
assert "build" not in out
|
||||
|
||||
|
||||
def test_query_cli_heuristic_context_filter(monkeypatch, tmp_path, capsys):
|
||||
graph_path = _write_graph(tmp_path)
|
||||
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
|
||||
monkeypatch.setattr(
|
||||
mainmod.sys,
|
||||
"argv",
|
||||
["graphify", "query", "who calls extract", "--graph", str(graph_path)],
|
||||
)
|
||||
mainmod.main()
|
||||
out = capsys.readouterr().out
|
||||
assert "Context: call (heuristic)" in out
|
||||
assert "cluster" in out
|
||||
assert "build" not in out
|
||||
@@ -57,7 +57,7 @@ def test_report_shows_token_cost():
|
||||
|
||||
def test_report_shows_raw_cohesion_scores():
|
||||
G, communities, cohesion, labels, gods, surprises, detection, tokens = make_inputs()
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, "./project")
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, "./project", min_community_size=1)
|
||||
assert "Cohesion:" in report
|
||||
assert "✓" not in report
|
||||
assert "⚠" not in report
|
||||
+47
-2
@@ -9,6 +9,10 @@ from graphify.serve import (
|
||||
_score_nodes,
|
||||
_bfs,
|
||||
_dfs,
|
||||
_filter_graph_by_context,
|
||||
_infer_context_filters,
|
||||
_query_graph_text,
|
||||
_resolve_context_filters,
|
||||
_subgraph_to_text,
|
||||
_load_graph,
|
||||
)
|
||||
@@ -21,8 +25,8 @@ def _make_graph() -> nx.Graph:
|
||||
G.add_node("n3", label="build", source_file="build.py", source_location="L1", community=1)
|
||||
G.add_node("n4", label="report", source_file="report.py", source_location="L1", community=1)
|
||||
G.add_node("n5", label="isolated", source_file="other.py", source_location="L1", community=2)
|
||||
G.add_edge("n1", "n2", relation="calls", confidence="INFERRED")
|
||||
G.add_edge("n2", "n3", relation="imports", confidence="EXTRACTED")
|
||||
G.add_edge("n1", "n2", relation="calls", confidence="INFERRED", context="call")
|
||||
G.add_edge("n2", "n3", relation="imports", confidence="EXTRACTED", context="import")
|
||||
G.add_edge("n3", "n4", relation="uses", confidence="EXTRACTED")
|
||||
return G
|
||||
|
||||
@@ -73,6 +77,16 @@ def test_score_nodes_source_file_partial():
|
||||
assert "n2" in nids
|
||||
|
||||
|
||||
def test_infer_context_filters_for_calls_question():
|
||||
assert _infer_context_filters("who calls extract") == ["call"]
|
||||
|
||||
|
||||
def test_resolve_context_filters_explicit_overrides_heuristic():
|
||||
filters, source = _resolve_context_filters("who calls extract", ["field"])
|
||||
assert filters == ["field"]
|
||||
assert source == "explicit"
|
||||
|
||||
|
||||
# --- _bfs ---
|
||||
|
||||
def test_bfs_depth_1():
|
||||
@@ -99,6 +113,15 @@ def test_bfs_returns_edges():
|
||||
assert any(u == "n1" or v == "n1" for u, v in edges)
|
||||
|
||||
|
||||
def test_filter_graph_by_context_limits_traversal():
|
||||
G = _make_graph()
|
||||
filtered = _filter_graph_by_context(G, ["call"])
|
||||
visited, edges = _bfs(filtered, ["n1"], depth=2)
|
||||
assert "n2" in visited
|
||||
assert "n3" not in visited
|
||||
assert edges == [("n1", "n2")]
|
||||
|
||||
|
||||
# --- _dfs ---
|
||||
|
||||
def test_dfs_depth_1():
|
||||
@@ -135,6 +158,28 @@ def test_subgraph_to_text_edge_included():
|
||||
assert "calls" in text
|
||||
|
||||
|
||||
def test_subgraph_to_text_includes_edge_context():
|
||||
G = _make_graph()
|
||||
text = _subgraph_to_text(G, {"n1", "n2"}, [("n1", "n2")])
|
||||
assert "context=call" in text
|
||||
|
||||
|
||||
def test_query_graph_text_explicit_context_filter_changes_traversal():
|
||||
G = _make_graph()
|
||||
text = _query_graph_text(G, "extract", mode="bfs", depth=2, token_budget=2000, context_filters=["call"])
|
||||
assert "Context: call (explicit)" in text
|
||||
assert "cluster" in text
|
||||
assert "build" not in text
|
||||
|
||||
|
||||
def test_query_graph_text_heuristic_context_filter_changes_traversal():
|
||||
G = _make_graph()
|
||||
text = _query_graph_text(G, "who calls extract", mode="bfs", depth=2, token_budget=2000)
|
||||
assert "Context: call (heuristic)" in text
|
||||
assert "cluster" in text
|
||||
assert "build" not in text
|
||||
|
||||
|
||||
# --- _load_graph ---
|
||||
|
||||
def test_load_graph_roundtrip(tmp_path):
|
||||
|
||||
@@ -52,6 +52,34 @@ def test_watched_extensions_excludes_noise():
|
||||
|
||||
# --- watch() import error without watchdog ---
|
||||
|
||||
def test_check_update_no_flag_returns_true(tmp_path):
|
||||
"""check_update returns True and is silent when needs_update flag is absent."""
|
||||
from graphify.watch import check_update
|
||||
assert check_update(tmp_path) is True
|
||||
|
||||
|
||||
def test_check_update_with_flag_returns_true_and_prints(tmp_path, capsys):
|
||||
"""check_update returns True and prints notification when flag exists."""
|
||||
from graphify.watch import check_update
|
||||
flag = tmp_path / "graphify-out" / "needs_update"
|
||||
flag.parent.mkdir(parents=True, exist_ok=True)
|
||||
flag.write_text("1")
|
||||
result = check_update(tmp_path)
|
||||
assert result is True
|
||||
out = capsys.readouterr().out
|
||||
assert "graphify --update" in out
|
||||
|
||||
|
||||
def test_check_update_does_not_clear_flag(tmp_path):
|
||||
"""check_update never removes the needs_update flag (clearing is LLM's job)."""
|
||||
from graphify.watch import check_update
|
||||
flag = tmp_path / "graphify-out" / "needs_update"
|
||||
flag.parent.mkdir(parents=True, exist_ok=True)
|
||||
flag.write_text("1")
|
||||
check_update(tmp_path)
|
||||
assert flag.exists()
|
||||
|
||||
|
||||
def test_watch_raises_without_watchdog(tmp_path, monkeypatch):
|
||||
import builtins
|
||||
real_import = builtins.__import__
|
||||
|
||||
+2
-2
@@ -20,7 +20,7 @@ def _make_graph():
|
||||
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", "edges": 2}]
|
||||
GOD_NODES = [{"id": "n1", "label": "parse", "degree": 2}]
|
||||
|
||||
|
||||
def test_to_wiki_writes_index(tmp_path):
|
||||
@@ -105,7 +105,7 @@ def test_god_node_article_links_community(tmp_path):
|
||||
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", "edges": 99}]
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user