Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
441ac9fc38 | ||
|
|
25c1ea9212 | ||
|
|
0010d38337 | ||
|
|
06df2066a8 | ||
|
|
12a706b595 | ||
|
|
189cdd92c9 | ||
|
|
519564b742 | ||
|
|
660b605e18 | ||
|
|
e22a189df1 | ||
|
|
6fa2ba2318 | ||
|
|
3457b9cd80 | ||
|
|
48888a7c26 | ||
|
|
69d2cc84e2 | ||
|
|
21e096fd88 | ||
|
|
2415576ab0 | ||
|
|
005a36608a | ||
|
|
cc63a1711b | ||
|
|
64585cf889 | ||
|
|
a9cb692961 | ||
|
|
9a8346d39a | ||
|
|
6aecfcf0fe | ||
|
|
dc69020a47 | ||
|
|
b68ec63494 | ||
|
|
0dfc26e57f | ||
|
|
5f5b59309c | ||
|
|
49c3b50b5f | ||
|
|
0267cd789f | ||
|
|
2b1efe8f08 | ||
|
|
ee85bbfbfd | ||
|
|
5b33e6d2e6 | ||
|
|
579e1cc744 | ||
|
|
913feca6a6 | ||
|
|
4f08e23807 | ||
|
|
b3c99ec0ed | ||
|
|
682d124618 | ||
|
|
239000d2c9 | ||
|
|
ec413d5233 | ||
|
|
34380434c4 | ||
|
|
b26467a8eb | ||
|
|
b5e7cf3f55 | ||
|
|
5ee4b01406 | ||
|
|
cddf9cf9bf | ||
|
|
09b33b795b | ||
|
|
68081c1c89 | ||
|
|
6c3ccdc77b | ||
|
|
26a5a35200 | ||
|
|
741ac3655b | ||
|
|
c1a7e250b6 | ||
|
|
c121fc4e42 | ||
|
|
6e84b42320 | ||
|
|
d40e27463d | ||
|
|
b6ffdbb8dd | ||
|
|
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 |
No files matched your search
@@ -2,9 +2,10 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["v1", "v2", "v3", "v4", "main"]
|
||||
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "main"]
|
||||
pull_request:
|
||||
branches: ["v1", "v2", "v3", "v4", "main"]
|
||||
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "main"]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
@@ -23,7 +24,7 @@ jobs:
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pip install -e ".[mcp,pdf,watch]"
|
||||
pip install -e ".[mcp,pdf,watch,sql]"
|
||||
pip install pytest
|
||||
|
||||
- name: Run tests
|
||||
|
||||
+219
@@ -2,6 +2,225 @@
|
||||
|
||||
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
|
||||
|
||||
## 0.7.8 (2026-05-06)
|
||||
|
||||
- Feat: Gemini and OpenAI backends -- `graphify extract ./docs --backend gemini` (GEMINI_API_KEY / GOOGLE_API_KEY) or `--backend openai` (OPENAI_API_KEY); `[gemini]` and `[openai]` extras added (#735)
|
||||
- Feat: Groovy and Spock support -- `.groovy` and `.gradle` extracted via tree-sitter-groovy; Spock spec files (`def "feature"()` syntax) handled via regex fallback (#732)
|
||||
- Feat: Luau support -- `.luau` (Roblox Luau) added to code extraction using the Lua tree-sitter parser (#745)
|
||||
- Feat: Markdown structural extraction -- headings, fenced code blocks, and nesting hierarchy extracted as graph nodes from `.md` and `.mdx` files with zero new dependencies (#711)
|
||||
- Fix: `collect_files()` extension set now auto-syncs with `_DISPATCH` -- previously 18 extensions (`.sql`, `.vue`, `.svelte`, `.jsx`, `.ex`, `.jl`, etc.) were silently skipped in skill-mode extraction (#711)
|
||||
- Fix: `detect_incremental` now forwards `follow_symlinks` to `detect()` -- symlinked subtrees no longer vanish on `--update` runs (#736)
|
||||
- Fix: TS bare-path / `.svelte.ts` / `.svelte.js` / `index.ts` directory / multi-dot imports now resolve correctly -- previously these produced phantom edges dropped at merge time (#717, #716)
|
||||
- Fix: `cluster-only` now loads and saves `.graphify_labels.json` -- human-readable community labels survive re-clustering instead of resetting to "Community N" (#744)
|
||||
- Fix: `graphify export wiki` now fails fast with exit 1 if `.graphify_analysis.json` is missing -- prevents silent deletion of existing wiki articles (#746)
|
||||
- Fix: `to_wiki()` now raises before the cleanup loop when `communities` is empty -- second safety layer against wiki data loss (#746)
|
||||
- Fix: Ollama import error message now says "Ollama" not "Kimi" and points to `pip install openai`; `[ollama]` extras group added (#750)
|
||||
- Security: hooks.py path execution now validates scripts are within the repo root -- closes supply-chain attack vector where a malicious commit could redirect hook execution (#747)
|
||||
|
||||
## 0.7.7 (2026-05-05)
|
||||
|
||||
- Feat: Ollama backend for headless extraction -- `graphify extract ./docs --backend ollama`; auto-detected when `OLLAMA_BASE_URL` is set; defaults to `qwen2.5-coder:7b`; zero cost ($0.00); sentinel API key handles OpenAI client auth requirement (#729)
|
||||
- Feat: Cross-project global graph at `~/.graphify/global.json` -- `graphify global add/remove/list/path` to register multiple project graphs with `<repo>::<id>` prefixed node IDs, preventing silent collisions; hash-based skip avoids re-ingesting unchanged graphs (#729)
|
||||
- Feat: `graphify extract --global --as <tag>` flag -- after building a project graph, auto-registers it into the global graph in one step (#729)
|
||||
- Feat: `merge-graphs` now prefix-relabels each input graph before composing, preventing silent node ID collisions when two projects share entity names (#729)
|
||||
- Fix: `deduplicate_entities` raises `ValueError` if called with nodes spanning multiple repos (cross-project dedup disabled by design -- per-project graphs are deduplicated in isolation) (#729)
|
||||
- Fix: `detect_incremental()` now accepts and forwards `follow_symlinks` to `detect()`. Without this, `--update` runs silently miss any files reached through a symlinked sub-tree (e.g. `state_of_truth/` symlinking to a directory outside the corpus root), even when the original full run had detected them. Previously the flag was on `detect()` and `collect_files()` only. (#736)
|
||||
|
||||
## 0.7.6 (2026-05-05)
|
||||
|
||||
- Fix: `cluster-only` now accepts `--graph <path>` to specify a non-default graph.json location; positional path and flags can appear in any order (#724)
|
||||
- Fix: `_is_sensitive()` no longer drops legitimate source files — word boundaries on the keyword pattern prevent false positives like `tokenizer.py`, `password_verification.py`, `SecretManager.java` (#718)
|
||||
- Fix: `graphify extract --backend claude/kimi` raises default `max_tokens` from 8192 → 16384, eliminating the truncation-then-recursive-split cascade on dense doc corpora; respects `GRAPHIFY_MAX_OUTPUT_TOKENS` env var (#730)
|
||||
- Fix: `--update` prune message now clearly distinguishes "N nodes pruned from M deleted files" from "M deletions detected but graph already clean — no drift" (#539)
|
||||
- Fix: `extract_svelte()` stub nodes now carry the resolved import path as `source_file` instead of the importer's path, preventing metadata corruption after merge (#712)
|
||||
- Fix: `extract_svelte()` now catches static `import X from './foo.svelte'` via a dedicated regex pass over `<script>` block content — previously tree-sitter's JS parser silently dropped all static imports in `.svelte` files (#713)
|
||||
- Fix: `graphify extract` (full rebuild path) now saves `manifest.json` on every successful run, not only on `--update`; prevents stale-manifest drift on subsequent incremental runs (#538)
|
||||
- Fix: `graphify antigravity install` now writes to `.agent/` (no trailing s) matching Antigravity's actual config paths (#704)
|
||||
- Fix: Pi skill YAML frontmatter description simplified to avoid "nested mappings" parse error on Pi startup (#737)
|
||||
- Fix: `--dedup-llm` flag now correctly threads LLM backend through to `deduplicate_entities` in both fresh and incremental extract paths; fresh extract path now also runs dedup (previously called `build_from_json` directly, bypassing dedup entirely)
|
||||
|
||||
## 0.7.5 (2026-05-04)
|
||||
|
||||
- Feat: `graphify extract` now runs incrementally - auto-detects prior `manifest.json` and re-extracts only changed/new files; semantic results cached by content hash so unchanged docs cost zero LLM tokens on repeat runs (#698)
|
||||
- Feat: Entity deduplication pipeline runs on every build - entropy gate + MinHash/LSH blocking + Jaro-Winkler verification + same-community boost collapses near-duplicate entities (typos, spacing, plurals) before clustering
|
||||
- Feat: `--dedup-llm` flag for `graphify extract` - optional LLM tiebreaker for ambiguous entity pairs (~$0.01 for 10k-node graphs), off by default
|
||||
- Fix: `graphify hook install` rebuild now preserves human-readable community labels from `.graphify_labels.json` instead of resetting to generic "Community N" names on every commit (#705)
|
||||
- Fix: `graphify install --platform gemini` now works correctly (#706)
|
||||
- Deps: `datasketch` and `rapidfuzz` added as base dependencies
|
||||
|
||||
## 0.7.4 (2026-05-04)
|
||||
|
||||
- Fix: `_read_tsconfig_aliases()` now parses JSONC — handles `//` line comments, `/* */` block comments, and trailing commas that every TypeScript framework starter generates; warns to stderr on parse failure instead of silently returning `{}` (#700)
|
||||
- Fix: `extract_svelte()` regex fallback now captures aliased dynamic imports (`$lib/...`, `$partials/...`, `@/...`) and uses correct `_make_id(str(path))` scheme so edges survive into `graph.json` instead of being dropped as phantom nodes (#701)
|
||||
|
||||
## 0.7.3 (2026-05-04)
|
||||
|
||||
- Feat: `graphify extract <path>` — headless full-pipeline extraction for CI; runs AST extraction on code files and semantic LLM extraction on docs/papers/images without Claude Code in the loop; supports `--backend kimi|claude`, `--out DIR`, `--no-cluster`; auto-detects backend from `MOONSHOT_API_KEY` / `ANTHROPIC_API_KEY`; docs-only corpora (issue #698) work cleanly
|
||||
- Fix: export/query/path/explain CLI subcommands added in 0.7.2 now ship with integration tests
|
||||
- Fix: skill.md reduced from 63KB to 47KB by replacing Python heredocs with CLI calls (#696)
|
||||
|
||||
## 0.7.2 (2026-05-04)
|
||||
|
||||
- Feat: Fortran support - extracts modules, subroutines, functions, programs, `use` imports, and `call` edges from `.f`, `.F`, `.f90`, `.F90`, `.f95`, `.F95`, `.f03`, `.F03`, `.f08`, `.F08` files; names are lowercased for case-insensitive matching (#694)
|
||||
|
||||
## 0.7.1 (2026-05-04)
|
||||
|
||||
- Fix: Obsidian export - community labels with `.`, `&`, `(`, `)` now produce valid Obsidian tags; only `[a-zA-Z0-9_\-/]` characters survive, preventing broken Dataview queries (#690)
|
||||
- Fix: `_load_tsconfig_aliases()` now follows tsconfig `extends` chains - SvelteKit, Nuxt, and NestJS path aliases defined in extended configs are no longer silently dropped (#691)
|
||||
- Fix: `.svelte` files now get a regex pass over the template layer after JS AST extraction - `{#await import('./X.svelte')}` markup-level dynamic imports are captured as edges (#692)
|
||||
- Fix: recursion limit raised to 10,000 at extract entry points (main process + each worker) with a `_safe_extract` wrapper that skips pathological files with a clear warning instead of crashing the whole run (#695)
|
||||
|
||||
## 0.7.0 (2026-05-03)
|
||||
|
||||
Multi-dev busy-repo support: four gaps that caused merge conflicts, stale graphs, and silent cache misses in team workflows.
|
||||
|
||||
- Feat: `graphify hook install` now also configures a git merge driver for `graphify-out/graph.json` — union-merges two graph.json files so git never produces conflict markers in the knowledge graph; writes `.gitattributes` and registers `graphify merge-driver` in `.git/config`
|
||||
- Feat: `graphify merge-driver <base> <current> <other>` subcommand — takes two graph.json variants and writes their node/edge union back to `<current>`; always exits 0 so merge never blocks
|
||||
- Feat: Leiden community detection now seeded (`seed=42` when supported) for deterministic community IDs across parallel rebuilds — reduces JSON diff churn in multi-dev repos
|
||||
- Feat: `graph.json` now embeds `built_at_commit` (git HEAD) at write time; `GRAPH_REPORT.md` surfaces the commit hash and a freshness check hint
|
||||
- Fix: `file_hash` is now content-only (path removed from hash) — renamed files reuse their cache entry instead of re-extracting; cached `source_file` fields are updated to the new path on load
|
||||
- Fix: watch mode mixed-batch handling — commits with both code and non-code files now rebuild code immediately AND write `needs_update` flag; previously code changes were silently dropped in mixed batches
|
||||
|
||||
## 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)
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
</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://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=v7" 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>
|
||||
@@ -20,67 +21,45 @@
|
||||
</a>
|
||||
</p>
|
||||
|
||||
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, or Google Antigravity - it reads your files, builds a knowledge graph, and gives you back structure you didn't know was there. Understand a codebase faster. Find the "why" behind architectural decisions.
|
||||
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.
|
||||
|
||||
Fully multimodal. Drop in code, PDFs, markdown, screenshots, diagrams, whiteboard photos, images in other languages, or video and audio files - graphify extracts concepts and relationships from all of it and connects them into one graph. Videos are transcribed with Whisper using a domain-aware prompt derived from your corpus. 25 languages supported via tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
|
||||
|
||||
> Andrej Karpathy keeps a `/raw` folder where he drops papers, tweets, screenshots, and notes. graphify is the answer to that problem - 71.5x fewer tokens per query vs reading the raw files, persistent across sessions, honest about what it found vs guessed.
|
||||
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 - open in any browser, 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`. You can keep a single `.graphifyignore` at your repo root — patterns work correctly even when graphify is run on a subfolder.
|
||||
|
||||
## 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), [VS Code Copilot Chat](https://code.visualstudio.com/docs/copilot/overview), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), [Trae](https://trae.ai), [Kiro](https://kiro.dev), Hermes, or [Google Antigravity](https://antigravity.google)
|
||||
**Requires Python 3.10+**
|
||||
|
||||
```bash
|
||||
# Recommended — works on Mac and Linux with no PATH setup needed
|
||||
uv tool install graphifyy && graphify install
|
||||
# or with pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# or plain pip
|
||||
pip 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`.
|
||||
|
||||
> **`graphify: command not found`?** Use `uv tool install graphifyy` (recommended) or `pipx install graphifyy` — both put the CLI in a managed location that's automatically on PATH. With plain `pip`, you may need to add `~/.local/bin` (Linux) or `~/Library/Python/3.x/bin` (Mac) to your PATH, or run `python -m graphify` instead. On Windows, pip scripts land in `%APPDATA%\Python\PythonXY\Scripts`.
|
||||
> **`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`.
|
||||
|
||||
### Platform support
|
||||
### 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` |
|
||||
@@ -93,22 +72,18 @@ pip install graphifyy && graphify install
|
||||
| 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 supports PreToolUse hooks — `graphify codex install` installs one in `.codex/hooks.json` in addition to writing AGENTS.md.
|
||||
> 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 |
|
||||
|----------|---------|
|
||||
@@ -126,319 +101,227 @@ After building a graph, run this once in your project:
|
||||
| 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, OpenClaw, Factory Droid, Trae, and Hermes** write the same rules to `AGENTS.md` in your project root and copy the skill to the platform's global skill directory. These platforms don't support tool hooks, so AGENTS.md is the always-on mechanism.
|
||||
---
|
||||
|
||||
**Kiro IDE/CLI** writes the skill to `.kiro/skills/graphify/SKILL.md` (invoked via `/graphify`) and a steering file to `.kiro/steering/graphify.md` with `inclusion: always` — Kiro injects this into every conversation automatically, no hook needed.
|
||||
## What files it handles
|
||||
|
||||
**Google Antigravity** writes `.agents/rules/graphify.md` (always-on rules) and `.agents/workflows/graphify.md` (registers `/graphify` as a slash command). No hook equivalent exists in Antigravity — rules are the always-on mechanism.
|
||||
| Type | Extensions |
|
||||
|------|-----------|
|
||||
| Code (28 languages) | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .jl .vue .svelte .groovy .gradle .sql .f .F .f90 .F90 .f95 .F95 .f03 .F03 .f08 .F08` |
|
||||
| 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]`) |
|
||||
|
||||
**GitHub Copilot CLI** copies the skill to `~/.copilot/skills/graphify/SKILL.md`. Run `graphify copilot install` to set it up.
|
||||
Code is extracted locally with no API calls (AST via tree-sitter). Everything else goes through your AI assistant's model API.
|
||||
|
||||
**VS Code Copilot Chat** installs a Python-only skill (works on Windows PowerShell and macOS/Linux alike) and writes `.github/copilot-instructions.md` in your project root — VS Code reads this automatically every session, making graph context always-on without any hook mechanism. Run `graphify vscode install`. Note: this configures the chat panel in VS Code, not the Copilot CLI terminal tool.
|
||||
---
|
||||
|
||||
Uninstall with the matching uninstall command (e.g. `graphify claude uninstall`).
|
||||
## Common commands
|
||||
|
||||
**Always-on vs explicit trigger — what's the difference?**
|
||||
```bash
|
||||
/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
|
||||
|
||||
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 "what connects auth to the database?"
|
||||
/graphify path "UserService" "DatabasePool"
|
||||
/graphify explain "RateLimiter"
|
||||
|
||||
`/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.
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper and add it
|
||||
/graphify add <youtube-url> # transcribe and add a video
|
||||
|
||||
Think of it this way: the always-on hook gives your assistant a map. The `/graphify` commands let it navigate the map precisely.
|
||||
graphify hook install # auto-rebuild on git commit
|
||||
graphify merge-graphs a.json b.json # combine two graphs
|
||||
```
|
||||
|
||||
### Team workflows
|
||||
See the [full command reference](#full-command-reference) below.
|
||||
|
||||
`graphify-out/` is designed to be committed to git so every teammate starts with a fresh map.
|
||||
---
|
||||
|
||||
## 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:**
|
||||
```
|
||||
# keep graph outputs, skip heavy/local-only files
|
||||
graphify-out/cache/ # optional: commit for shared extraction speed, skip to keep repo small
|
||||
graphify-out/manifest.json # mtime-based, invalid after git clone — always gitignore this
|
||||
graphify-out/cost.json # local token tracking, not useful to share
|
||||
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
|
||||
```
|
||||
|
||||
**Shared setup:**
|
||||
1. One person runs `/graphify .` to build the initial graph and commits `graphify-out/`.
|
||||
2. Everyone else pulls — their assistant reads `GRAPH_REPORT.md` immediately with no extra steps.
|
||||
3. Install the post-commit hook (`graphify hook install`) so the graph rebuilds automatically after code changes — no LLM calls needed for code-only updates.
|
||||
4. For doc/paper changes, whoever edits the files runs `/graphify --update` to refresh semantic nodes.
|
||||
**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). This also sets up a git merge driver so `graph.json` is never left with conflict markers — two devs committing in parallel get their graphs union-merged automatically.
|
||||
4. When docs or papers change, run `/graphify --update` to refresh those nodes.
|
||||
|
||||
**Excluding paths** — create `.graphifyignore` in your project root (same syntax as `.gitignore`). Files matching those patterns are skipped during detection and extraction.
|
||||
---
|
||||
|
||||
```
|
||||
# .graphifyignore example
|
||||
AGENTS.md # graphify install files — don't extract your own instructions as knowledge
|
||||
CLAUDE.md
|
||||
GEMINI.md
|
||||
.gemini/
|
||||
.opencode/
|
||||
docs/translations/ # generated content you don't want in the graph
|
||||
```
|
||||
|
||||
## 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:
|
||||
## Using the graph directly
|
||||
|
||||
```bash
|
||||
graphify query "show the auth flow" --graph graphify-out/graph.json
|
||||
# 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`.
|
||||
|
||||
> **WSL / Linux note:** Ubuntu ships `python3`, not `python`. Install into a project venv to avoid PEP 668 conflicts, and use the full venv path in your `.mcp.json`:
|
||||
> **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]"
|
||||
> ```
|
||||
> ```json
|
||||
> { "mcpServers": { "graphify": { "type": "stdio", "command": ".venv/bin/python3", "args": ["-m", "graphify.serve", "graphify-out/graph.json"] } } }
|
||||
> ```
|
||||
> Also note: the PyPI package is `graphifyy` (double-y) — `pip install graphify` installs an unrelated package.
|
||||
|
||||
<details>
|
||||
<summary>Manual install (curl)</summary>
|
||||
---
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/graphify
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v4/graphify/skill.md \
|
||||
> ~/.claude/skills/graphify/SKILL.md
|
||||
```
|
||||
## Privacy
|
||||
|
||||
Add to `~/.claude/CLAUDE.md`:
|
||||
- **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 for semantic extraction (via the `/graphify` skill, using whatever model your IDE session runs). Headless `graphify extract` requires `GEMINI_API_KEY` / `GOOGLE_API_KEY` (Gemini), `MOONSHOT_API_KEY` (Kimi), `ANTHROPIC_API_KEY` (Claude), `OPENAI_API_KEY` (OpenAI), or a running Ollama instance (`OLLAMA_BASE_URL`). The `--dedup-llm` flag uses the same key.
|
||||
- No telemetry, no usage tracking, no analytics.
|
||||
|
||||
```
|
||||
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
|
||||
```
|
||||
---
|
||||
|
||||
</details>
|
||||
|
||||
## 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 <video-url> # download audio, transcribe, add to graph
|
||||
/graphify add https://... --author "Name" # tag the original author
|
||||
/graphify add https://... --contributor "Name" # tag who added it to the corpus
|
||||
/graphify 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 + PreToolUse hook in .codex/hooks.json (Codex)
|
||||
graphify opencode install # AGENTS.md + tool.execute.before plugin (OpenCode)
|
||||
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
|
||||
graphify cursor uninstall
|
||||
graphify gemini install # GEMINI.md + BeforeTool hook (Gemini CLI)
|
||||
graphify gemini uninstall
|
||||
graphify copilot install # skill file (GitHub Copilot CLI)
|
||||
graphify copilot uninstall
|
||||
graphify aider install # AGENTS.md (Aider)
|
||||
graphify aider uninstall
|
||||
graphify claw install # AGENTS.md (OpenClaw)
|
||||
graphify droid install # AGENTS.md (Factory Droid)
|
||||
graphify trae install # AGENTS.md (Trae)
|
||||
graphify trae uninstall
|
||||
graphify trae-cn install # AGENTS.md (Trae CN)
|
||||
graphify trae-cn uninstall
|
||||
graphify hermes install # AGENTS.md + ~/.hermes/skills/ (Hermes)
|
||||
graphify hermes uninstall
|
||||
graphify kiro install # .kiro/skills/ + .kiro/steering/graphify.md (Kiro IDE/CLI)
|
||||
graphify kiro uninstall
|
||||
graphify antigravity install # .agents/rules + .agents/workflows (Google Antigravity)
|
||||
graphify antigravity 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 and navigate the graph directly from the terminal (no AI assistant needed)
|
||||
graphify query "what connects attention to the optimizer?"
|
||||
graphify query "show the auth flow" --dfs
|
||||
graphify query "what is CfgNode?" --budget 500
|
||||
graphify query "..." --graph path/to/graph.json
|
||||
graphify path "DigestAuth" "Response" # shortest path between two nodes
|
||||
graphify explain "SwinTransformer" # plain-language explanation of a node
|
||||
graphify extract ./docs # headless LLM extraction for CI (no IDE needed)
|
||||
graphify extract ./docs --backend gemini # explicit backend: gemini, kimi, claude, openai, or ollama
|
||||
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
|
||||
graphify extract ./docs --backend ollama # local Ollama (set OLLAMA_BASE_URL / OLLAMA_MODEL)
|
||||
graphify extract ./docs --no-cluster # raw extraction only, skip clustering
|
||||
graphify extract ./docs --dedup-llm # LLM tiebreaker for ambiguous entity pairs (uses same API key)
|
||||
graphify extract ./docs --global --as myrepo # extract and register into the cross-project global graph
|
||||
GRAPHIFY_MAX_OUTPUT_TOKENS=32768 graphify extract ./docs --backend claude # raise output cap for dense corpora
|
||||
|
||||
# add content and update the graph from the terminal
|
||||
graphify add https://arxiv.org/abs/1706.03762 # fetch paper, save to ./raw, update graph
|
||||
graphify add https://... --author "Name" --contributor "Name"
|
||||
graphify global add graphify-out/graph.json myrepo # register a project graph into ~/.graphify/global.json
|
||||
graphify global remove myrepo # remove a project from the global graph
|
||||
graphify global list # show all registered repos + node/edge counts
|
||||
graphify global path # print path to the global graph file
|
||||
|
||||
# incremental update and maintenance
|
||||
graphify watch ./src # auto-rebuild on code changes
|
||||
graphify check-update ./src # check if semantic re-extraction is pending (cron-safe)
|
||||
graphify update ./src # re-extract code files, no LLM needed
|
||||
graphify cluster-only ./my-project # rerun clustering on existing graph.json
|
||||
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
|
||||
graphify cluster-only ./my-project --graph path/to/graph.json # custom graph location
|
||||
```
|
||||
|
||||
Works with any mix of file types:
|
||||
---
|
||||
|
||||
| Type | Extensions | Extraction |
|
||||
|------|-----------|------------|
|
||||
| Code | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl .vue .svelte` | AST via tree-sitter + call-graph (cross-file for all languages) + Java extends/implements + docstring/comment rationale |
|
||||
| Docs | `.md .mdx .html .txt .rst` | Concepts + relationships + design rationale via Claude |
|
||||
| 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
|
||||
|
||||
## Video and audio corpus
|
||||
- [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
|
||||
|
||||
Drop video or audio files into your corpus folder alongside your code and docs — graphify picks them up automatically:
|
||||
|
||||
```bash
|
||||
pip install 'graphifyy[video]' # one-time setup
|
||||
/graphify ./my-corpus # transcribes any video/audio files it finds
|
||||
```
|
||||
|
||||
Add a YouTube video (or any public video URL) directly:
|
||||
|
||||
```bash
|
||||
/graphify add <video-url>
|
||||
```
|
||||
|
||||
yt-dlp downloads audio-only (fast, small), Whisper transcribes it locally, and the transcript is fed into the same extraction pipeline as your other docs. Transcripts are cached in `graphify-out/transcripts/` so re-runs skip already-transcribed files.
|
||||
|
||||
For better accuracy on technical content, use a larger model:
|
||||
|
||||
```bash
|
||||
/graphify ./my-corpus --whisper-model medium
|
||||
```
|
||||
|
||||
Audio never leaves your machine. All transcription runs locally.
|
||||
|
||||
## What you get
|
||||
|
||||
**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.
|
||||
|
||||
**Suggested questions** - 4-5 questions the graph is uniquely positioned to answer
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
**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. Video transcription via faster-whisper + yt-dlp (optional, `pip install graphifyy[video]`). No Neo4j required, no server, runs entirely locally.
|
||||
---
|
||||
|
||||
## Built on graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) is the enterprise layer on top of graphify. Where graphify turns a folder of files into a knowledge graph, Penpax applies the same graph to your entire working life — continuously.
|
||||
[**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.
|
||||
|
||||
| | graphify | Penpax |
|
||||
|---|---|---|
|
||||
| Input | A folder of files | Browser history, meetings, emails, files, code — everything |
|
||||
| Runs | On demand | Continuously in the background |
|
||||
| Scope | A project | Your entire working life |
|
||||
| Query | CLI / MCP / AI skill | Natural language, always on |
|
||||
| Privacy | Local by default | Fully on-device, no cloud |
|
||||
Built for people whose work lives across hundreds of conversations and documents they can never fully reconstruct. No cloud, fully on-device.
|
||||
|
||||
Built for lawyers, consultants, executives, doctors, researchers — anyone whose work lives across hundreds of conversations and documents they can never fully reconstruct.
|
||||
**Free trial launching soon.** [Join the waitlist →](https://graphifylabs.ai)
|
||||
|
||||
**Free trial launching soon.** [Join the waitlist →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## What we are building next
|
||||
|
||||
graphify is the graph layer. Penpax is the always-on layer on top of it — an on-device digital twin that connects your meetings, browser history, files, emails, and code into one continuously updating knowledge graph. No cloud, no training on your data. [Join the waitlist.](https://safishamsi.github.io/penpax.ai)
|
||||
---
|
||||
|
||||
<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"]`.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,133 @@
|
||||
# Design: Incremental Updates + Entity Deduplication
|
||||
|
||||
**Date:** 2026-05-04
|
||||
**Issues:** #698 (incremental updates), entity deduplication (no issue, proactive)
|
||||
**Branch:** v7
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
1. `graphify extract` rebuilds the full graph from scratch every run — re-sends all files to the LLM regardless of what changed. For a 1000-file Markdown corpus updated daily this is expensive.
|
||||
|
||||
2. LLM extraction is chunk-by-chunk — the same real-world concept can get different labels across chunks (`AuthManager`, `AuthenticationManager`, `auth_mgr`). No semantic dedup exists beyond exact string normalization.
|
||||
|
||||
---
|
||||
|
||||
## Pipeline (every `graphify extract` run)
|
||||
|
||||
```
|
||||
detect (full or incremental, auto-detected)
|
||||
↓
|
||||
AST extract (code files, AST cache-aware)
|
||||
↓
|
||||
Semantic LLM extract (doc/paper/image files, semantic cache-aware)
|
||||
↓
|
||||
build_merge (merge into existing graph, prune deleted nodes)
|
||||
↓
|
||||
deduplicate_entities (normalize → entropy gate → MinHash/LSH → Jaro-Winkler → community boost → optional LLM)
|
||||
↓
|
||||
cluster (full graph, always re-run)
|
||||
↓
|
||||
score_all + god_nodes + surprising_connections
|
||||
↓
|
||||
write graph.json + .graphify_analysis.json + manifest.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Feature 1: Incremental Updates
|
||||
|
||||
### Auto-detection
|
||||
If `graphify-out/manifest.json` + `graphify-out/graph.json` both exist → incremental mode. No flag needed. First run is always full.
|
||||
|
||||
### Incremental mode changes
|
||||
- `detect_incremental(target)` instead of `detect(target)` — returns `new_files`, `unchanged_files`, `deleted_files`
|
||||
- Only `new_files` go through AST + LLM extraction
|
||||
- `build_merge(new_chunks, prune_sources=deleted_files)` instead of `build_from_json` — merges into existing graph, prunes nodes from deleted files
|
||||
- `manifest.json` written only on successful completion (crash mid-run does not corrupt next run's diff)
|
||||
|
||||
### Semantic cache (both full and incremental mode)
|
||||
- Before LLM call: `check_semantic_cache(files)` splits into `(cached_results, uncached_files)`
|
||||
- Only `uncached_files` sent to `extract_corpus_parallel`
|
||||
- After LLM call: `save_semantic_cache(fresh_results)` — keyed by content hash
|
||||
- On file rename: `source_file` updated to new path in cached result (same pattern as existing AST cache)
|
||||
|
||||
### Output summary
|
||||
```
|
||||
[graphify extract] incremental: 20 changed, 980 cached, 2 deleted
|
||||
[graphify extract] graph: 4,821 nodes, 12,304 edges, 43 communities
|
||||
[graphify extract] tokens: 18,432 in / 6,201 out, est. cost: $0.08
|
||||
```
|
||||
|
||||
### Files changed
|
||||
- `graphify/__main__.py` — `elif cmd == "extract":` block only (~5 targeted changes)
|
||||
|
||||
---
|
||||
|
||||
## Feature 2: Entity Deduplication
|
||||
|
||||
### New module: `graphify/dedup.py`
|
||||
Single responsibility. Called from `build.py` after graph construction. Returns deduplicated `(nodes, edges)`.
|
||||
|
||||
### Pipeline
|
||||
|
||||
**Step 1 — Exact normalization**
|
||||
Wire up the dormant `deduplicate_by_label` in `build.py`. Catches case/punctuation variants across files. Free win, already written.
|
||||
|
||||
**Step 2 — Entropy gate**
|
||||
Skip fuzzy matching on labels with < 2.5 bits/char entropy. Short ambiguous names (`"AI"`, `"DB"`, `"x"`) are too risky to auto-merge. Only high-entropy labels proceed to steps 3-4.
|
||||
|
||||
**Step 3 — MinHash + LSH blocking** (`datasketch`)
|
||||
3-gram shingles, 128 permutations, threshold 0.7. Generates candidate pairs in O(n) instead of O(n²). Sub-second at 10k nodes.
|
||||
|
||||
**Step 4 — Jaro-Winkler verification** (`rapidfuzz`)
|
||||
Each candidate pair verified at ≥ 0.92. Catches typos, plurals, spacing variants. Pairs below threshold discarded.
|
||||
|
||||
**Step 5 — Same-community boost**
|
||||
Pairs where both nodes share a Leiden community ID get +0.05 score bonus. Graphify-specific advantage — community structure is a strong signal that GraphRAG/LightRAG don't exploit.
|
||||
|
||||
**Step 6 — Union-find merge**
|
||||
Confirmed pairs fed into union-find → connected components → each component merged into one node. Edges rewired to survivor. Self-loops dropped. Prefer shorter non-chunk-suffixed IDs as survivor.
|
||||
|
||||
**Step 7 — Optional LLM tiebreaker** (`--dedup-llm` flag)
|
||||
Ambiguous pairs (score 0.75–0.85) batched in groups of 30, one LLM call per batch. ~$0.01 total for 10k nodes. Off by default.
|
||||
|
||||
### Integration point
|
||||
Dedup runs after `build_merge` / `build_from_json`, before `cluster`. Order matters: cleaner graph → better community detection.
|
||||
|
||||
```python
|
||||
# in build.py
|
||||
G = build_merge(...) # or build_from_json
|
||||
G = deduplicate_entities(G) # new step
|
||||
communities = cluster(G) # unchanged
|
||||
```
|
||||
|
||||
### New dependencies
|
||||
- `datasketch` — always required (added to `[project.dependencies]`)
|
||||
- `rapidfuzz` — always required (added to `[project.dependencies]`)
|
||||
- No `sentence-transformers` / PyTorch dependency
|
||||
|
||||
### Files changed
|
||||
- `graphify/dedup.py` — new module, full pipeline
|
||||
- `graphify/build.py` — call `deduplicate_entities` after graph construction; wire dormant `deduplicate_by_label`
|
||||
- `graphify/__main__.py` — add `--dedup-llm` flag parsing in extract block
|
||||
- `pyproject.toml` — add `datasketch`, `rapidfuzz` to base dependencies
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
- Unit tests for each dedup step in isolation (`tests/test_dedup.py`)
|
||||
- Integration test: two chunks with overlapping entity labels → single merged node in output graph
|
||||
- Incremental test: run extract twice, assert second run makes zero LLM calls for unchanged files
|
||||
- Rename test: rename a file, assert cache hit and `source_file` updated correctly
|
||||
- Delete test: delete a file, assert its nodes are pruned from graph
|
||||
|
||||
---
|
||||
|
||||
## Non-goals
|
||||
|
||||
- `--dedup embed` (MiniLM cosine) — explicitly excluded, no PyTorch dependency
|
||||
- Incremental support for `graphify update` (AST-only) — already handled by existing AST cache
|
||||
- Dedup across different graph.json files (merge two graphs) — separate feature
|
||||
+1036
-53
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,34 @@
|
||||
"""Graph analysis: god nodes (most connected), surprising connections (cross-community), suggested questions."""
|
||||
from __future__ import annotations
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
|
||||
# Language families — extensions sharing a runtime can legitimately call each other
|
||||
_LANG_FAMILY: dict[str, str] = {
|
||||
**{e: "python" for e in (".py", ".pyw")},
|
||||
**{e: "js" for e in (".js", ".jsx", ".mjs", ".ejs", ".ts", ".tsx", ".vue", ".svelte")},
|
||||
**{e: "go" for e in (".go",)},
|
||||
**{e: "rust" for e in (".rs",)},
|
||||
**{e: "jvm" for e in (".java", ".kt", ".kts", ".scala")},
|
||||
**{e: "c" for e in (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp")},
|
||||
**{e: "ruby" for e in (".rb",)},
|
||||
**{e: "swift" for e in (".swift",)},
|
||||
**{e: "dotnet" for e in (".cs",)},
|
||||
**{e: "php" for e in (".php",)},
|
||||
**{e: "r" for e in (".r",)},
|
||||
}
|
||||
|
||||
|
||||
def _cross_language(src_a: str, src_b: str) -> bool:
|
||||
"""Return True if two source files belong to different language families."""
|
||||
ext_a = Path(src_a).suffix.lower()
|
||||
ext_b = Path(src_b).suffix.lower()
|
||||
fam_a = _LANG_FAMILY.get(ext_a)
|
||||
fam_b = _LANG_FAMILY.get(ext_b)
|
||||
if fam_a is None or fam_b is None:
|
||||
return False
|
||||
return fam_a != fam_b
|
||||
|
||||
|
||||
def _node_community_map(communities: dict[int, list[str]]) -> dict[str, int]:
|
||||
"""Invert communities dict: node_id -> community_id."""
|
||||
@@ -143,7 +170,13 @@ def _surprise_score(
|
||||
|
||||
# 1. Confidence weight - uncertain connections are more noteworthy
|
||||
conf = data.get("confidence", "EXTRACTED")
|
||||
relation = data.get("relation", "")
|
||||
conf_bonus = {"AMBIGUOUS": 3, "INFERRED": 2, "EXTRACTED": 1}.get(conf, 1)
|
||||
|
||||
# Cross-language INFERRED calls are likely resolver pollution, not real surprises
|
||||
if conf == "INFERRED" and relation == "calls" and _cross_language(u_source, v_source):
|
||||
conf_bonus = 0 # downgrade: don't promote likely false positives
|
||||
|
||||
score += conf_bonus
|
||||
if conf in ("AMBIGUOUS", "INFERRED"):
|
||||
reasons.append(f"{conf.lower()} connection - not explicitly stated in source")
|
||||
|
||||
+184
-1
@@ -21,8 +21,10 @@
|
||||
# before any graph construction happens.
|
||||
#
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
from .validate import validate_extraction
|
||||
|
||||
@@ -37,6 +39,12 @@ def _normalize_id(s: str) -> str:
|
||||
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.
|
||||
|
||||
@@ -50,6 +58,18 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
|
||||
# Canonicalize legacy node/edge schema before validation.
|
||||
for node in extraction.get("nodes", []):
|
||||
if isinstance(node, dict) and "source" in node and "source_file" not in node:
|
||||
# Count edges that reference this node so the warning is actionable (#479)
|
||||
node_id = node.get("id", "?")
|
||||
affected_edges = sum(
|
||||
1 for e in extraction.get("edges", [])
|
||||
if e.get("source") == node_id or e.get("target") == node_id
|
||||
)
|
||||
print(
|
||||
f"[graphify] WARNING: node '{node_id}' uses field 'source' instead of "
|
||||
f"'source_file' — {affected_edges} edge(s) may be misrouted. "
|
||||
f"Rename the field to 'source_file' to silence this warning.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
node["source_file"] = node.pop("source")
|
||||
|
||||
errors = validate_extraction(extraction)
|
||||
@@ -59,6 +79,8 @@ 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
|
||||
@@ -81,6 +103,8 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
|
||||
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
|
||||
@@ -92,17 +116,27 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
|
||||
return G
|
||||
|
||||
|
||||
def build(extractions: list[dict], *, directed: bool = False) -> nx.Graph:
|
||||
def build(
|
||||
extractions: list[dict],
|
||||
*,
|
||||
directed: bool = False,
|
||||
dedup: bool = True,
|
||||
dedup_llm_backend: str | None = None,
|
||||
) -> nx.Graph:
|
||||
"""Merge multiple extraction results into one graph.
|
||||
|
||||
directed=True produces a DiGraph that preserves edge direction (source→target).
|
||||
directed=False (default) produces an undirected Graph for backward compatibility.
|
||||
dedup=True (default) runs entity deduplication before building the graph.
|
||||
dedup_llm_backend: if set (e.g. "gemini", "claude", or "kimi"), uses LLM to resolve
|
||||
ambiguous pairs in the 75–92 Jaro-Winkler score zone.
|
||||
|
||||
Extractions are merged in order. For nodes with the same ID, the last
|
||||
extraction's attributes win (NetworkX add_node overwrites). Pass AST
|
||||
results before semantic results so semantic labels take precedence, or
|
||||
reverse the order if you prefer AST source_location precision to win.
|
||||
"""
|
||||
from graphify.dedup import deduplicate_entities
|
||||
combined: dict = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
for ext in extractions:
|
||||
combined["nodes"].extend(ext.get("nodes", []))
|
||||
@@ -110,4 +144,153 @@ def build(extractions: list[dict], *, directed: bool = False) -> nx.Graph:
|
||||
combined["hyperedges"].extend(ext.get("hyperedges", []))
|
||||
combined["input_tokens"] += ext.get("input_tokens", 0)
|
||||
combined["output_tokens"] += ext.get("output_tokens", 0)
|
||||
if dedup and combined["nodes"]:
|
||||
combined["nodes"], combined["edges"] = deduplicate_entities(
|
||||
combined["nodes"], combined["edges"], communities={},
|
||||
dedup_llm_backend=dedup_llm_backend,
|
||||
)
|
||||
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,
|
||||
dedup: bool = True,
|
||||
dedup_llm_backend: str | None = None,
|
||||
) -> 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, dedup=dedup, dedup_llm_backend=dedup_llm_backend)
|
||||
|
||||
# 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)
|
||||
n_files = len(prune_sources)
|
||||
n_nodes = len(to_remove)
|
||||
if n_nodes:
|
||||
print(
|
||||
f"[graphify] Pruned {n_nodes} node(s) from {n_files} deleted source file(s).",
|
||||
file=sys.stderr,
|
||||
)
|
||||
else:
|
||||
print(
|
||||
f"[graphify] {n_files} source file(s) deleted since last run — "
|
||||
f"no matching nodes in graph, already clean.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
# Safety check: refuse to shrink the graph silently (#479)
|
||||
# Skip when dedup or prune_sources is active — shrinkage is intentional there.
|
||||
if graph_path.exists() and not dedup and not prune_sources:
|
||||
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
|
||||
|
||||
|
||||
def prefix_graph_for_global(G: nx.Graph, repo_tag: str) -> nx.Graph:
|
||||
"""Return a copy of G with all node IDs prefixed with repo_tag::.
|
||||
|
||||
Labels are preserved unchanged (for display). A 'local_id' attribute
|
||||
is added to each node so the original ID can be recovered. Edges are
|
||||
rewritten to match the new prefixed IDs. The 'repo' attribute is set
|
||||
on every node.
|
||||
"""
|
||||
relabel = {n: f"{repo_tag}::{n}" for n in G.nodes}
|
||||
H = nx.relabel_nodes(G, relabel, copy=True)
|
||||
for node, data in H.nodes(data=True):
|
||||
data["repo"] = repo_tag
|
||||
data.setdefault("local_id", node.split("::", 1)[1])
|
||||
return H
|
||||
|
||||
|
||||
def prune_repo_from_graph(G: nx.Graph, repo_tag: str) -> int:
|
||||
"""Remove all nodes tagged with repo_tag from G in-place. Returns count removed."""
|
||||
to_remove = [n for n, d in G.nodes(data=True) if d.get("repo") == repo_tag]
|
||||
G.remove_nodes_from(to_remove)
|
||||
return len(to_remove)
|
||||
+95
-32
@@ -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,6 +23,17 @@ def _body_content(content: bytes) -> bytes:
|
||||
return content
|
||||
|
||||
|
||||
def _normalize_path(path: Path) -> Path:
|
||||
"""Normalize path for consistent cache keys across Windows path spellings."""
|
||||
import sys
|
||||
if sys.platform != "win32":
|
||||
return path
|
||||
s = str(path)
|
||||
if s.startswith("\\\\?\\"):
|
||||
s = s[4:] # strip extended-length prefix \\?\
|
||||
return Path(os.path.normcase(s))
|
||||
|
||||
|
||||
def file_hash(path: Path, root: Path = Path(".")) -> str:
|
||||
"""SHA256 of file contents + path relative to root.
|
||||
|
||||
@@ -27,7 +44,8 @@ def file_hash(path: Path, root: Path = Path(".")) -> str:
|
||||
For Markdown files (.md), only the body below the YAML frontmatter is hashed,
|
||||
so metadata-only changes (e.g. reviewed, status, tags) do not invalidate the cache.
|
||||
"""
|
||||
p = Path(path)
|
||||
p = _normalize_path(Path(path))
|
||||
root = _normalize_path(Path(root))
|
||||
if not p.is_file():
|
||||
raise IsADirectoryError(f"file_hash requires a file, got: {p}")
|
||||
raw = p.read_bytes()
|
||||
@@ -43,37 +61,54 @@ def file_hash(path: Path, root: Path = Path(".")) -> str:
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def cache_dir(root: Path = Path(".")) -> Path:
|
||||
"""Returns graphify-out/cache/ - creates it if needed."""
|
||||
d = Path(root).resolve() / "graphify-out" / "cache"
|
||||
def cache_dir(root: Path = Path("."), kind: str = "ast") -> Path:
|
||||
"""Returns graphify-out/cache/{kind}/ - creates it if needed.
|
||||
|
||||
kind is "ast" or "semantic". Separate subdirectories prevent semantic cache
|
||||
entries from overwriting AST cache entries for the same source_file (#582).
|
||||
"""
|
||||
_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, root)
|
||||
except OSError:
|
||||
return None
|
||||
entry = cache_dir(root) / f"{h}.json"
|
||||
if not entry.exists():
|
||||
return None
|
||||
try:
|
||||
return json.loads(entry.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
entry = cache_dir(root, kind) / f"{h}.json"
|
||||
if entry.exists():
|
||||
try:
|
||||
return json.loads(entry.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
# Migration fallback: check legacy flat cache/ dir for AST entries
|
||||
if kind == "ast":
|
||||
legacy = Path(root).resolve() / _GRAPHIFY_OUT / "cache" / f"{h}.json"
|
||||
if legacy.exists():
|
||||
try:
|
||||
return json.loads(legacy.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
|
||||
def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "ast") -> None:
|
||||
"""Save extraction result for this file.
|
||||
|
||||
Stores as graphify-out/cache/{hash}.json where hash = SHA256 of current file contents.
|
||||
Stores as graphify-out/cache/{kind}/{hash}.json where hash = SHA256 of current file contents.
|
||||
result should be a dict with 'nodes' and 'edges' lists.
|
||||
|
||||
No-ops if `path` is not a regular file. Subagent-produced semantic fragments
|
||||
@@ -84,34 +119,60 @@ def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
|
||||
if not p.is_file():
|
||||
return
|
||||
h = file_hash(p, root)
|
||||
entry = cache_dir(root) / f"{h}.json"
|
||||
tmp = entry.with_suffix(".tmp")
|
||||
target_dir = cache_dir(root, kind)
|
||||
entry = target_dir / f"{h}.json"
|
||||
fd, tmp_path = tempfile.mkstemp(dir=target_dir, prefix=f"{h}.", suffix=".tmp")
|
||||
try:
|
||||
tmp.write_text(json.dumps(result), encoding="utf-8")
|
||||
os.write(fd, json.dumps(result).encode())
|
||||
os.close(fd)
|
||||
try:
|
||||
os.replace(tmp, entry)
|
||||
os.replace(tmp_path, entry)
|
||||
except PermissionError:
|
||||
# Windows: os.replace can fail with WinError 5 if the target is
|
||||
# briefly locked. Fall back to copy-then-delete.
|
||||
import shutil
|
||||
shutil.copy2(tmp, entry)
|
||||
tmp.unlink(missing_ok=True)
|
||||
shutil.copy2(tmp_path, entry)
|
||||
os.unlink(tmp_path)
|
||||
except Exception:
|
||||
tmp.unlink(missing_ok=True)
|
||||
try:
|
||||
os.close(fd)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
os.unlink(tmp_path)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def cached_files(root: Path = Path(".")) -> set[str]:
|
||||
"""Return set of file paths that have a valid cache entry (hash still matches)."""
|
||||
d = cache_dir(root)
|
||||
return {p.stem for p in d.glob("*.json")}
|
||||
"""Return set of file hashes that have a valid cache entry (any kind)."""
|
||||
base = Path(root).resolve() / _GRAPHIFY_OUT / "cache"
|
||||
hashes: set[str] = set()
|
||||
# Legacy flat entries
|
||||
if base.is_dir():
|
||||
hashes.update(p.stem for p in base.glob("*.json"))
|
||||
# Namespaced entries
|
||||
for kind in ("ast", "semantic"):
|
||||
d = base / kind
|
||||
if d.is_dir():
|
||||
hashes.update(p.stem for p in d.glob("*.json"))
|
||||
return hashes
|
||||
|
||||
|
||||
def clear_cache(root: Path = Path(".")) -> None:
|
||||
"""Delete all graphify-out/cache/*.json files."""
|
||||
d = cache_dir(root)
|
||||
for f in d.glob("*.json"):
|
||||
f.unlink()
|
||||
"""Delete all cache entries (ast/, semantic/, and legacy flat entries)."""
|
||||
base = Path(root).resolve() / _GRAPHIFY_OUT / "cache"
|
||||
# Legacy flat entries
|
||||
if base.is_dir():
|
||||
for f in base.glob("*.json"):
|
||||
f.unlink()
|
||||
# Namespaced entries
|
||||
for kind in ("ast", "semantic"):
|
||||
d = base / kind
|
||||
if d.is_dir():
|
||||
for f in d.glob("*.json"):
|
||||
f.unlink()
|
||||
|
||||
|
||||
def check_semantic_cache(
|
||||
@@ -129,7 +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", []))
|
||||
@@ -148,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
|
||||
@@ -173,6 +236,6 @@ def save_semantic_cache(
|
||||
if not p.is_absolute():
|
||||
p = Path(root) / p
|
||||
if p.is_file():
|
||||
save_cached(p, result, root)
|
||||
save_cached(p, result, root, kind="semantic")
|
||||
saved += 1
|
||||
return saved
|
||||
@@ -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)}
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
"""Entity deduplication pipeline for graphify knowledge graphs.
|
||||
|
||||
Pipeline: exact normalization → entropy gate → MinHash/LSH blocking →
|
||||
Jaro-Winkler verification → same-community boost → union-find merge.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import math
|
||||
import re
|
||||
from collections import defaultdict
|
||||
|
||||
from datasketch import MinHash, MinHashLSH
|
||||
from rapidfuzz.distance import JaroWinkler
|
||||
|
||||
|
||||
# ── helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
def _norm(label: str) -> str:
|
||||
"""Lowercase + collapse non-alphanumeric runs to space."""
|
||||
return re.sub(r"[^a-z0-9]+", " ", label.lower()).strip()
|
||||
|
||||
|
||||
def _entropy(label: str) -> float:
|
||||
"""Shannon entropy in bits/char of the normalised label."""
|
||||
s = _norm(label)
|
||||
if not s:
|
||||
return 0.0
|
||||
freq: dict[str, int] = defaultdict(int)
|
||||
for ch in s:
|
||||
freq[ch] += 1
|
||||
n = len(s)
|
||||
return -sum((c / n) * math.log2(c / n) for c in freq.values())
|
||||
|
||||
|
||||
def _shingles(text: str, k: int = 3) -> set[str]:
|
||||
"""Return k-gram character shingles of text."""
|
||||
if len(text) < k:
|
||||
return {text}
|
||||
return {text[i : i + k] for i in range(len(text) - k + 1)}
|
||||
|
||||
|
||||
def _make_minhash(text: str, num_perm: int = 128) -> MinHash:
|
||||
# Strip spaces so "graph extractor" and "graphextractor" share shingles
|
||||
m = MinHash(num_perm=num_perm)
|
||||
for shingle in _shingles(text.replace(" ", "")):
|
||||
m.update(shingle.encode("utf-8"))
|
||||
return m
|
||||
|
||||
|
||||
# ── union-find ────────────────────────────────────────────────────────────────
|
||||
|
||||
class _UF:
|
||||
def __init__(self) -> None:
|
||||
self._parent: dict[str, str] = {}
|
||||
|
||||
def find(self, x: str) -> str:
|
||||
self._parent.setdefault(x, x)
|
||||
while self._parent[x] != x:
|
||||
self._parent[x] = self._parent[self._parent[x]]
|
||||
x = self._parent[x]
|
||||
return x
|
||||
|
||||
def union(self, x: str, y: str) -> None:
|
||||
self._parent.setdefault(x, x)
|
||||
self._parent.setdefault(y, y)
|
||||
rx, ry = self.find(x), self.find(y)
|
||||
if rx != ry:
|
||||
self._parent[ry] = rx
|
||||
|
||||
def components(self) -> dict[str, list[str]]:
|
||||
groups: dict[str, list[str]] = defaultdict(list)
|
||||
for x in self._parent:
|
||||
groups[self.find(x)].append(x)
|
||||
return dict(groups)
|
||||
|
||||
|
||||
# ── constants ─────────────────────────────────────────────────────────────────
|
||||
|
||||
_ENTROPY_THRESHOLD = 2.5
|
||||
_LSH_THRESHOLD = 0.7
|
||||
_MERGE_THRESHOLD = 92.0 # rapidfuzz normalized_similarity * 100
|
||||
_COMMUNITY_BOOST = 5.0 # score bonus when both nodes share community
|
||||
_NUM_PERM = 128
|
||||
_CHUNK_SUFFIX = re.compile(r"_c\d+$")
|
||||
|
||||
|
||||
# ── main entry point ──────────────────────────────────────────────────────────
|
||||
|
||||
def deduplicate_entities(
|
||||
nodes: list[dict],
|
||||
edges: list[dict],
|
||||
*,
|
||||
communities: dict[str, int],
|
||||
dedup_llm_backend: str | None = None,
|
||||
) -> tuple[list[dict], list[dict]]:
|
||||
"""Deduplicate near-identical entities in a knowledge graph.
|
||||
|
||||
Args:
|
||||
nodes: list of node dicts with at minimum {"id": str, "label": str}
|
||||
edges: list of edge dicts with {"source": str, "target": str, ...}
|
||||
communities: mapping of node_id -> community_id (from cluster())
|
||||
dedup_llm_backend: if set, use LLM to resolve ambiguous pairs
|
||||
|
||||
Returns:
|
||||
(deduped_nodes, deduped_edges) with edges rewired to survivors
|
||||
"""
|
||||
# Guard: cross-project dedup is not supported — nodes from different repos
|
||||
# share label names by coincidence and must never be merged by string similarity.
|
||||
# If you need to dedup a global graph, run deduplicate_entities per-repo first.
|
||||
repos_seen = {n.get("repo") for n in nodes if n.get("repo")}
|
||||
if len(repos_seen) > 1:
|
||||
raise ValueError(
|
||||
f"deduplicate_entities: nodes span multiple repos {sorted(repos_seen)!r}. "
|
||||
f"Cross-project dedup is disabled — run dedup per-repo before merging."
|
||||
)
|
||||
|
||||
if len(nodes) <= 1:
|
||||
return nodes, edges
|
||||
|
||||
# Pre-deduplicate: keep first occurrence of each id
|
||||
seen_ids: dict[str, dict] = {}
|
||||
for node in nodes:
|
||||
nid = node.get("id", "")
|
||||
if nid and nid not in seen_ids:
|
||||
seen_ids[nid] = node
|
||||
unique_nodes = list(seen_ids.values())
|
||||
|
||||
if len(unique_nodes) <= 1:
|
||||
return unique_nodes, edges
|
||||
|
||||
# ── pass 1: exact normalization ───────────────────────────────────────────
|
||||
norm_to_nodes: dict[str, list[dict]] = defaultdict(list)
|
||||
for node in unique_nodes:
|
||||
key = _norm(node.get("label", node.get("id", "")))
|
||||
if key:
|
||||
norm_to_nodes[key].append(node)
|
||||
|
||||
uf = _UF()
|
||||
for key, group in norm_to_nodes.items():
|
||||
if len(group) > 1:
|
||||
winner = _pick_winner(group)
|
||||
for node in group:
|
||||
uf.union(winner["id"], node["id"])
|
||||
|
||||
exact_merges = sum(len(g) - 1 for g in norm_to_nodes.values() if len(g) > 1)
|
||||
|
||||
# ── pass 2: MinHash/LSH + Jaro-Winkler (high-entropy nodes only) ─────────
|
||||
candidates: list[dict] = []
|
||||
seen_norms: set[str] = set()
|
||||
for node in unique_nodes:
|
||||
key = _norm(node.get("label", node.get("id", "")))
|
||||
if key and key not in seen_norms:
|
||||
seen_norms.add(key)
|
||||
if _entropy(node.get("label", "")) >= _ENTROPY_THRESHOLD:
|
||||
candidates.append(node)
|
||||
|
||||
fuzzy_merges = 0
|
||||
if len(candidates) >= 2:
|
||||
lsh = MinHashLSH(threshold=_LSH_THRESHOLD, num_perm=_NUM_PERM)
|
||||
minhashes: dict[str, MinHash] = {}
|
||||
|
||||
for node in candidates:
|
||||
norm_label = _norm(node.get("label", node.get("id", "")))
|
||||
m = _make_minhash(norm_label)
|
||||
minhashes[node["id"]] = m
|
||||
try:
|
||||
lsh.insert(node["id"], m)
|
||||
except ValueError:
|
||||
pass # duplicate key in LSH — already inserted
|
||||
|
||||
for node in candidates:
|
||||
node_id = node["id"]
|
||||
norm_label = _norm(node.get("label", node.get("id", "")))
|
||||
neighbors = lsh.query(minhashes[node_id])
|
||||
|
||||
for neighbor_id in neighbors:
|
||||
if neighbor_id == node_id:
|
||||
continue
|
||||
if uf.find(node_id) == uf.find(neighbor_id):
|
||||
continue
|
||||
|
||||
neighbor = next((n for n in candidates if n["id"] == neighbor_id), None)
|
||||
if neighbor is None:
|
||||
continue
|
||||
|
||||
neighbor_norm = _norm(neighbor.get("label", neighbor.get("id", "")))
|
||||
score = JaroWinkler.normalized_similarity(norm_label, neighbor_norm) * 100
|
||||
|
||||
c1 = communities.get(node_id)
|
||||
c2 = communities.get(neighbor_id)
|
||||
if c1 is not None and c2 is not None and c1 == c2:
|
||||
score += _COMMUNITY_BOOST
|
||||
|
||||
if score >= _MERGE_THRESHOLD:
|
||||
all_group = norm_to_nodes.get(norm_label, [node]) + \
|
||||
norm_to_nodes.get(neighbor_norm, [neighbor])
|
||||
winner = _pick_winner(all_group)
|
||||
uf.union(winner["id"], node_id)
|
||||
uf.union(winner["id"], neighbor_id)
|
||||
fuzzy_merges += 1
|
||||
|
||||
# ── pass 3: LLM tiebreaker for ambiguous pairs (opt-in) ──────────────────
|
||||
if dedup_llm_backend is not None:
|
||||
_llm_tiebreak(candidates, uf, communities, backend=dedup_llm_backend)
|
||||
|
||||
# ── build remap table from union-find components ──────────────────────────
|
||||
components = uf.components()
|
||||
remap: dict[str, str] = {}
|
||||
|
||||
for root, members in components.items():
|
||||
if len(members) == 1:
|
||||
continue
|
||||
group_nodes = [n for n in unique_nodes if n["id"] in members]
|
||||
winner = _pick_winner(group_nodes) if group_nodes else {"id": root}
|
||||
winner_id = winner["id"]
|
||||
for member in members:
|
||||
if member != winner_id:
|
||||
remap[member] = winner_id
|
||||
|
||||
# ── apply remap ───────────────────────────────────────────────────────────
|
||||
if not remap:
|
||||
return unique_nodes, edges
|
||||
|
||||
total = len(remap)
|
||||
msg = f"[graphify] Deduplicated {total} node(s)"
|
||||
if exact_merges:
|
||||
msg += f" ({exact_merges} exact"
|
||||
if fuzzy_merges:
|
||||
msg += f", {fuzzy_merges} fuzzy"
|
||||
msg += ")"
|
||||
print(msg + ".", flush=True)
|
||||
|
||||
deduped_nodes = [n for n in unique_nodes if n["id"] not in remap]
|
||||
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 _pick_winner(nodes: list[dict]) -> dict:
|
||||
"""Pick the canonical survivor: prefer no chunk suffix, then shorter ID."""
|
||||
if not nodes:
|
||||
raise ValueError("Cannot pick winner from empty list")
|
||||
|
||||
def _score(n: dict) -> tuple[int, int]:
|
||||
has_suffix = bool(_CHUNK_SUFFIX.search(n["id"]))
|
||||
return (1 if has_suffix else 0, len(n["id"]))
|
||||
|
||||
return min(nodes, key=_score)
|
||||
|
||||
|
||||
def _llm_tiebreak(
|
||||
candidates: list[dict],
|
||||
uf: _UF,
|
||||
communities: dict[str, int],
|
||||
*,
|
||||
backend: str,
|
||||
batch_size: int = 30,
|
||||
low: float = 75.0,
|
||||
high: float = 92.0,
|
||||
) -> None:
|
||||
"""Batch-resolve ambiguous pairs (score in [low, high)) via LLM."""
|
||||
try:
|
||||
from graphify.llm import BACKENDS, _format_backend_env_keys, _get_backend_api_key
|
||||
if backend not in BACKENDS:
|
||||
print(f"[graphify] --dedup-llm: unknown backend {backend!r}, skipping LLM tiebreaker.", flush=True)
|
||||
return
|
||||
if not _get_backend_api_key(backend):
|
||||
env_keys = _format_backend_env_keys(backend)
|
||||
print(f"[graphify] --dedup-llm: {env_keys} not set, skipping LLM tiebreaker.", flush=True)
|
||||
return
|
||||
except ImportError:
|
||||
return
|
||||
|
||||
ambiguous: list[tuple[dict, dict, float]] = []
|
||||
for i, node in enumerate(candidates):
|
||||
norm_i = _norm(node.get("label", node.get("id", "")))
|
||||
for j in range(i + 1, len(candidates)):
|
||||
neighbor = candidates[j]
|
||||
if uf.find(node["id"]) == uf.find(neighbor["id"]):
|
||||
continue
|
||||
norm_j = _norm(neighbor.get("label", neighbor.get("id", "")))
|
||||
score = JaroWinkler.normalized_similarity(norm_i, norm_j) * 100
|
||||
c1 = communities.get(node["id"])
|
||||
c2 = communities.get(neighbor["id"])
|
||||
if c1 is not None and c2 is not None and c1 == c2:
|
||||
score += _COMMUNITY_BOOST
|
||||
if low <= score < high:
|
||||
ambiguous.append((node, neighbor, score))
|
||||
|
||||
if not ambiguous:
|
||||
return
|
||||
|
||||
try:
|
||||
from graphify.llm import _call_llm
|
||||
except ImportError:
|
||||
return
|
||||
|
||||
for batch_start in range(0, len(ambiguous), batch_size):
|
||||
batch = ambiguous[batch_start : batch_start + batch_size]
|
||||
pairs_text = "\n".join(
|
||||
f"{i+1}. \"{a['label']}\" vs \"{b['label']}\""
|
||||
for i, (a, b, _) in enumerate(batch)
|
||||
)
|
||||
prompt = (
|
||||
"For each pair below, answer only 'yes' or 'no': are they the same real-world concept?\n\n"
|
||||
f"{pairs_text}\n\n"
|
||||
"Reply with one line per pair: '1. yes', '2. no', etc."
|
||||
)
|
||||
try:
|
||||
response = _call_llm(prompt, backend=backend, max_tokens=200)
|
||||
lines = response.strip().splitlines()
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
parts = line.split(".", 1)
|
||||
if len(parts) != 2:
|
||||
continue
|
||||
try:
|
||||
idx = int(parts[0].strip()) - 1
|
||||
except ValueError:
|
||||
continue
|
||||
if 0 <= idx < len(batch):
|
||||
answer = parts[1].strip().lower()
|
||||
if answer.startswith("yes"):
|
||||
a, b, _ = batch[idx]
|
||||
winner = _pick_winner([a, b])
|
||||
uf.union(winner["id"], a["id"])
|
||||
uf.union(winner["id"], b["id"])
|
||||
except Exception as exc:
|
||||
print(f"[graphify] --dedup-llm batch failed: {exc}", flush=True)
|
||||
+385
-52
@@ -18,8 +18,8 @@ class FileType(str, Enum):
|
||||
|
||||
_MANIFEST_PATH = "graphify-out/manifest.json"
|
||||
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.ejs', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.dart', '.v', '.sv'}
|
||||
DOC_EXTENSIONS = {'.md', '.mdx', '.txt', '.rst', '.html'}
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.ejs', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.dart', '.v', '.sv', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08'}
|
||||
DOC_EXTENSIONS = {'.md', '.mdx', '.txt', '.rst', '.html', '.yaml', '.yml'}
|
||||
PAPER_EXTENSIONS = {'.pdf'}
|
||||
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
|
||||
OFFICE_EXTENSIONS = {'.docx', '.xlsx'}
|
||||
@@ -33,7 +33,7 @@ FILE_COUNT_UPPER = 200 # files - above this, warn about token cost
|
||||
_SENSITIVE_PATTERNS = [
|
||||
re.compile(r'(^|[\\/])\.(env|envrc)(\.|$)', re.IGNORECASE),
|
||||
re.compile(r'\.(pem|key|p12|pfx|cert|crt|der|p8)$', re.IGNORECASE),
|
||||
re.compile(r'(credential|secret|passwd|password|token|private_key)', re.IGNORECASE),
|
||||
re.compile(r'\b(credential|secret|passwd|password|token|private_key)s?\b', re.IGNORECASE),
|
||||
re.compile(r'(id_rsa|id_dsa|id_ecdsa|id_ed25519)(\.pub)?$'),
|
||||
re.compile(r'(\.netrc|\.pgpass|\.htpasswd)$', re.IGNORECASE),
|
||||
re.compile(r'(aws_credentials|gcloud_credentials|service.account)', re.IGNORECASE),
|
||||
@@ -78,11 +78,42 @@ def _looks_like_paper(path: Path) -> bool:
|
||||
_ASSET_DIR_MARKERS = {".imageset", ".xcassets", ".appiconset", ".colorset", ".launchimage"}
|
||||
|
||||
|
||||
_SHEBANG_CODE_INTERPRETERS = {
|
||||
"python", "python3", "python2",
|
||||
"ruby", "perl", "node", "nodejs",
|
||||
"bash", "sh", "dash", "zsh", "fish", "ksh", "tcsh",
|
||||
"lua", "php", "julia", "Rscript",
|
||||
}
|
||||
|
||||
|
||||
def _shebang_file_type(path: Path) -> FileType | None:
|
||||
"""Peek at the first line of an extensionless file for a shebang."""
|
||||
try:
|
||||
with path.open("rb") as f:
|
||||
first = f.read(128)
|
||||
if not first.startswith(b"#!"):
|
||||
return None
|
||||
line = first.split(b"\n")[0].decode(errors="replace")
|
||||
parts = line[2:].strip().split()
|
||||
if not parts:
|
||||
return None
|
||||
interp = parts[0].split("/")[-1] # /usr/bin/env → env
|
||||
if interp == "env" and len(parts) > 1:
|
||||
interp = parts[1].split("/")[-1]
|
||||
if interp in _SHEBANG_CODE_INTERPRETERS:
|
||||
return FileType.CODE
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def classify_file(path: Path) -> FileType | None:
|
||||
# Compound extensions must be checked before simple suffix lookup
|
||||
if path.name.lower().endswith(".blade.php"):
|
||||
return FileType.CODE
|
||||
ext = path.suffix.lower()
|
||||
if not ext:
|
||||
return _shebang_file_type(path)
|
||||
if ext in CODE_EXTENSIONS:
|
||||
return FileType.CODE
|
||||
if ext in PAPER_EXTENSIONS:
|
||||
@@ -169,7 +200,6 @@ def xlsx_to_markdown(path: Path) -> str:
|
||||
ws = wb[sheet_name]
|
||||
rows = []
|
||||
for row in ws.iter_rows(values_only=True):
|
||||
# Skip entirely empty rows
|
||||
if all(cell is None for cell in row):
|
||||
continue
|
||||
rows.append([str(cell) if cell is not None else "" for cell in row])
|
||||
@@ -190,6 +220,91 @@ def xlsx_to_markdown(path: Path) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def xlsx_extract_structure(path: Path) -> dict:
|
||||
"""Extract structural nodes (sheets, named tables, column headers) from an .xlsx file.
|
||||
|
||||
Returns a nodes/edges dict compatible with the graphify extract pipeline.
|
||||
Used in addition to xlsx_to_markdown so Claude sees both structure and content.
|
||||
"""
|
||||
def _nid(*parts: str) -> str:
|
||||
return re.sub(r"[^a-z0-9_]", "_", "_".join(p.lower() for p in parts).strip("_"))
|
||||
|
||||
try:
|
||||
import openpyxl
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": []}
|
||||
|
||||
try:
|
||||
wb = openpyxl.load_workbook(str(path), read_only=False, data_only=True)
|
||||
except Exception:
|
||||
return {"nodes": [], "edges": []}
|
||||
|
||||
stem = _re.sub(r"[^a-z0-9]", "_", path.stem.lower())
|
||||
str_path = str(path)
|
||||
file_nid = _nid(str_path)
|
||||
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "document",
|
||||
"source_file": str_path, "source_location": None}]
|
||||
edges: list[dict] = []
|
||||
seen: set[str] = {file_nid}
|
||||
|
||||
def _add(nid: str, label: str) -> None:
|
||||
if nid not in seen:
|
||||
seen.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "document",
|
||||
"source_file": str_path, "source_location": None})
|
||||
|
||||
def _edge(src: str, tgt: str, relation: str) -> None:
|
||||
edges.append({"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": "EXTRACTED", "source_file": str_path,
|
||||
"source_location": None, "weight": 1.0})
|
||||
|
||||
for sheet_name in wb.sheetnames:
|
||||
ws = wb[sheet_name]
|
||||
sheet_nid = _nid(stem, sheet_name)
|
||||
_add(sheet_nid, f"{sheet_name} (sheet)")
|
||||
_edge(file_nid, sheet_nid, "contains")
|
||||
|
||||
# Named Excel Tables (ListObjects)
|
||||
if hasattr(ws, "tables"):
|
||||
for tbl in ws.tables.values():
|
||||
tbl_nid = _nid(stem, sheet_name, tbl.name)
|
||||
_add(tbl_nid, tbl.name)
|
||||
_edge(sheet_nid, tbl_nid, "contains")
|
||||
# Column headers from table header row
|
||||
ref = tbl.ref # e.g. "A1:D10"
|
||||
if ref:
|
||||
try:
|
||||
from openpyxl.utils import range_boundaries
|
||||
min_col, min_row, max_col, _ = range_boundaries(ref)
|
||||
header_row = list(ws.iter_rows(min_row=min_row, max_row=min_row,
|
||||
min_col=min_col, max_col=max_col,
|
||||
values_only=True))
|
||||
if header_row:
|
||||
for col_name in header_row[0]:
|
||||
if col_name:
|
||||
col_nid = _nid(stem, tbl.name, str(col_name))
|
||||
_add(col_nid, str(col_name))
|
||||
_edge(tbl_nid, col_nid, "contains")
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# Fallback: first non-empty row as column headers
|
||||
for row in ws.iter_rows(max_row=1, values_only=True):
|
||||
for cell in row:
|
||||
if cell:
|
||||
col_nid = _nid(stem, sheet_name, str(cell))
|
||||
_add(col_nid, str(cell))
|
||||
_edge(sheet_nid, col_nid, "contains")
|
||||
break
|
||||
|
||||
try:
|
||||
wb.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
|
||||
|
||||
def convert_office_file(path: Path, out_dir: Path) -> Path | None:
|
||||
"""Convert a .docx or .xlsx to a markdown sidecar in out_dir.
|
||||
|
||||
@@ -241,6 +356,7 @@ _SKIP_DIRS = {
|
||||
"site-packages", "lib64",
|
||||
".pytest_cache", ".mypy_cache", ".ruff_cache",
|
||||
".tox", ".eggs", "*.egg-info",
|
||||
"graphify-out", # never treat own output as source input (#524)
|
||||
}
|
||||
|
||||
# Large generated files that are never useful to extract
|
||||
@@ -262,38 +378,169 @@ def _is_noise_dir(part: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
"""Read .graphifyignore from root **and ancestor directories**.
|
||||
_VCS_MARKERS = (".git", ".hg", ".svn", "_darcs", ".fossil")
|
||||
|
||||
Returns a list of (anchor_dir, pattern) pairs. Each pattern is matched
|
||||
against paths relative to both the scan root and the anchor_dir where
|
||||
the .graphifyignore file was found — so patterns written relative to a
|
||||
parent directory still work when graphify is run on a subfolder.
|
||||
|
||||
Walks upward from *root* towards the filesystem root, stopping at a
|
||||
``.git`` boundary. Lines starting with # are comments; blank lines ignored.
|
||||
def _parse_gitignore_line(raw: str) -> str:
|
||||
"""Parse one raw line from a .graphifyignore file per gitignore spec.
|
||||
|
||||
- Strip newline chars
|
||||
- Strip inline comments (whitespace + # suffix), but only when # is
|
||||
preceded by whitespace — so path#with#hash.py is preserved
|
||||
- Unescape \\# to literal #
|
||||
- Remove trailing spaces unless escaped with backslash
|
||||
- Strip leading whitespace
|
||||
- Return empty string for blank lines and full-line comments
|
||||
"""
|
||||
patterns: list[tuple[Path, str]] = []
|
||||
current = root.resolve()
|
||||
line = raw.rstrip("\n\r")
|
||||
line = line.lstrip()
|
||||
if not line or line.startswith("#"):
|
||||
return ""
|
||||
# Strip inline comments: require whitespace before # (gitignore extension)
|
||||
line = re.sub(r"\s+#+[^\\].*$", "", line)
|
||||
# Unescape \# → literal #
|
||||
line = line.replace("\\#", "#")
|
||||
# Remove unescaped trailing spaces (per gitignore spec)
|
||||
line = re.sub(r"(?<!\\) +$", "", line)
|
||||
return line
|
||||
|
||||
|
||||
def _find_vcs_root(start: Path) -> Path | None:
|
||||
"""Walk upward from start; return the first directory containing a VCS marker."""
|
||||
current = start.resolve()
|
||||
home = Path.home()
|
||||
while True:
|
||||
ignore_file = current / ".graphifyignore"
|
||||
if ignore_file.exists():
|
||||
for line in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#"):
|
||||
patterns.append((current, line))
|
||||
# Stop climbing once we've processed the git repo root
|
||||
if (current / ".git").exists():
|
||||
break
|
||||
if any((current / m).exists() for m in _VCS_MARKERS):
|
||||
return current
|
||||
parent = current.parent
|
||||
if parent == current:
|
||||
break # filesystem root
|
||||
if parent == current or current == home:
|
||||
return None
|
||||
current = parent
|
||||
|
||||
|
||||
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
"""Read .graphifyignore files and return (anchor_dir, pattern) pairs.
|
||||
|
||||
Patterns are returned outer-first so that inner (closer) rules are
|
||||
appended last and win via last-match-wins semantics — matching gitignore
|
||||
behavior exactly.
|
||||
|
||||
Walk ceiling: the nearest VCS root if inside a repo, otherwise the scan
|
||||
root itself (hermetic — no leakage across unrelated sibling projects).
|
||||
"""
|
||||
root = root.resolve()
|
||||
ceiling = _find_vcs_root(root) or root
|
||||
|
||||
# Collect ancestor dirs from ceiling down to root (outer → inner)
|
||||
dirs: list[Path] = []
|
||||
current = root
|
||||
while True:
|
||||
dirs.append(current)
|
||||
if current == ceiling:
|
||||
break
|
||||
current = current.parent
|
||||
dirs.reverse() # ceiling first, scan root last
|
||||
|
||||
patterns: list[tuple[Path, str]] = []
|
||||
for d in dirs:
|
||||
ignore_file = d / ".graphifyignore"
|
||||
if ignore_file.exists():
|
||||
for raw in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||
line = _parse_gitignore_line(raw)
|
||||
if line:
|
||||
patterns.append((d, line))
|
||||
return patterns
|
||||
|
||||
|
||||
def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if path matches any .graphifyignore pattern."""
|
||||
"""Return True if the path should be ignored per .graphifyignore patterns.
|
||||
|
||||
Uses gitignore last-match-wins semantics: all patterns are evaluated in
|
||||
order; the final matching pattern determines the result. Negation patterns
|
||||
(starting with !) un-ignore a previously ignored path.
|
||||
"""
|
||||
if not patterns:
|
||||
return False
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
@@ -311,25 +558,63 @@ def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> boo
|
||||
return False
|
||||
|
||||
for anchor, pattern in patterns:
|
||||
anchored = pattern.startswith("/")
|
||||
p = pattern.strip("/")
|
||||
if not p:
|
||||
continue
|
||||
# Try path relative to the scan root
|
||||
try:
|
||||
rel = str(path.relative_to(root)).replace(os.sep, "/")
|
||||
if _matches(rel, p):
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
# Also try relative to the anchor dir (the .graphifyignore's location),
|
||||
# so patterns written at a parent level still fire when running on a subfolder
|
||||
if anchor != root:
|
||||
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
|
||||
|
||||
|
||||
@@ -346,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"
|
||||
@@ -367,12 +653,17 @@ 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:
|
||||
@@ -389,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)):
|
||||
@@ -444,8 +736,21 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict[str, float]:
|
||||
"""Load the file modification time manifest from a previous run."""
|
||||
def _md5_file(path: Path) -> str:
|
||||
"""MD5 of file contents streamed in 64KB chunks — for change detection only."""
|
||||
import hashlib as _hl
|
||||
h = _hl.md5(usedforsecurity=False)
|
||||
try:
|
||||
with path.open("rb") as f:
|
||||
for chunk in iter(lambda: f.read(65536), b""):
|
||||
h.update(chunk)
|
||||
except OSError:
|
||||
return ""
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict:
|
||||
"""Load the manifest from a previous run. Returns {} on any error."""
|
||||
try:
|
||||
return json.loads(Path(manifest_path).read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
@@ -453,25 +758,39 @@ def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict[str, float]:
|
||||
|
||||
|
||||
def save_manifest(files: dict[str, list[str]], manifest_path: str = _MANIFEST_PATH) -> None:
|
||||
"""Save current file mtimes so the next --update run can diff against them."""
|
||||
manifest: dict[str, float] = {}
|
||||
"""Save current file mtimes + content hashes for change detection on --update."""
|
||||
manifest: dict[str, dict] = {}
|
||||
for file_list in files.values():
|
||||
for f in file_list:
|
||||
try:
|
||||
manifest[f] = Path(f).stat().st_mtime
|
||||
p = Path(f)
|
||||
manifest[f] = {"mtime": p.stat().st_mtime, "hash": _md5_file(p)}
|
||||
except OSError:
|
||||
pass # file deleted between detect() and manifest write - skip it
|
||||
Path(manifest_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(manifest_path).write_text(json.dumps(manifest, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
|
||||
def detect_incremental(
|
||||
root: Path,
|
||||
manifest_path: str = _MANIFEST_PATH,
|
||||
*,
|
||||
follow_symlinks: bool = False,
|
||||
) -> 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.
|
||||
|
||||
The ``follow_symlinks`` flag is forwarded to :func:`detect` so corpora that
|
||||
rely on symlinked sub-trees (e.g. a ``state_of_truth/`` symlink pointing to a
|
||||
directory outside the scan root) are scanned consistently between full and
|
||||
incremental runs.
|
||||
"""
|
||||
full = detect(root)
|
||||
full = detect(root, follow_symlinks=follow_symlinks)
|
||||
manifest = load_manifest(manifest_path)
|
||||
|
||||
if not manifest:
|
||||
@@ -487,12 +806,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)
|
||||
|
||||
+176
-22
@@ -11,6 +11,15 @@ from networkx.readwrite import json_graph
|
||||
from graphify.security import sanitize_label
|
||||
from graphify.analyze import _node_community_map
|
||||
|
||||
def _obsidian_tag(name: str) -> str:
|
||||
"""Sanitize a community name for use as an Obsidian tag.
|
||||
|
||||
Obsidian tags only allow alphanumerics, hyphens, underscores, and slashes.
|
||||
Spaces become underscores; everything else is stripped.
|
||||
"""
|
||||
return re.sub(r"[^a-zA-Z0-9_\-/]", "", name.replace(" ", "_"))
|
||||
|
||||
|
||||
def _strip_diacritics(text: str) -> str:
|
||||
import unicodedata
|
||||
nfkd = unicodedata.normalize("NFKD", text)
|
||||
@@ -25,6 +34,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; }
|
||||
@@ -55,6 +80,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>"""
|
||||
|
||||
|
||||
@@ -240,15 +273,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 {{
|
||||
@@ -257,8 +317,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);
|
||||
}});
|
||||
@@ -279,7 +349,37 @@ 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 _git_head() -> str | None:
|
||||
"""Return the current git HEAD commit hash, or None if not in a git repo."""
|
||||
import subprocess as _sp
|
||||
try:
|
||||
r = _sp.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, timeout=3)
|
||||
return r.stdout.strip() if r.returncode == 0 else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *, force: bool = False, built_at_commit: str | None = None) -> 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")
|
||||
@@ -292,9 +392,22 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) ->
|
||||
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", encoding="utf-8") as f:
|
||||
commit = built_at_commit if built_at_commit is not None else _git_head()
|
||||
if commit:
|
||||
data["built_at_commit"] = commit
|
||||
with open(output_path, "w", encoding="utf-8") as f: # nosec
|
||||
json.dump(data, f, indent=2)
|
||||
return True
|
||||
|
||||
|
||||
def prune_dangling_edges(graph_data: dict) -> tuple[dict, int]:
|
||||
@@ -335,7 +448,7 @@ def to_cypher(G: nx.Graph, output_path: str) -> None:
|
||||
f"MATCH (a {{id: '{u_esc}'}}), (b {{id: '{v_esc}'}}) "
|
||||
f"MERGE (a)-[:{rel} {{confidence: '{conf}'}}]->(b);"
|
||||
)
|
||||
with open(output_path, "w", encoding="utf-8") as f:
|
||||
with open(output_path, "w", encoding="utf-8") as f: # nosec
|
||||
f.write("\n".join(lines))
|
||||
|
||||
|
||||
@@ -345,6 +458,7 @@ def to_html(
|
||||
output_path: str,
|
||||
community_labels: dict[int, str] | None = None,
|
||||
member_counts: dict[int, int] | None = None,
|
||||
node_limit: int | None = None,
|
||||
) -> None:
|
||||
"""Generate an interactive vis.js HTML visualization of the graph.
|
||||
|
||||
@@ -354,11 +468,43 @@ def to_html(
|
||||
|
||||
If member_counts is provided (aggregated community view), node sizes are
|
||||
based on community member counts rather than graph degree.
|
||||
|
||||
If node_limit is set and the graph exceeds it, automatically builds an
|
||||
aggregated community-level meta-graph instead of raising ValueError.
|
||||
"""
|
||||
if G.number_of_nodes() > MAX_NODES_FOR_VIZ:
|
||||
limit = node_limit if node_limit is not None else _viz_node_limit()
|
||||
if G.number_of_nodes() > limit:
|
||||
if node_limit is not None:
|
||||
# Build aggregated community meta-graph
|
||||
from collections import Counter as _Counter
|
||||
import networkx as _nx
|
||||
print(f"Graph has {G.number_of_nodes()} nodes (above {limit} limit). Building aggregated community view...")
|
||||
node_to_community = {nid: cid for cid, members in communities.items() for nid in members}
|
||||
meta = _nx.Graph()
|
||||
for cid, members in communities.items():
|
||||
meta.add_node(str(cid), label=(community_labels or {}).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:
|
||||
print("Single community - aggregated view not useful. Skipping graph.html.")
|
||||
return
|
||||
meta_communities = {cid: [str(cid)] for cid in communities}
|
||||
mc = {cid: len(members) for cid, members in communities.items()}
|
||||
to_html(meta, meta_communities, output_path,
|
||||
community_labels=community_labels, member_counts=mc)
|
||||
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.")
|
||||
return
|
||||
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)
|
||||
@@ -395,14 +541,19 @@ def to_html(
|
||||
"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",
|
||||
@@ -451,6 +602,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>
|
||||
@@ -460,7 +614,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
|
||||
@@ -538,7 +692,7 @@ def to_obsidian(
|
||||
ftype_tag = _FTYPE_TAG.get(ftype, f"graphify/{ftype}" if ftype else "graphify/document")
|
||||
dom_conf = _dominant_confidence(node_id)
|
||||
conf_tag = f"graphify/{dom_conf}"
|
||||
comm_tag = f"community/{community_name.replace(' ', '_')}"
|
||||
comm_tag = f"community/{_obsidian_tag(community_name)}"
|
||||
node_tags = [ftype_tag, conf_tag, comm_tag]
|
||||
|
||||
lines: list[str] = []
|
||||
@@ -575,7 +729,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"
|
||||
@@ -650,7 +804,7 @@ def to_obsidian(
|
||||
lines.append("")
|
||||
|
||||
# Dataview live query (improvement 2)
|
||||
comm_tag_name = community_name.replace(" ", "_")
|
||||
comm_tag_name = _obsidian_tag(community_name)
|
||||
lines.append("## Live Query (requires Dataview plugin)")
|
||||
lines.append("")
|
||||
lines.append("```dataview")
|
||||
@@ -692,7 +846,7 @@ def to_obsidian(
|
||||
|
||||
community_safe = safe_name(community_name)
|
||||
fname = f"_COMMUNITY_{community_safe}.md"
|
||||
(out / fname).write_text("\n".join(lines), encoding="utf-8")
|
||||
(out / fname).write_text("\n".join(lines), encoding="utf-8") # nosec
|
||||
community_notes_written += 1
|
||||
|
||||
# Improvement 4: write .obsidian/graph.json to color nodes by community in graph view
|
||||
@@ -707,7 +861,7 @@ def to_obsidian(
|
||||
for cid, label in sorted((community_labels or {}).items())
|
||||
]
|
||||
}
|
||||
(obsidian_dir / "graph.json").write_text(json.dumps(graph_config, indent=2), encoding="utf-8")
|
||||
(obsidian_dir / "graph.json").write_text(json.dumps(graph_config, indent=2), encoding="utf-8") # nosec
|
||||
|
||||
return G.number_of_nodes() + community_notes_written
|
||||
|
||||
@@ -868,7 +1022,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(
|
||||
|
||||
+1491
-139
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,155 @@
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import hashlib
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph as _jg
|
||||
|
||||
_GLOBAL_DIR = Path.home() / ".graphify"
|
||||
_GLOBAL_GRAPH = _GLOBAL_DIR / "global-graph.json"
|
||||
_GLOBAL_MANIFEST = _GLOBAL_DIR / "global-manifest.json"
|
||||
|
||||
|
||||
def _load_manifest() -> dict:
|
||||
if _GLOBAL_MANIFEST.exists():
|
||||
try:
|
||||
return json.loads(_GLOBAL_MANIFEST.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
pass
|
||||
return {"version": 1, "repos": {}}
|
||||
|
||||
|
||||
def _save_manifest(manifest: dict) -> None:
|
||||
_GLOBAL_DIR.mkdir(parents=True, exist_ok=True)
|
||||
_GLOBAL_MANIFEST.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def _load_global_graph() -> nx.Graph:
|
||||
if _GLOBAL_GRAPH.exists():
|
||||
data = json.loads(_GLOBAL_GRAPH.read_text(encoding="utf-8"))
|
||||
if "links" not in data and "edges" in data:
|
||||
data = dict(data, links=data["edges"])
|
||||
try:
|
||||
return _jg.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
return _jg.node_link_graph(data)
|
||||
return nx.Graph()
|
||||
|
||||
|
||||
def _save_global_graph(G: nx.Graph) -> None:
|
||||
_GLOBAL_DIR.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
data = _jg.node_link_data(G, edges="links")
|
||||
except TypeError:
|
||||
data = _jg.node_link_data(G)
|
||||
_GLOBAL_GRAPH.write_text(json.dumps(data, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def _file_hash(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
h.update(path.read_bytes())
|
||||
return h.hexdigest()[:16]
|
||||
|
||||
|
||||
def global_add(source_path: Path, repo_tag: str) -> dict:
|
||||
"""Add or update a project graph in the global graph.
|
||||
|
||||
Returns a summary dict with keys: repo_tag, nodes_added, nodes_removed, skipped.
|
||||
Skipped=True means the source graph hasn't changed since last add.
|
||||
"""
|
||||
from graphify.build import prefix_graph_for_global, prune_repo_from_graph
|
||||
|
||||
if not source_path.exists():
|
||||
raise FileNotFoundError(f"graph not found: {source_path}")
|
||||
|
||||
manifest = _load_manifest()
|
||||
src_hash = _file_hash(source_path)
|
||||
|
||||
existing = manifest["repos"].get(repo_tag, {})
|
||||
existing_path = existing.get("source_path", "")
|
||||
if existing_path and existing_path != str(source_path.resolve()):
|
||||
print(
|
||||
f"[graphify global] warning: repo tag '{repo_tag}' previously pointed to "
|
||||
f"{existing_path!r}, now updating to {str(source_path.resolve())!r}. "
|
||||
f"Use --as <tag> to give it a different name.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
if existing.get("source_hash") == src_hash:
|
||||
return {"repo_tag": repo_tag, "nodes_added": 0, "nodes_removed": 0, "skipped": True}
|
||||
|
||||
# Load source graph
|
||||
data = json.loads(source_path.read_text(encoding="utf-8"))
|
||||
if "links" not in data and "edges" in data:
|
||||
data = dict(data, links=data["edges"])
|
||||
try:
|
||||
src_G = _jg.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
src_G = _jg.node_link_graph(data)
|
||||
|
||||
# Prefix IDs for cross-project isolation
|
||||
prefixed = prefix_graph_for_global(src_G, repo_tag)
|
||||
|
||||
# Load global graph and prune stale nodes for this repo
|
||||
G = _load_global_graph()
|
||||
removed = prune_repo_from_graph(G, repo_tag)
|
||||
|
||||
# Merge external-library nodes (no source_file) by label to avoid duplication
|
||||
external_labels = {
|
||||
d.get("label", ""): n
|
||||
for n, d in G.nodes(data=True)
|
||||
if not d.get("source_file") and d.get("label")
|
||||
}
|
||||
nodes_to_skip = set()
|
||||
for node, data in prefixed.nodes(data=True):
|
||||
if not data.get("source_file") and data.get("label") in external_labels:
|
||||
nodes_to_skip.add(node)
|
||||
|
||||
# Compose: add prefixed nodes (except deduplicated externals) into global graph
|
||||
for node, data in prefixed.nodes(data=True):
|
||||
if node not in nodes_to_skip:
|
||||
G.add_node(node, **data)
|
||||
for u, v, data in prefixed.edges(data=True):
|
||||
if u not in nodes_to_skip and v not in nodes_to_skip:
|
||||
G.add_edge(u, v, **data)
|
||||
|
||||
added = prefixed.number_of_nodes() - len(nodes_to_skip)
|
||||
_save_global_graph(G)
|
||||
|
||||
manifest["repos"][repo_tag] = {
|
||||
"added_at": datetime.now(timezone.utc).isoformat(),
|
||||
"source_path": str(source_path.resolve()),
|
||||
"node_count": added,
|
||||
"edge_count": prefixed.number_of_edges(),
|
||||
"source_hash": src_hash,
|
||||
}
|
||||
_save_manifest(manifest)
|
||||
|
||||
return {"repo_tag": repo_tag, "nodes_added": added, "nodes_removed": removed, "skipped": False}
|
||||
|
||||
|
||||
def global_remove(repo_tag: str) -> int:
|
||||
"""Remove all nodes for repo_tag from the global graph. Returns count removed."""
|
||||
from graphify.build import prune_repo_from_graph
|
||||
|
||||
manifest = _load_manifest()
|
||||
if repo_tag not in manifest["repos"]:
|
||||
raise KeyError(f"repo '{repo_tag}' not in global graph")
|
||||
|
||||
G = _load_global_graph()
|
||||
removed = prune_repo_from_graph(G, repo_tag)
|
||||
_save_global_graph(G)
|
||||
|
||||
del manifest["repos"][repo_tag]
|
||||
_save_manifest(manifest)
|
||||
return removed
|
||||
|
||||
|
||||
def global_list() -> dict:
|
||||
"""Return the manifest repos dict."""
|
||||
return _load_manifest().get("repos", {})
|
||||
|
||||
|
||||
def global_path() -> Path:
|
||||
return _GLOBAL_GRAPH
|
||||
+38
-20
@@ -1,7 +1,7 @@
|
||||
# git hook integration - install/uninstall graphify post-commit and post-checkout hooks
|
||||
from __future__ import annotations
|
||||
import configparser
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
_HOOK_MARKER = "# graphify-hook-start"
|
||||
@@ -61,7 +61,13 @@ 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
|
||||
|
||||
@@ -74,12 +80,15 @@ if not changed:
|
||||
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
|
||||
"""
|
||||
|
||||
@@ -111,17 +120,21 @@ GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
|
||||
[ -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
|
||||
"""
|
||||
|
||||
@@ -138,19 +151,24 @@ def _git_root(path: Path) -> Path | 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)
|
||||
if not p.is_absolute():
|
||||
p = root / p
|
||||
cfg = configparser.RawConfigParser()
|
||||
cfg.read(root / ".git" / "config", encoding="utf-8")
|
||||
# configparser lowercases option names; git's hooksPath becomes hookspath
|
||||
custom = cfg.get("core", "hookspath", fallback="").strip()
|
||||
if custom:
|
||||
p = Path(custom).expanduser()
|
||||
if not p.is_absolute():
|
||||
p = root / p
|
||||
# Validate the resolved path stays within the repository root
|
||||
# to prevent supply-chain attacks via malicious core.hooksPath values
|
||||
try:
|
||||
p.resolve().relative_to(root.resolve())
|
||||
except ValueError:
|
||||
pass # Path escapes repo root; fall through to default .git/hooks
|
||||
else:
|
||||
p.mkdir(parents=True, exist_ok=True)
|
||||
return p
|
||||
except (OSError, FileNotFoundError):
|
||||
except Exception:
|
||||
pass
|
||||
d = root / ".git" / "hooks"
|
||||
d.mkdir(exist_ok=True)
|
||||
|
||||
+8
-11
@@ -49,19 +49,16 @@ def _fetch_html(url: str) -> str:
|
||||
|
||||
|
||||
def _html_to_markdown(html: str, url: str) -> str:
|
||||
"""Convert HTML to clean markdown. Uses html2text if available, else basic strip."""
|
||||
"""Convert HTML to clean markdown. Uses markdownify if available, else basic strip."""
|
||||
# Always pre-strip script/style so their text content never leaks into output
|
||||
html = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
|
||||
html = re.sub(r"<style[^>]*>.*?</style>", "", html, flags=re.DOTALL | re.IGNORECASE)
|
||||
try:
|
||||
import html2text
|
||||
h = html2text.HTML2Text()
|
||||
h.ignore_links = False
|
||||
h.ignore_images = True
|
||||
h.body_width = 0
|
||||
return h.handle(html)
|
||||
from markdownify import markdownify
|
||||
return markdownify(html, heading_style="ATX", bullets="-", strip=["img"])
|
||||
except ImportError:
|
||||
# Fallback: strip tags
|
||||
text = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
|
||||
text = re.sub(r"<style[^>]*>.*?</style>", "", text, flags=re.DOTALL | re.IGNORECASE)
|
||||
text = re.sub(r"<[^>]+>", " ", text)
|
||||
# Fallback: basic tag strip
|
||||
text = re.sub(r"<[^>]+>", " ", html)
|
||||
text = re.sub(r"\s+", " ", text).strip()
|
||||
return text[:8000]
|
||||
|
||||
|
||||
+586
@@ -0,0 +1,586 @@
|
||||
# Direct LLM backend for semantic extraction — supports Claude, Kimi K2.6,
|
||||
# Gemini, and OpenAI.
|
||||
# Used by `graphify extract . --backend gemini` 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,
|
||||
"max_tokens": 16384,
|
||||
},
|
||||
"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
|
||||
"max_tokens": 16384,
|
||||
},
|
||||
"ollama": {
|
||||
"base_url": os.environ.get("OLLAMA_BASE_URL", "http://localhost:11434/v1"),
|
||||
"default_model": os.environ.get("OLLAMA_MODEL", "qwen2.5-coder:7b"),
|
||||
"env_key": "OLLAMA_API_KEY",
|
||||
"pricing": {"input": 0.0, "output": 0.0},
|
||||
"temperature": 0,
|
||||
"max_tokens": 16384,
|
||||
},
|
||||
"gemini": {
|
||||
"base_url": "https://generativelanguage.googleapis.com/v1beta/openai/",
|
||||
"default_model": "gemini-3-flash-preview",
|
||||
"env_keys": ["GEMINI_API_KEY", "GOOGLE_API_KEY"],
|
||||
"model_env_key": "GRAPHIFY_GEMINI_MODEL",
|
||||
"pricing": {"input": 0.50, "output": 3.00}, # USD per 1M tokens
|
||||
"temperature": 0,
|
||||
"reasoning_effort": "low",
|
||||
"max_completion_tokens": 16384,
|
||||
},
|
||||
"openai": {
|
||||
"base_url": "https://api.openai.com/v1",
|
||||
"default_model": "gpt-4.1-mini",
|
||||
"env_key": "OPENAI_API_KEY",
|
||||
"model_env_key": "GRAPHIFY_OPENAI_MODEL",
|
||||
"pricing": {"input": 0.40, "output": 1.60}, # USD per 1M tokens
|
||||
"temperature": 0,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _resolve_max_tokens(default: int) -> int:
|
||||
"""Honour GRAPHIFY_MAX_OUTPUT_TOKENS env var override, else use backend default."""
|
||||
raw = os.environ.get("GRAPHIFY_MAX_OUTPUT_TOKENS", "").strip()
|
||||
if raw:
|
||||
try:
|
||||
v = int(raw)
|
||||
if v > 0:
|
||||
return v
|
||||
except ValueError:
|
||||
pass
|
||||
return default
|
||||
|
||||
_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 _backend_env_keys(backend: str) -> list[str]:
|
||||
"""Return accepted API-key environment variables for a backend."""
|
||||
cfg = BACKENDS[backend]
|
||||
keys = cfg.get("env_keys")
|
||||
if keys:
|
||||
return list(keys)
|
||||
return [cfg["env_key"]]
|
||||
|
||||
|
||||
def _get_backend_api_key(backend: str) -> str:
|
||||
"""Return the first configured API key for backend, or an empty string."""
|
||||
for env_key in _backend_env_keys(backend):
|
||||
value = os.environ.get(env_key)
|
||||
if value:
|
||||
return value
|
||||
return ""
|
||||
|
||||
|
||||
def _format_backend_env_keys(backend: str) -> str:
|
||||
"""Return user-facing accepted API-key variable names."""
|
||||
return " or ".join(_backend_env_keys(backend))
|
||||
|
||||
|
||||
def _default_model_for_backend(backend: str) -> str:
|
||||
"""Return configured model override or backend default model."""
|
||||
cfg = BACKENDS[backend]
|
||||
model_env_key = cfg.get("model_env_key")
|
||||
if model_env_key:
|
||||
model = os.environ.get(model_env_key)
|
||||
if model:
|
||||
return model
|
||||
return cfg["default_model"]
|
||||
|
||||
|
||||
def _call_openai_compat(
|
||||
base_url: str,
|
||||
api_key: str,
|
||||
model: str,
|
||||
user_message: str,
|
||||
temperature: float | None = 0,
|
||||
reasoning_effort: str | None = None,
|
||||
max_completion_tokens: int = 8192,
|
||||
*,
|
||||
backend: str = "",
|
||||
) -> dict:
|
||||
"""Call any OpenAI-compatible API (Kimi, OpenAI, etc.) and return parsed JSON."""
|
||||
try:
|
||||
from openai import OpenAI
|
||||
except ImportError as exc:
|
||||
pkg_hint = "graphifyy[kimi]" if backend == "kimi" else "openai"
|
||||
raise ImportError(
|
||||
"Gemini/Kimi/Ollama/OpenAI-compatible extraction requires the openai package. "
|
||||
f"Run: pip install {pkg_hint}"
|
||||
) 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": max_completion_tokens,
|
||||
}
|
||||
if temperature is not None:
|
||||
kwargs["temperature"] = temperature
|
||||
if reasoning_effort is not None:
|
||||
kwargs["reasoning_effort"] = reasoning_effort
|
||||
# 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
|
||||
output_tokens = result["output_tokens"]
|
||||
if output_tokens < 50 and backend == "ollama":
|
||||
print(
|
||||
"[graphify] warning: ollama returned very few tokens — the model may be "
|
||||
"too small or not following the JSON instruction format. "
|
||||
"Try a larger model with --model (e.g. --model qwen2.5-coder:14b).",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int = 8192) -> 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=max_tokens,
|
||||
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 _get_backend_api_key(backend)
|
||||
if not key and backend == "ollama":
|
||||
key = "ollama" # Ollama ignores auth but openai client requires non-empty
|
||||
if not key:
|
||||
raise ValueError(
|
||||
f"No API key for backend '{backend}'. "
|
||||
f"Set {_format_backend_env_keys(backend)} or pass api_key=."
|
||||
)
|
||||
mdl = model or _default_model_for_backend(backend)
|
||||
user_msg = _read_files(files, root)
|
||||
max_out = _resolve_max_tokens(cfg.get("max_tokens", 8192))
|
||||
|
||||
if backend == "claude":
|
||||
return _call_claude(key, mdl, user_msg, max_tokens=max_out)
|
||||
else:
|
||||
return _call_openai_compat(
|
||||
cfg["base_url"],
|
||||
key,
|
||||
mdl,
|
||||
user_msg,
|
||||
temperature=cfg.get("temperature", 0),
|
||||
reasoning_effort=cfg.get("reasoning_effort"),
|
||||
max_completion_tokens=cfg.get("max_completion_tokens", max_out),
|
||||
backend=backend,
|
||||
)
|
||||
|
||||
|
||||
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.
|
||||
|
||||
Priority: gemini → kimi → ollama (opt-in via OLLAMA_BASE_URL) → claude → openai.
|
||||
Ollama is opt-in via env var — never auto-probed without OLLAMA_BASE_URL set.
|
||||
Claude is the default for the skill.md subagent pipeline and is never forced here.
|
||||
"""
|
||||
for backend in ("gemini", "kimi"):
|
||||
if _get_backend_api_key(backend):
|
||||
return backend
|
||||
if os.environ.get("OLLAMA_BASE_URL"):
|
||||
return "ollama"
|
||||
for backend in ("claude", "openai"):
|
||||
if _get_backend_api_key(backend):
|
||||
return backend
|
||||
return None
|
||||
+22
-7
@@ -23,6 +23,8 @@ def generate(
|
||||
token_cost: dict,
|
||||
root: str,
|
||||
suggested_questions: list[dict] | None = None,
|
||||
min_community_size: int = 3,
|
||||
built_at_commit: str | None = None,
|
||||
) -> str:
|
||||
today = date.today().isoformat()
|
||||
|
||||
@@ -52,16 +54,31 @@ def generate(
|
||||
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)}
|
||||
thin_count_summary = sum(
|
||||
1 for nodes in communities.values()
|
||||
if 0 < sum(1 for n in nodes if not _ifn(G, n)) < min_community_size
|
||||
)
|
||||
shown_count = len(communities) - thin_count_summary
|
||||
|
||||
lines += [
|
||||
"",
|
||||
"## Summary",
|
||||
f"- {G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(non_empty)} communities detected",
|
||||
f"- {G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(communities)} communities"
|
||||
+ (f" ({shown_count} shown, {thin_count_summary} thin omitted)" if thin_count_summary else ""),
|
||||
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",
|
||||
]
|
||||
|
||||
if built_at_commit:
|
||||
lines += [
|
||||
"",
|
||||
"## Graph Freshness",
|
||||
f"- Built from commit: `{built_at_commit[:8]}`",
|
||||
"- Run `git rev-parse HEAD` and compare to check if the graph is stale.",
|
||||
"- Run `graphify update .` after code changes (no API cost).",
|
||||
]
|
||||
|
||||
# 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:
|
||||
@@ -108,7 +125,7 @@ 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"]
|
||||
lines += ["", f"## Communities ({len(communities)} total, {thin_count_summary} thin omitted)"]
|
||||
for cid, nodes in communities.items():
|
||||
label = community_labels.get(cid, f"Community {cid}")
|
||||
score = cohesion_scores.get(cid, 0.0)
|
||||
@@ -116,6 +133,8 @@ def generate(
|
||||
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 += [
|
||||
@@ -157,11 +176,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.")
|
||||
|
||||
|
||||
+37
-3
@@ -1,6 +1,7 @@
|
||||
# Security helpers - URL validation, safe fetch, path guards, label sanitisation
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import html
|
||||
import re
|
||||
import urllib.error
|
||||
@@ -58,12 +59,45 @@ def validate_url(url: str) -> str:
|
||||
f"Blocked private/internal IP {addr} (resolved from '{hostname}'). "
|
||||
f"Got: {url!r}"
|
||||
)
|
||||
except socket.gaierror:
|
||||
pass # DNS failure will surface later during fetch
|
||||
except socket.gaierror as exc:
|
||||
raise ValueError(
|
||||
f"DNS resolution failed for '{hostname}': {exc}. Got: {url!r}"
|
||||
) from exc
|
||||
|
||||
return url
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _ssrf_guarded_socket():
|
||||
"""Patch socket.getaddrinfo for the duration of a fetch to catch DNS rebinding.
|
||||
|
||||
Validates every IP that urllib resolves so a DNS server cannot return a public IP
|
||||
for validate_url and swap to a private IP for the actual connection (TOCTOU fix).
|
||||
Not thread-safe, but graphify is a single-threaded CLI tool.
|
||||
"""
|
||||
original = socket.getaddrinfo
|
||||
|
||||
def _guarded(host, port, *args, **kwargs):
|
||||
results = original(host, port, *args, **kwargs)
|
||||
for info in results:
|
||||
addr = info[4][0]
|
||||
try:
|
||||
ip = ipaddress.ip_address(addr)
|
||||
except ValueError:
|
||||
continue
|
||||
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local:
|
||||
raise OSError(
|
||||
f"SSRF blocked: IP {addr} resolved from '{host}' is private/reserved"
|
||||
)
|
||||
return results
|
||||
|
||||
socket.getaddrinfo = _guarded
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
socket.getaddrinfo = original
|
||||
|
||||
|
||||
class _NoFileRedirectHandler(urllib.request.HTTPRedirectHandler):
|
||||
"""Redirect handler that re-validates every redirect target.
|
||||
|
||||
@@ -104,7 +138,7 @@ def safe_fetch(url: str, max_bytes: int = _MAX_FETCH_BYTES, timeout: int = 30) -
|
||||
opener = _build_opener()
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 graphify/1.0"})
|
||||
|
||||
with opener.open(req, timeout=timeout) as resp:
|
||||
with _ssrf_guarded_socket(), opener.open(req, timeout=timeout) as resp:
|
||||
# urllib raises HTTPError for non-2xx when using urlopen directly;
|
||||
# with a custom opener we check manually to be safe.
|
||||
status = getattr(resp, "status", None) or getattr(resp, "code", None)
|
||||
|
||||
+127
-12
@@ -45,6 +45,9 @@ def _strip_diacritics(text: str) -> str:
|
||||
return "".join(c for c in nfkd if not unicodedata.combining(c))
|
||||
|
||||
|
||||
_EXACT_MATCH_BONUS = 100.0
|
||||
|
||||
|
||||
def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
|
||||
scored = []
|
||||
norm_terms = [_strip_diacritics(t).lower() for t in terms]
|
||||
@@ -52,11 +55,76 @@ def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
|
||||
norm_label = data.get("norm_label") or _strip_diacritics(data.get("label") or "").lower()
|
||||
source = (data.get("source_file") or "").lower()
|
||||
score = sum(1 for t in norm_terms if t in norm_label) + sum(0.5 for t in norm_terms if t in source)
|
||||
# Exact match: single term equals the full label (strip trailing () for functions)
|
||||
if any(t == norm_label or t == norm_label.rstrip("()") for t in norm_terms):
|
||||
score += _EXACT_MATCH_BONUS
|
||||
if score > 0:
|
||||
scored.append((score, nid))
|
||||
return sorted(scored, reverse=True)
|
||||
|
||||
|
||||
_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)
|
||||
@@ -89,11 +157,18 @@ def _dfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], lis
|
||||
return visited, edges_seen
|
||||
|
||||
|
||||
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000) -> str:
|
||||
"""Render subgraph as text, cutting at token_budget (approx 3 chars/token)."""
|
||||
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000, *, seeds: list[str] | None = None) -> str:
|
||||
"""Render subgraph as text, cutting at token_budget (approx 3 chars/token).
|
||||
|
||||
seeds: exact-match nodes rendered first before the degree-sorted expansion,
|
||||
so the queried symbol always appears at the top of the output.
|
||||
"""
|
||||
char_budget = token_budget * 3
|
||||
lines = []
|
||||
for nid in sorted(nodes, key=lambda n: G.degree(n), reverse=True):
|
||||
seed_set = set(seeds or [])
|
||||
ordered = [n for n in (seeds or []) if n in nodes] + \
|
||||
sorted(nodes - seed_set, key=lambda n: G.degree(n), reverse=True)
|
||||
for nid in ordered:
|
||||
d = G.nodes[nid]
|
||||
line = f"NODE {sanitize_label(d.get('label', nid))} [src={d.get('source_file', '')} loc={d.get('source_location', '')} community={d.get('community', '')}]"
|
||||
lines.append(line)
|
||||
@@ -101,7 +176,13 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
|
||||
if u in nodes and v in nodes:
|
||||
raw = G[u][v]
|
||||
d = next(iter(raw.values()), {}) if isinstance(G, (nx.MultiGraph, nx.MultiDiGraph)) else raw
|
||||
line = f"EDGE {sanitize_label(G.nodes[u].get('label', u))} --{d.get('relation', '')} [{d.get('confidence', '')}]--> {sanitize_label(G.nodes[v].get('label', v))}"
|
||||
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:
|
||||
@@ -109,6 +190,34 @@ 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 (diacritic-insensitive)."""
|
||||
term = _strip_diacritics(label).lower()
|
||||
@@ -175,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"],
|
||||
},
|
||||
@@ -239,14 +353,15 @@ 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()
|
||||
|
||||
+26
-2
@@ -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 "
|
||||
|
||||
+26
-2
@@ -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 "
|
||||
|
||||
+27
-2
@@ -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,7 +300,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}
|
||||
```
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
@@ -312,6 +313,30 @@ Wait for all subagents. For each result:
|
||||
|
||||
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 "
|
||||
|
||||
@@ -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,7 +296,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}
|
||||
```
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
@@ -308,6 +309,30 @@ Wait for all subagents. For each result:
|
||||
|
||||
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-out/.graphify_python) -c "
|
||||
@@ -818,7 +843,10 @@ 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).')
|
||||
else:
|
||||
print(f'{len(deleted)} file(s) deleted since last run — no ghost nodes in graph, already clean.')
|
||||
|
||||
# Merge: new nodes/edges into existing graph
|
||||
G_existing.update(G_new)
|
||||
|
||||
+27
-2
@@ -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,7 +297,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}
|
||||
```
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
@@ -309,6 +310,30 @@ Wait for all subagents. For each result:
|
||||
|
||||
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 "
|
||||
|
||||
+26
-2
@@ -234,7 +234,7 @@ Process each file one at a time. For each file:
|
||||
- INFERRED: reasonable inference (shared structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain — flag it, do not omit
|
||||
- Code files: semantic edges AST cannot find. Do not re-extract imports.
|
||||
- Doc/paper files: named concepts, entities, citations, and rationale nodes (WHY decisions were made → `rationale_for` edges)
|
||||
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. 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.
|
||||
@@ -243,7 +243,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`.
|
||||
|
||||
@@ -253,6 +253,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 "
|
||||
|
||||
@@ -261,7 +261,8 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. 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.
|
||||
@@ -297,7 +298,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}
|
||||
```
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
@@ -310,6 +311,30 @@ Wait for all subagents. For each result:
|
||||
|
||||
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-out/.graphify_python) -c "
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+28
-3
@@ -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:
|
||||
@@ -305,6 +306,30 @@ Wait for all subagents. For each result:
|
||||
|
||||
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 "
|
||||
@@ -825,7 +850,7 @@ G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None,
|
||||
'files': {'code': [], 'document': [], 'paper': []}}
|
||||
tokens = {'input': 0, 'output':': 0}
|
||||
tokens = {'input': 0, 'output': 0}
|
||||
|
||||
communities = cluster(G)
|
||||
cohesion = score_all(G, communities)
|
||||
|
||||
@@ -151,13 +151,16 @@ if cached_path.exists():
|
||||
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': 0, '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')
|
||||
"
|
||||
|
||||
@@ -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,14 +279,20 @@ 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**
|
||||
@@ -298,6 +305,30 @@ Wait for all subagents. For each result:
|
||||
|
||||
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
|
||||
python -c "
|
||||
@@ -784,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.')
|
||||
"
|
||||
```
|
||||
|
||||
|
||||
+110
-430
@@ -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)
|
||||
@@ -40,25 +43,39 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
## What graphify is for
|
||||
|
||||
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:
|
||||
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.
|
||||
|
||||
Use it for:
|
||||
- A codebase you're new to (understand architecture before touching anything)
|
||||
- A reading list (papers + tweets + notes → one navigable graph)
|
||||
- A research corpus (citation graph + concept graph in one)
|
||||
- Your personal /raw folder (drop everything in, let it grow, query it)
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If no path was given, use `.` (current directory). Do not ask the user for a path.
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL — run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
|
||||
### Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given)
|
||||
|
||||
**Single repo:**
|
||||
```bash
|
||||
LOCAL_PATH=$(graphify clone <github-url> [--branch <branch>])
|
||||
# Use LOCAL_PATH as the target for all subsequent steps
|
||||
```
|
||||
|
||||
**Multiple repos (cross-repo graph):**
|
||||
```bash
|
||||
# Clone each repo, run the full pipeline on each, then merge
|
||||
graphify clone <url1> # → ~/.graphify/repos/<owner1>/<repo1>
|
||||
graphify clone <url2> # → ~/.graphify/repos/<owner2>/<repo2>
|
||||
# Run /graphify on each local path to produce their graph.json files
|
||||
# Then merge:
|
||||
graphify merge-graphs \
|
||||
~/.graphify/repos/<owner1>/<repo1>/graphify-out/graph.json \
|
||||
~/.graphify/repos/<owner2>/<repo2>/graphify-out/graph.json \
|
||||
--out graphify-out/cross-repo-graph.json
|
||||
```
|
||||
|
||||
Graphify clones into `~/.graphify/repos/<owner>/<repo>` and reuses existing clones on repeat runs. Each node in the merged graph carries a `repo` attribute so you can filter by origin.
|
||||
|
||||
### Step 1 - Ensure graphify is installed
|
||||
|
||||
```bash
|
||||
@@ -84,6 +101,8 @@ if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
|
||||
# Write interpreter path for all subsequent steps (persists across invocations)
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
# Save scan root so `graphify update` (no args) knows where to look next time
|
||||
echo "$(cd INPUT_PATH && pwd)" > graphify-out/.graphify_root
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
@@ -170,7 +189,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 `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user:
|
||||
> Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`).
|
||||
|
||||
Print it once, then continue. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="gemini")` for semantic extraction instead of dispatching Claude subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it.
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
@@ -272,7 +296,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.
|
||||
@@ -301,16 +326,22 @@ 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.
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the filename without extension and entity is the symbol name, both normalized (lowercase, non-alphanumeric chars replaced with `_`). Example: `src/auth/session.py` + `ValidateToken` → `session_validatetoken`. This must match the ID the AST extractor generates so cross-references between code and semantic nodes connect correctly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
{"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**
|
||||
@@ -323,6 +354,30 @@ Wait for all subagents. For each result:
|
||||
|
||||
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-out/.graphify_python) -c "
|
||||
@@ -500,84 +555,18 @@ Replace INPUT_PATH with the actual path.
|
||||
|
||||
If `--obsidian` was given:
|
||||
|
||||
- If `--obsidian-dir <path>` was also given, use that path as the vault directory. Otherwise default to `graphify-out/obsidian`.
|
||||
- If `--obsidian-dir <path>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`.
|
||||
|
||||
```bash
|
||||
$(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-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()}
|
||||
|
||||
obsidian_dir = 'OBSIDIAN_DIR' # replace with --obsidian-dir value, or 'graphify-out/obsidian' if not given
|
||||
|
||||
n = to_obsidian(G, communities, obsidian_dir, community_labels=labels or None, cohesion=cohesion)
|
||||
print(f'Obsidian vault: {n} notes in {obsidian_dir}/')
|
||||
|
||||
to_canvas(G, communities, f'{obsidian_dir}/graph.canvas', community_labels=labels or None)
|
||||
print(f'Canvas: {obsidian_dir}/graph.canvas - open in Obsidian for structured community layout')
|
||||
print()
|
||||
print(f'Open {obsidian_dir}/ as a vault in Obsidian.')
|
||||
print(' Graph view - nodes colored by community (set automatically)')
|
||||
print(' graph.canvas - structured layout with communities as groups')
|
||||
print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries')
|
||||
"
|
||||
graphify export obsidian
|
||||
# or with custom dir: graphify export obsidian --dir ~/vaults/my-project
|
||||
```
|
||||
|
||||
Generate the HTML graph (always, unless `--no-viz`):
|
||||
|
||||
```bash
|
||||
$(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-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()}
|
||||
|
||||
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')
|
||||
"
|
||||
graphify export html # auto-aggregates to community view if graph > 5000 nodes
|
||||
# or: graphify export html --no-viz
|
||||
```
|
||||
|
||||
### Step 6b - Wiki (only if --wiki flag)
|
||||
@@ -587,27 +576,7 @@ else:
|
||||
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')
|
||||
"
|
||||
graphify export wiki
|
||||
```
|
||||
|
||||
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
|
||||
@@ -615,80 +584,27 @@ print(' graphify-out/wiki/index.md -> agent entry point')
|
||||
**If `--neo4j`** - generate a Cypher file for manual import:
|
||||
|
||||
```bash
|
||||
$(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-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')
|
||||
"
|
||||
graphify export neo4j
|
||||
```
|
||||
|
||||
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
|
||||
|
||||
```bash
|
||||
$(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-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()}
|
||||
|
||||
result = push_to_neo4j(G, uri='NEO4J_URI', user='NEO4J_USER', password='NEO4J_PASSWORD', communities=communities)
|
||||
print(f'Pushed to Neo4j: {result[\"nodes\"]} nodes, {result[\"edges\"]} edges')
|
||||
"
|
||||
graphify export neo4j --push bolt://localhost:7687 --user neo4j --password PASSWORD
|
||||
```
|
||||
|
||||
Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.
|
||||
Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.
|
||||
|
||||
### Step 7b - SVG export (only if --svg flag)
|
||||
|
||||
```bash
|
||||
$(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-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()}
|
||||
|
||||
to_svg(G, communities, 'graphify-out/graph.svg', community_labels=labels or None)
|
||||
print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
|
||||
"
|
||||
graphify export svg
|
||||
```
|
||||
|
||||
### Step 7c - GraphML export (only if --graphml flag)
|
||||
|
||||
```bash
|
||||
$(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-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()}
|
||||
|
||||
to_graphml(G, communities, 'graphify-out/graph.graphml')
|
||||
print('graph.graphml written - open in Gephi, yEd, or any GraphML tool')
|
||||
"
|
||||
graphify export graphml
|
||||
```
|
||||
|
||||
### Step 7d - MCP server (only if --mcp flag)
|
||||
@@ -716,15 +632,7 @@ To configure in Claude Desktop, add to `claude_desktop_config.json`:
|
||||
If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run:
|
||||
|
||||
```bash
|
||||
$(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-out/.graphify_detect.json').read_text())
|
||||
result = run_benchmark('graphify-out/graph.json', corpus_words=detection['total_words'])
|
||||
print_benchmark(result)
|
||||
"
|
||||
graphify benchmark
|
||||
```
|
||||
|
||||
Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora.
|
||||
@@ -768,7 +676,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
|
||||
"
|
||||
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_labels.json graphify-out/.graphify_chunk_*.json
|
||||
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -850,7 +758,7 @@ import json
|
||||
from pathlib import Path
|
||||
|
||||
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','.lua','.toc'}
|
||||
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc','.f','.F','.f90','.F90','.f95','.F95','.f03','.F03','.f08','.F08'}
|
||||
new_files = result.get('new_files', {})
|
||||
all_changed = [f for files in new_files.values() for f in files]
|
||||
code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
|
||||
@@ -887,7 +795,10 @@ 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)
|
||||
@@ -903,6 +814,14 @@ merged_out = {
|
||||
}
|
||||
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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -942,45 +861,10 @@ Clean up after: `rm -f graphify-out/.graphify_old.json`
|
||||
|
||||
## For --cluster-only
|
||||
|
||||
Skip Steps 1–3. Load the existing graph from `graphify-out/graph.json` and re-run clustering:
|
||||
Skip Steps 1–3. Re-run clustering on the existing graph:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections
|
||||
from graphify.report import generate
|
||||
from graphify.export import to_json
|
||||
from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None,
|
||||
'files': {'code': [], 'document': [], 'paper': []}}
|
||||
tokens = {'input': 0, 'output': 0}
|
||||
|
||||
communities = cluster(G)
|
||||
cohesion = score_all(G, communities)
|
||||
gods = god_nodes(G)
|
||||
surprises = surprising_connections(G, communities)
|
||||
labels = {cid: 'Community ' + str(cid) for cid in communities}
|
||||
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, '.')
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
to_json(G, communities, 'graphify-out/graph.json')
|
||||
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
'cohesion': {str(k): v for k, v in cohesion.items()},
|
||||
'gods': gods,
|
||||
'surprises': surprises,
|
||||
}
|
||||
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
print(f'Re-clustered: {len(communities)} communities')
|
||||
"
|
||||
graphify cluster-only .
|
||||
```
|
||||
|
||||
Then run Steps 5–9 as normal (label communities, generate viz, benchmark, clean up, report).
|
||||
@@ -996,113 +880,12 @@ Two traversal modes - choose based on the question:
|
||||
| BFS (default) | _(none)_ | "What is X connected to?" - broad context, nearest neighbors first |
|
||||
| DFS | `--dfs` | "How does X reach Y?" - trace a specific chain or dependency path |
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(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.')
|
||||
raise SystemExit(1)
|
||||
"
|
||||
```
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
Load `graphify-out/graph.json`, then:
|
||||
|
||||
1. Find the 1-3 nodes whose label best matches key terms in the question.
|
||||
2. Run the appropriate traversal from each starting node.
|
||||
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
|
||||
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
|
||||
5. If the graph lacks enough information, say so - do not hallucinate edges.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
question = 'QUESTION'
|
||||
mode = 'MODE' # 'bfs' or 'dfs'
|
||||
terms = [t.lower() for t in question.split() if len(t) > 3]
|
||||
|
||||
# Find best-matching start nodes
|
||||
scored = []
|
||||
for nid, ndata in G.nodes(data=True):
|
||||
label = ndata.get('label', '').lower()
|
||||
score = sum(1 for t in terms if t in label)
|
||||
if score > 0:
|
||||
scored.append((score, nid))
|
||||
scored.sort(reverse=True)
|
||||
start_nodes = [nid for _, nid in scored[:3]]
|
||||
|
||||
if not start_nodes:
|
||||
print('No matching nodes found for query terms:', terms)
|
||||
sys.exit(0)
|
||||
|
||||
subgraph_nodes = set()
|
||||
subgraph_edges = []
|
||||
|
||||
if mode == 'dfs':
|
||||
# DFS: follow one path as deep as possible before backtracking.
|
||||
# Depth-limited to 6 to avoid traversing the whole graph.
|
||||
visited = set()
|
||||
stack = [(n, 0) for n in reversed(start_nodes)]
|
||||
while stack:
|
||||
node, depth = stack.pop()
|
||||
if node in visited or depth > 6:
|
||||
continue
|
||||
visited.add(node)
|
||||
subgraph_nodes.add(node)
|
||||
for neighbor in G.neighbors(node):
|
||||
if neighbor not in visited:
|
||||
stack.append((neighbor, depth + 1))
|
||||
subgraph_edges.append((node, neighbor))
|
||||
else:
|
||||
# BFS: explore all neighbors layer by layer up to depth 3.
|
||||
frontier = set(start_nodes)
|
||||
subgraph_nodes = set(start_nodes)
|
||||
for _ in range(3):
|
||||
next_frontier = set()
|
||||
for n in frontier:
|
||||
for neighbor in G.neighbors(n):
|
||||
if neighbor not in subgraph_nodes:
|
||||
next_frontier.add(neighbor)
|
||||
subgraph_edges.append((n, neighbor))
|
||||
subgraph_nodes.update(next_frontier)
|
||||
frontier = next_frontier
|
||||
|
||||
# Token-budget aware output: rank by relevance, cut at budget (~4 chars/token)
|
||||
token_budget = BUDGET # default 2000
|
||||
char_budget = token_budget * 4
|
||||
|
||||
# Score each node by term overlap for ranked output
|
||||
def relevance(nid):
|
||||
label = G.nodes[nid].get('label', '').lower()
|
||||
return sum(1 for t in terms if t in label)
|
||||
|
||||
ranked_nodes = sorted(subgraph_nodes, key=relevance, reverse=True)
|
||||
|
||||
lines = [f'Traversal: {mode.upper()} | Start: {[G.nodes[n].get(\"label\",n) for n in start_nodes]} | {len(subgraph_nodes)} nodes']
|
||||
for nid in ranked_nodes:
|
||||
d = G.nodes[nid]
|
||||
lines.append(f' NODE {d.get(\"label\", nid)} [src={d.get(\"source_file\",\"\")} loc={d.get(\"source_location\",\"\")}]')
|
||||
for u, v in subgraph_edges:
|
||||
if u in subgraph_nodes and v in subgraph_nodes:
|
||||
d = G.edges[u, v]
|
||||
lines.append(f' EDGE {G.nodes[u].get(\"label\",u)} --{d.get(\"relation\",\"\")} [{d.get(\"confidence\",\"\")}]--> {G.nodes[v].get(\"label\",v)}')
|
||||
|
||||
output = '\n'.join(lines)
|
||||
if len(output) > char_budget:
|
||||
output = output[:char_budget] + f'\n... (truncated at ~{token_budget} token budget - use --budget N for more)'
|
||||
print(output)
|
||||
"
|
||||
graphify query "QUESTION"
|
||||
# or: graphify query "QUESTION" --dfs --budget 3000
|
||||
```
|
||||
|
||||
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
|
||||
Replace `QUESTION` with the user's actual question. Answer using **only** what the graph output contains. Quote `source_location` when citing a specific fact. If the graph lacks enough information, say so - do not hallucinate edges.
|
||||
|
||||
After writing the answer, save it back into the graph so it improves future queries:
|
||||
|
||||
@@ -1118,66 +901,11 @@ Replace `QUESTION` with the question, `ANSWER` with your full answer text, `SOUR
|
||||
|
||||
Find the shortest path between two named concepts in the graph.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(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.')
|
||||
raise SystemExit(1)
|
||||
"
|
||||
```
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
a_term = 'NODE_A'
|
||||
b_term = 'NODE_B'
|
||||
|
||||
def find_node(term):
|
||||
term = term.lower()
|
||||
scored = sorted(
|
||||
[(sum(1 for w in term.split() if w in G.nodes[n].get('label','').lower()), n)
|
||||
for n in G.nodes()],
|
||||
reverse=True
|
||||
)
|
||||
return scored[0][1] if scored and scored[0][0] > 0 else None
|
||||
|
||||
src = find_node(a_term)
|
||||
tgt = find_node(b_term)
|
||||
|
||||
if not src or not tgt:
|
||||
print(f'Could not find nodes matching: {a_term!r} or {b_term!r}')
|
||||
sys.exit(0)
|
||||
|
||||
try:
|
||||
path = nx.shortest_path(G, src, tgt)
|
||||
print(f'Shortest path ({len(path)-1} hops):')
|
||||
for i, nid in enumerate(path):
|
||||
label = G.nodes[nid].get('label', nid)
|
||||
if i < len(path) - 1:
|
||||
edge = G.edges[nid, path[i+1]]
|
||||
rel = edge.get('relation', '')
|
||||
conf = edge.get('confidence', '')
|
||||
print(f' {label} --{rel}--> [{conf}]')
|
||||
else:
|
||||
print(f' {label}')
|
||||
except nx.NetworkXNoPath:
|
||||
print(f'No path found between {a_term!r} and {b_term!r}')
|
||||
except nx.NodeNotFound as e:
|
||||
print(f'Node not found: {e}')
|
||||
"
|
||||
graphify path "NODE_A" "NODE_B"
|
||||
```
|
||||
|
||||
Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then explain the path in plain language - what each hop means, why it's significant.
|
||||
Replace `NODE_A` and `NODE_B` with the actual concept names. Then explain the path in plain language - what each hop means, why it's significant.
|
||||
|
||||
After writing the explanation, save it back:
|
||||
|
||||
@@ -1191,56 +919,8 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
|
||||
|
||||
Give a plain-language explanation of a single node - everything connected to it.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(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.')
|
||||
raise SystemExit(1)
|
||||
"
|
||||
```
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
term = 'NODE_NAME'
|
||||
term_lower = term.lower()
|
||||
|
||||
# Find best matching node
|
||||
scored = sorted(
|
||||
[(sum(1 for w in term_lower.split() if w in G.nodes[n].get('label','').lower()), n)
|
||||
for n in G.nodes()],
|
||||
reverse=True
|
||||
)
|
||||
if not scored or scored[0][0] == 0:
|
||||
print(f'No node matching {term!r}')
|
||||
sys.exit(0)
|
||||
|
||||
nid = scored[0][1]
|
||||
data_n = G.nodes[nid]
|
||||
print(f'NODE: {data_n.get(\"label\", nid)}')
|
||||
print(f' source: {data_n.get(\"source_file\",\"unknown\")}')
|
||||
print(f' type: {data_n.get(\"file_type\",\"unknown\")}')
|
||||
print(f' degree: {G.degree(nid)}')
|
||||
print()
|
||||
print('CONNECTIONS:')
|
||||
for neighbor in G.neighbors(nid):
|
||||
edge = G.edges[nid, neighbor]
|
||||
nlabel = G.nodes[neighbor].get('label', neighbor)
|
||||
rel = edge.get('relation', '')
|
||||
conf = edge.get('confidence', '')
|
||||
src_file = G.nodes[neighbor].get('source_file', '')
|
||||
print(f' --{rel}--> {nlabel} [{conf}] ({src_file})')
|
||||
"
|
||||
graphify explain "NODE_NAME"
|
||||
```
|
||||
|
||||
Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations.
|
||||
|
||||
@@ -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"}
|
||||
|
||||
+71
-19
@@ -1,10 +1,23 @@
|
||||
# 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")
|
||||
|
||||
|
||||
def _git_head() -> str | None:
|
||||
"""Return current git HEAD commit hash, or None outside a repo."""
|
||||
import subprocess as _sp
|
||||
try:
|
||||
r = _sp.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, timeout=3)
|
||||
return r.stdout.strip() if r.returncode == 0 else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
from graphify.detect import CODE_EXTENSIONS, DOC_EXTENSIONS, PAPER_EXTENSIONS, IMAGE_EXTENSIONS
|
||||
|
||||
@@ -33,9 +46,13 @@ def _relativize_source_files(payload: dict, root: Path) -> None:
|
||||
continue
|
||||
|
||||
|
||||
def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
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()
|
||||
@@ -53,27 +70,40 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
detected = detect(watch_path, follow_symlinks=follow_symlinks)
|
||||
code_files = [Path(f) for f in detected['files']['code']]
|
||||
|
||||
# Include document files that have AST extractors (e.g. .md, .mdx)
|
||||
from graphify.extract import _get_extractor
|
||||
for doc_file in detected['files'].get('document', []):
|
||||
p = Path(doc_file)
|
||||
if _get_extractor(p) is not None:
|
||||
code_files.append(p)
|
||||
|
||||
if not code_files:
|
||||
print("[graphify watch] No code files found - nothing to rebuild.")
|
||||
return False
|
||||
|
||||
commit = _git_head()
|
||||
result = extract(code_files, cache_root=watch_root)
|
||||
|
||||
# Preserve semantic nodes/edges from a previous full run.
|
||||
# AST-only rebuild replaces code nodes; doc/paper/image nodes are kept.
|
||||
out = watch_path / "graphify-out"
|
||||
# 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"))
|
||||
code_ids = {n["id"] for n in existing.get("nodes", []) if n.get("file_type") == "code"}
|
||||
sem_nodes = [n for n in existing.get("nodes", []) if n.get("file_type") != "code"]
|
||||
sem_edges = [e for e in existing.get("links", existing.get("edges", []))
|
||||
if e.get("confidence") in ("INFERRED", "AMBIGUOUS")
|
||||
or (e.get("source") not in code_ids and e.get("target") not in code_ids)]
|
||||
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"] + sem_nodes,
|
||||
"edges": result["edges"] + sem_edges,
|
||||
"nodes": result["nodes"] + preserved_nodes,
|
||||
"edges": result["edges"] + preserved_edges,
|
||||
"hyperedges": existing.get("hyperedges", []),
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0,
|
||||
@@ -94,15 +124,35 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
cohesion = score_all(G, communities)
|
||||
gods = god_nodes(G)
|
||||
surprises = surprising_connections(G, communities)
|
||||
labels = {cid: "Community " + str(cid) for cid in communities}
|
||||
labels_file = out / ".graphify_labels.json"
|
||||
try:
|
||||
raw = json.loads(labels_file.read_text(encoding="utf-8")) if labels_file.exists() else {}
|
||||
labels = {int(k): v for k, v in raw.items() if int(k) in communities}
|
||||
except Exception:
|
||||
raw = {}
|
||||
labels = {}
|
||||
for cid in communities:
|
||||
if cid not in labels:
|
||||
labels[cid] = "Community " + str(cid)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
out.mkdir(exist_ok=True)
|
||||
(out / ".graphify_root").write_text(str(watch_root), encoding="utf-8")
|
||||
|
||||
json_written = to_json(G, communities, str(out / "graph.json"), force=force, built_at_commit=commit)
|
||||
if not json_written:
|
||||
return False
|
||||
|
||||
try:
|
||||
from graphify.detect import save_manifest
|
||||
save_manifest(detected["files"])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection,
|
||||
{"input": 0, "output": 0}, report_root, suggested_questions=questions)
|
||||
{"input": 0, "output": 0}, report_root, suggested_questions=questions,
|
||||
built_at_commit=commit)
|
||||
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
|
||||
to_json(G, communities, str(out / "graph.json"))
|
||||
|
||||
# to_html raises ValueError for graphs > MAX_NODES_FOR_VIZ (5000).
|
||||
# Wrap so core outputs (graph.json + GRAPH_REPORT.md) always land.
|
||||
@@ -140,7 +190,7 @@ def check_update(watch_path: Path) -> bool:
|
||||
re-extraction via `/graphify --update` — this function only signals
|
||||
that the update is needed.
|
||||
"""
|
||||
flag = Path(watch_path) / "graphify-out" / "needs_update"
|
||||
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.")
|
||||
@@ -149,7 +199,7 @@ def check_update(watch_path: Path) -> bool:
|
||||
|
||||
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", encoding="utf-8")
|
||||
print(f"\n[graphify watch] New or changed files detected in {watch_path}")
|
||||
@@ -194,7 +244,7 @@ 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
|
||||
@@ -219,10 +269,12 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
|
||||
batch = list(changed)
|
||||
changed.clear()
|
||||
print(f"\n[graphify watch] {len(batch)} file(s) changed")
|
||||
if _has_non_code(batch):
|
||||
_notify_only(watch_path)
|
||||
else:
|
||||
has_non_code = _has_non_code(batch)
|
||||
has_code = any(p.suffix.lower() in _CODE_EXTENSIONS for p in batch)
|
||||
if has_code:
|
||||
_rebuild_code(watch_path)
|
||||
if has_non_code:
|
||||
_notify_only(watch_path)
|
||||
except KeyboardInterrupt:
|
||||
print("\n[graphify watch] Stopped.")
|
||||
finally:
|
||||
|
||||
+27
-1
@@ -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]]:
|
||||
@@ -185,6 +196,21 @@ def to_wiki(
|
||||
out = Path(output_dir)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if not communities:
|
||||
raise ValueError(
|
||||
"communities dict is empty — refusing to clear wiki/. "
|
||||
"Run `graphify extract .` or `graphify cluster-only .` first."
|
||||
)
|
||||
|
||||
# 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 []
|
||||
|
||||
+22
-10
@@ -4,14 +4,16 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "graphifyy"
|
||||
version = "0.4.31"
|
||||
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
|
||||
version = "0.7.8"
|
||||
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", "gemini", "aider", "kiro", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
|
||||
requires-python = ">=3.10,<3.14"
|
||||
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",
|
||||
"datasketch",
|
||||
"rapidfuzz",
|
||||
"tree-sitter>=0.23.0",
|
||||
"tree-sitter-python",
|
||||
"tree-sitter-javascript",
|
||||
@@ -19,6 +21,7 @@ dependencies = [
|
||||
"tree-sitter-go",
|
||||
"tree-sitter-rust",
|
||||
"tree-sitter-java",
|
||||
"tree-sitter-groovy",
|
||||
"tree-sitter-c",
|
||||
"tree-sitter-cpp",
|
||||
"tree-sitter-ruby",
|
||||
@@ -34,6 +37,7 @@ dependencies = [
|
||||
"tree-sitter-objc",
|
||||
"tree-sitter-julia",
|
||||
"tree-sitter-verilog",
|
||||
"tree-sitter-fortran",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
@@ -44,13 +48,18 @@ Issues = "https://github.com/safishamsi/graphify/issues"
|
||||
[project.optional-dependencies]
|
||||
mcp = ["mcp"]
|
||||
neo4j = ["neo4j"]
|
||||
pdf = ["pypdf", "html2text"]
|
||||
pdf = ["pypdf", "markdownify"]
|
||||
watch = ["watchdog"]
|
||||
svg = ["matplotlib"]
|
||||
leiden = ["graspologic; python_version < '3.13'"]
|
||||
office = ["python-docx", "openpyxl"]
|
||||
video = ["faster-whisper", "yt-dlp"]
|
||||
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper", "yt-dlp", "matplotlib"]
|
||||
kimi = ["openai", "tiktoken"]
|
||||
ollama = ["openai"]
|
||||
gemini = ["openai", "tiktoken"]
|
||||
openai = ["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"
|
||||
@@ -60,9 +69,12 @@ graphify = "graphify.__main__:main"
|
||||
# Run without installing: uvx graphifyy install
|
||||
package = true
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["."]
|
||||
include = ["graphify*"]
|
||||
[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", "skill-kiro.md", "skill-vscode.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"]
|
||||
|
||||
[tool.bandit]
|
||||
skips = ["B404"]
|
||||
@@ -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
+33
@@ -0,0 +1,33 @@
|
||||
# Deploy Guide
|
||||
|
||||
How to deploy the QuranicWords backend.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Docker installed
|
||||
- SSH access to VPS
|
||||
|
||||
## Full Deploy
|
||||
|
||||
Run this one-liner on your VPS:
|
||||
|
||||
```bash
|
||||
cd /opt/QuranicWords && git pull origin main && docker compose build --no-cache api
|
||||
```
|
||||
|
||||
### Database Migration
|
||||
|
||||
If you changed the Prisma schema:
|
||||
|
||||
```sql
|
||||
ALTER TABLE users ADD COLUMN points INT DEFAULT 0;
|
||||
```
|
||||
|
||||
## Rollback
|
||||
|
||||
Use `git revert` to undo bad deploys.
|
||||
|
||||
```python
|
||||
def rollback(version):
|
||||
subprocess.run(["git", "checkout", version])
|
||||
```
|
||||
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
+17
@@ -0,0 +1,17 @@
|
||||
#define NDIM 3
|
||||
|
||||
module shapes
|
||||
#ifdef MPI
|
||||
use mpi
|
||||
#endif
|
||||
implicit none
|
||||
|
||||
contains
|
||||
|
||||
subroutine compute_volume(side, vol)
|
||||
real, intent(in) :: side
|
||||
real, intent(out) :: vol
|
||||
vol = side ** NDIM
|
||||
end subroutine compute_volume
|
||||
|
||||
end module shapes
|
||||
Vendored
+39
@@ -0,0 +1,39 @@
|
||||
module geometry
|
||||
use constants
|
||||
implicit none
|
||||
|
||||
real, parameter :: PI = 3.14159
|
||||
|
||||
contains
|
||||
|
||||
subroutine circle_area(radius, area)
|
||||
real, intent(in) :: radius
|
||||
real, intent(out) :: area
|
||||
area = PI * radius * radius
|
||||
end subroutine circle_area
|
||||
|
||||
function distance(x1, y1, x2, y2) result(d)
|
||||
real, intent(in) :: x1, y1, x2, y2
|
||||
real :: d
|
||||
d = sqrt((x2 - x1)**2 + (y2 - y1)**2)
|
||||
end function distance
|
||||
|
||||
subroutine print_area(radius)
|
||||
real, intent(in) :: radius
|
||||
real :: area
|
||||
call circle_area(radius, area)
|
||||
print *, "Area =", area
|
||||
end subroutine print_area
|
||||
|
||||
end module geometry
|
||||
|
||||
|
||||
program main
|
||||
use geometry
|
||||
implicit none
|
||||
|
||||
real :: r, a
|
||||
r = 5.0
|
||||
call circle_area(r, a)
|
||||
print *, "Circle area:", a
|
||||
end program main
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
package com.nicklastrange.example
|
||||
|
||||
import com.nicklastrange.Processor
|
||||
import com.nicklastrange.util.Helper
|
||||
|
||||
class SampleService {
|
||||
Processor processor
|
||||
|
||||
SampleService(Processor processor) {
|
||||
this.processor = processor
|
||||
}
|
||||
|
||||
String process(String input) {
|
||||
def result = processor.transform(input)
|
||||
return Helper.clean(result)
|
||||
}
|
||||
|
||||
private void reset() {
|
||||
processor.reset()
|
||||
}
|
||||
}
|
||||
Vendored
+35
@@ -0,0 +1,35 @@
|
||||
-- Luau sample (Roblox): typed Lua superset.
|
||||
-- tree-sitter-lua doesn't parse the type annotations, but extracts
|
||||
-- function declarations and call edges fine.
|
||||
|
||||
local Server = {}
|
||||
Server.__index = Server
|
||||
|
||||
type ServerConfig = {
|
||||
port: number,
|
||||
name: string?,
|
||||
}
|
||||
|
||||
function Server.new(config: ServerConfig): Server
|
||||
local self = setmetatable({}, Server)
|
||||
self.port = config.port
|
||||
self.name = config.name or "default"
|
||||
return self
|
||||
end
|
||||
|
||||
function Server:start(): ()
|
||||
print(string.format("listening on :%d", self.port))
|
||||
end
|
||||
|
||||
function Server:stop(): ()
|
||||
print("stopped")
|
||||
end
|
||||
|
||||
local function main()
|
||||
local s = Server.new({ port = 8080 })
|
||||
s:start()
|
||||
end
|
||||
|
||||
main()
|
||||
|
||||
return Server
|
||||
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
+42
@@ -0,0 +1,42 @@
|
||||
package com.nicklastrange.example
|
||||
|
||||
import spock.lang.Specification
|
||||
|
||||
class SampleSpec extends Specification {
|
||||
|
||||
def setup() {
|
||||
// common setup
|
||||
}
|
||||
|
||||
def "should process valid input"() {
|
||||
given:
|
||||
def input = "hello"
|
||||
|
||||
when:
|
||||
def result = input.toUpperCase()
|
||||
|
||||
then:
|
||||
result == "HELLO"
|
||||
}
|
||||
|
||||
def "should not change value when it's already correct"() {
|
||||
given:
|
||||
def value = "HELLO"
|
||||
|
||||
when:
|
||||
def result = value.toUpperCase()
|
||||
|
||||
then:
|
||||
result == value
|
||||
}
|
||||
|
||||
def "should handle #input and return #expected"() {
|
||||
expect:
|
||||
input.toUpperCase() == expected
|
||||
|
||||
where:
|
||||
input | expected
|
||||
"hello" | "HELLO"
|
||||
"world" | "WORLD"
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,21 @@ def test_legacy_edge_from_to_canonicalized():
|
||||
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}
|
||||
|
||||
+5
-3
@@ -67,11 +67,13 @@ def test_cached_files(tmp_path, cache_root):
|
||||
|
||||
|
||||
def test_clear_cache(tmp_file, cache_root):
|
||||
"""clear_cache removes all .json files from graphify-out/cache/."""
|
||||
"""clear_cache removes all .json files from graphify-out/cache/ (all subdirs)."""
|
||||
save_cached(tmp_file, {"nodes": [], "edges": []}, root=cache_root)
|
||||
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) > 0
|
||||
# Since v0.5.3 entries go into cache/ast/, not the flat cache/ dir
|
||||
cache_base = cache_root / "graphify-out" / "cache"
|
||||
assert len(list(cache_base.rglob("*.json"))) > 0
|
||||
clear_cache(cache_root)
|
||||
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) == 0
|
||||
assert len(list(cache_base.rglob("*.json"))) == 0
|
||||
|
||||
|
||||
def test_md_frontmatter_only_change_same_hash(tmp_path):
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Integration tests for graphify export subcommands and CLI commands.
|
||||
|
||||
Each test builds a minimal graph in a temp dir, runs the CLI command as a subprocess,
|
||||
and asserts the expected output file exists and is non-empty / valid.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
PYTHON = sys.executable
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
|
||||
def _run(args: list[str], cwd: Path) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
[PYTHON, "-m", "graphify"] + args,
|
||||
cwd=cwd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def _make_graph(tmp_path: Path) -> Path:
|
||||
"""Build a minimal graph.json + analysis/labels files in tmp_path/graphify-out/."""
|
||||
out = tmp_path / "graphify-out"
|
||||
out.mkdir()
|
||||
|
||||
extraction = json.loads((FIXTURES / "extraction.json").read_text())
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections
|
||||
from graphify.export import to_json
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = cluster(G)
|
||||
cohesion = score_all(G, communities)
|
||||
gods = god_nodes(G)
|
||||
surprises = surprising_connections(G, communities)
|
||||
labels = {cid: f"Community {cid}" for cid in communities}
|
||||
|
||||
to_json(G, communities, str(out / "graph.json"))
|
||||
|
||||
analysis = {
|
||||
"communities": {str(k): v for k, v in communities.items()},
|
||||
"cohesion": {str(k): v for k, v in cohesion.items()},
|
||||
"gods": gods,
|
||||
"surprises": surprises,
|
||||
}
|
||||
(out / ".graphify_analysis.json").write_text(json.dumps(analysis))
|
||||
(out / ".graphify_labels.json").write_text(
|
||||
json.dumps({str(k): v for k, v in labels.items()})
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
# ── graphify export html ─────────────────────────────────────────────────────
|
||||
|
||||
def test_export_html_creates_file(tmp_path):
|
||||
_make_graph(tmp_path)
|
||||
r = _run(["export", "html"], tmp_path)
|
||||
assert r.returncode == 0, r.stderr
|
||||
html = tmp_path / "graphify-out" / "graph.html"
|
||||
assert html.exists()
|
||||
assert html.stat().st_size > 0
|
||||
|
||||
|
||||
def test_export_html_no_viz_removes_file(tmp_path):
|
||||
out = _make_graph(tmp_path)
|
||||
(out / "graph.html").write_text("<html/>")
|
||||
r = _run(["export", "html", "--no-viz"], tmp_path)
|
||||
assert r.returncode == 0, r.stderr
|
||||
assert not (out / "graph.html").exists()
|
||||
|
||||
|
||||
def test_export_html_error_without_graph(tmp_path):
|
||||
r = _run(["export", "html"], tmp_path)
|
||||
assert r.returncode != 0
|
||||
|
||||
|
||||
# ── graphify export obsidian ─────────────────────────────────────────────────
|
||||
|
||||
def test_export_obsidian_creates_vault(tmp_path):
|
||||
_make_graph(tmp_path)
|
||||
r = _run(["export", "obsidian"], tmp_path)
|
||||
assert r.returncode == 0, r.stderr
|
||||
vault = tmp_path / "graphify-out" / "obsidian"
|
||||
assert vault.exists()
|
||||
md_files = list(vault.glob("*.md"))
|
||||
assert len(md_files) > 0
|
||||
|
||||
|
||||
def test_export_obsidian_custom_dir(tmp_path):
|
||||
_make_graph(tmp_path)
|
||||
custom = tmp_path / "my-vault"
|
||||
r = _run(["export", "obsidian", "--dir", str(custom)], tmp_path)
|
||||
assert r.returncode == 0, r.stderr
|
||||
assert custom.exists()
|
||||
assert len(list(custom.glob("*.md"))) > 0
|
||||
|
||||
|
||||
# ── graphify export wiki ─────────────────────────────────────────────────────
|
||||
|
||||
def test_export_wiki_creates_articles(tmp_path):
|
||||
_make_graph(tmp_path)
|
||||
r = _run(["export", "wiki"], tmp_path)
|
||||
assert r.returncode == 0, r.stderr
|
||||
wiki = tmp_path / "graphify-out" / "wiki"
|
||||
assert wiki.exists()
|
||||
assert (wiki / "index.md").exists()
|
||||
|
||||
|
||||
# ── graphify export graphml ──────────────────────────────────────────────────
|
||||
|
||||
def test_export_graphml_creates_file(tmp_path):
|
||||
_make_graph(tmp_path)
|
||||
r = _run(["export", "graphml"], tmp_path)
|
||||
assert r.returncode == 0, r.stderr
|
||||
gml = tmp_path / "graphify-out" / "graph.graphml"
|
||||
assert gml.exists()
|
||||
assert gml.stat().st_size > 0
|
||||
content = gml.read_text()
|
||||
assert "<graphml" in content
|
||||
|
||||
|
||||
# ── graphify export neo4j (cypher) ───────────────────────────────────────────
|
||||
|
||||
def test_export_neo4j_creates_cypher(tmp_path):
|
||||
_make_graph(tmp_path)
|
||||
r = _run(["export", "neo4j"], tmp_path)
|
||||
assert r.returncode == 0, r.stderr
|
||||
cypher = tmp_path / "graphify-out" / "cypher.txt"
|
||||
assert cypher.exists()
|
||||
assert cypher.stat().st_size > 0
|
||||
content = cypher.read_text()
|
||||
assert "MERGE" in content or "CREATE" in content
|
||||
|
||||
|
||||
# ── graphify query ───────────────────────────────────────────────────────────
|
||||
|
||||
def test_query_returns_output(tmp_path):
|
||||
_make_graph(tmp_path)
|
||||
r = _run(["query", "test"], tmp_path)
|
||||
assert r.returncode == 0, r.stderr
|
||||
assert len(r.stdout) > 0
|
||||
|
||||
|
||||
def test_query_dfs_flag(tmp_path):
|
||||
_make_graph(tmp_path)
|
||||
r = _run(["query", "test", "--dfs"], tmp_path)
|
||||
assert r.returncode == 0, r.stderr
|
||||
|
||||
|
||||
def test_query_budget_flag(tmp_path):
|
||||
_make_graph(tmp_path)
|
||||
r = _run(["query", "test", "--budget", "500"], tmp_path)
|
||||
assert r.returncode == 0, r.stderr
|
||||
|
||||
|
||||
def test_query_missing_graph_fails(tmp_path):
|
||||
r = _run(["query", "anything"], tmp_path)
|
||||
assert r.returncode != 0
|
||||
|
||||
|
||||
# ── graphify path ────────────────────────────────────────────────────────────
|
||||
|
||||
def test_path_runs_without_error(tmp_path):
|
||||
_make_graph(tmp_path)
|
||||
r = _run(["path", "Transformer", "LayerNorm"], tmp_path)
|
||||
# May find or not find a path — either is valid, should not crash
|
||||
assert r.returncode == 0, r.stderr
|
||||
|
||||
|
||||
def test_path_missing_graph_fails(tmp_path):
|
||||
r = _run(["path", "a", "b"], tmp_path)
|
||||
assert r.returncode != 0
|
||||
|
||||
|
||||
# ── graphify explain ─────────────────────────────────────────────────────────
|
||||
|
||||
def test_explain_runs_without_error(tmp_path):
|
||||
_make_graph(tmp_path)
|
||||
r = _run(["explain", "test"], tmp_path)
|
||||
assert r.returncode == 0, r.stderr
|
||||
|
||||
|
||||
def test_explain_missing_graph_fails(tmp_path):
|
||||
r = _run(["explain", "anything"], tmp_path)
|
||||
assert r.returncode != 0
|
||||
|
||||
|
||||
# ── graphify export unknown format ───────────────────────────────────────────
|
||||
|
||||
def test_export_unknown_format_fails(tmp_path):
|
||||
r = _run(["export", "pdf"], tmp_path)
|
||||
assert r.returncode != 0
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Tests for graphify/dedup.py entity deduplication pipeline."""
|
||||
from __future__ import annotations
|
||||
import pytest
|
||||
from graphify.dedup import deduplicate_entities, _entropy, _shingles
|
||||
|
||||
|
||||
# ── entropy gate ─────────────────────────────────────────────────────────────
|
||||
|
||||
def test_entropy_short_label_low():
|
||||
assert _entropy("AI") < 2.5
|
||||
|
||||
def test_entropy_normal_label_high():
|
||||
assert _entropy("AuthenticationManager") >= 2.5
|
||||
|
||||
def test_entropy_empty_string():
|
||||
assert _entropy("") == 0.0
|
||||
|
||||
|
||||
# ── shingles ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_shingles_produces_trigrams():
|
||||
s = _shingles("hello")
|
||||
assert "hel" in s
|
||||
assert "ell" in s
|
||||
assert "llo" in s
|
||||
|
||||
def test_shingles_short_string():
|
||||
# strings shorter than 3 chars return single shingle of the string itself
|
||||
assert _shingles("ab") == {"ab"}
|
||||
|
||||
|
||||
# ── full pipeline ─────────────────────────────────────────────────────────────
|
||||
|
||||
def _make_nodes(*labels):
|
||||
return [{"id": label.lower().replace(" ", "_"), "label": label, "source_file": "test.md"} for label in labels]
|
||||
|
||||
def _make_edges(src, tgt, relation="relates_to"):
|
||||
return [{"source": src, "target": tgt, "relation": relation}]
|
||||
|
||||
|
||||
def test_exact_duplicates_merged():
|
||||
nodes = _make_nodes("UserService", "userservice", "User Service")
|
||||
edges = []
|
||||
result_nodes, result_edges = deduplicate_entities(nodes, edges, communities={})
|
||||
# All three are the same concept — only one survives
|
||||
assert len(result_nodes) == 1
|
||||
|
||||
|
||||
def test_typo_merged():
|
||||
# "GraphExtractor" vs "Graph Extractor" — Jaro-Winkler >= 0.92
|
||||
nodes = _make_nodes("GraphExtractor", "Graph Extractor")
|
||||
edges = []
|
||||
result_nodes, _ = deduplicate_entities(nodes, edges, communities={})
|
||||
assert len(result_nodes) == 1
|
||||
|
||||
|
||||
def test_unrelated_not_merged():
|
||||
nodes = _make_nodes("UserService", "OrderService")
|
||||
edges = []
|
||||
result_nodes, _ = deduplicate_entities(nodes, edges, communities={})
|
||||
assert len(result_nodes) == 2
|
||||
|
||||
|
||||
def test_short_low_entropy_not_merged():
|
||||
# "AI" and "ML" are low-entropy — entropy gate skips them
|
||||
nodes = _make_nodes("AI", "ML")
|
||||
edges = []
|
||||
result_nodes, _ = deduplicate_entities(nodes, edges, communities={})
|
||||
assert len(result_nodes) == 2
|
||||
|
||||
|
||||
def test_edges_rewired_after_merge():
|
||||
nodes = _make_nodes("GraphExtractor", "Graph Extractor", "Parser")
|
||||
# edge from loser to Parser should be rewired to winner
|
||||
edges = [{"source": "graph_extractor", "target": "parser", "relation": "uses"}]
|
||||
result_nodes, result_edges = deduplicate_entities(nodes, edges, communities={})
|
||||
assert len(result_nodes) == 2 # merged + Parser
|
||||
# edge should still exist (rewired to winner)
|
||||
assert len(result_edges) == 1
|
||||
|
||||
|
||||
def test_self_loops_dropped_after_merge():
|
||||
# If both endpoints of an edge get merged into same node, drop the edge
|
||||
nodes = _make_nodes("GraphExtractor", "Graph Extractor")
|
||||
edges = [{"source": "graphextractor", "target": "graph_extractor", "relation": "same"}]
|
||||
_, result_edges = deduplicate_entities(nodes, edges, communities={})
|
||||
assert result_edges == []
|
||||
|
||||
|
||||
def test_community_boost_aids_merge():
|
||||
# Two nodes in same community with score in 0.75-0.85 zone get boosted
|
||||
nodes = _make_nodes("AuthManager", "Auth Manager")
|
||||
edges = []
|
||||
# Same community → boost → merge
|
||||
communities = {"authmanager": 1, "auth_manager": 1}
|
||||
result_with, _ = deduplicate_entities(nodes, edges, communities=communities)
|
||||
# Different community → no boost
|
||||
communities_diff = {"authmanager": 1, "auth_manager": 2}
|
||||
result_without, _ = deduplicate_entities(nodes, edges, communities=communities_diff)
|
||||
assert len(result_with) <= len(result_without)
|
||||
|
||||
|
||||
def test_empty_inputs():
|
||||
result_nodes, result_edges = deduplicate_entities([], [], communities={})
|
||||
assert result_nodes == []
|
||||
assert result_edges == []
|
||||
|
||||
|
||||
def test_single_node_no_crash():
|
||||
nodes = _make_nodes("UserService")
|
||||
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
|
||||
assert len(result_nodes) == 1
|
||||
|
||||
|
||||
def test_dedup_llm_flag_accepted():
|
||||
"""deduplicate_entities accepts dedup_llm_backend without crashing when no ambiguous pairs exist."""
|
||||
nodes = _make_nodes("UserService", "OrderService")
|
||||
edges = []
|
||||
result_nodes, _ = deduplicate_entities(nodes, edges, communities={}, dedup_llm_backend=None)
|
||||
assert len(result_nodes) == 2
|
||||
|
||||
|
||||
# ── build integration ─────────────────────────────────────────────────────────
|
||||
|
||||
def test_build_calls_dedup():
|
||||
"""build() should deduplicate near-identical nodes across extractions."""
|
||||
from graphify.build import build
|
||||
chunk1 = {
|
||||
"nodes": [{"id": "graphextractor", "label": "GraphExtractor", "source_file": "a.py"}],
|
||||
"edges": [],
|
||||
}
|
||||
chunk2 = {
|
||||
"nodes": [{"id": "graph_extractor", "label": "Graph Extractor", "source_file": "b.py"}],
|
||||
"edges": [],
|
||||
}
|
||||
G = build([chunk1, chunk2])
|
||||
assert G.number_of_nodes() == 1
|
||||
+49
-3
@@ -1,5 +1,5 @@
|
||||
from pathlib import Path
|
||||
from graphify.detect import classify_file, count_words, detect, FileType, _looks_like_paper, _is_ignored, _load_graphifyignore
|
||||
from graphify.detect import classify_file, count_words, detect, detect_incremental, save_manifest, FileType, _looks_like_paper, _is_ignored, _load_graphifyignore
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
@@ -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)
|
||||
@@ -201,6 +220,33 @@ def test_detect_handles_circular_symlinks(tmp_path):
|
||||
assert any("main.py" in f for f in result["files"]["code"])
|
||||
|
||||
|
||||
def test_detect_incremental_propagates_follow_symlinks(tmp_path, monkeypatch):
|
||||
"""detect_incremental must forward follow_symlinks so symlinked sub-trees
|
||||
appear in incremental scans the same way they appear in full scans."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
real_dir = tmp_path / "real_corpus"
|
||||
real_dir.mkdir()
|
||||
(real_dir / "note.md").write_text("# real note\n\nsome content")
|
||||
(tmp_path / "linked_corpus").symlink_to(real_dir)
|
||||
|
||||
manifest_path = str(tmp_path / "manifest.json")
|
||||
|
||||
# Without following symlinks, the symlinked dir contents are invisible.
|
||||
no_link = detect_incremental(tmp_path, manifest_path, follow_symlinks=False)
|
||||
assert not any("linked_corpus" in f for f in no_link["files"]["document"])
|
||||
|
||||
# With follow_symlinks=True, the symlinked dir contents appear and are new.
|
||||
yes_link = detect_incremental(tmp_path, manifest_path, follow_symlinks=True)
|
||||
assert any("linked_corpus" in f for f in yes_link["files"]["document"])
|
||||
assert yes_link["new_total"] >= 2 # real + linked
|
||||
|
||||
# After saving manifest, a second incremental scan should see no changes.
|
||||
save_manifest(yes_link["files"], manifest_path)
|
||||
second = detect_incremental(tmp_path, manifest_path, follow_symlinks=True)
|
||||
assert second["new_total"] == 0
|
||||
|
||||
|
||||
def test_classify_video_extensions():
|
||||
"""Video and audio file extensions should classify as VIDEO."""
|
||||
from graphify.detect import FileType
|
||||
|
||||
+31
-5
@@ -57,12 +57,9 @@ def test_extract_merges_multiple_files():
|
||||
|
||||
|
||||
def test_collect_files_from_dir():
|
||||
from graphify.extract import _DISPATCH
|
||||
files = collect_files(FIXTURES)
|
||||
supported = {".py", ".js", ".ts", ".tsx", ".go", ".rs",
|
||||
".java", ".c", ".cpp", ".cc", ".cxx", ".rb",
|
||||
".cs", ".kt", ".kts", ".scala", ".php", ".h", ".hpp",
|
||||
".swift", ".lua", ".toc", ".zig", ".ps1", ".ex", ".exs",
|
||||
".m", ".mm"}
|
||||
supported = set(_DISPATCH.keys())
|
||||
assert all(f.suffix in supported for f in files)
|
||||
assert len(files) > 0
|
||||
|
||||
@@ -124,6 +121,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 +172,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
|
||||
)
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Tests for the global graph infrastructure (graphify/global_graph.py),
|
||||
prefix/prune helpers in graphify/build.py, and the cross-repo guard in
|
||||
graphify/dedup.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pytest
|
||||
import networkx as nx
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
# ── helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def _make_graph(nodes, edges=None):
|
||||
"""Build a simple nx.Graph from node dicts."""
|
||||
G = nx.Graph()
|
||||
for n in nodes:
|
||||
nid = n["id"]
|
||||
G.add_node(nid, **{k: v for k, v in n.items() if k != "id"})
|
||||
for e in (edges or []):
|
||||
G.add_edge(
|
||||
e["source"],
|
||||
e["target"],
|
||||
**{k: v for k, v in e.items() if k not in ("source", "target")},
|
||||
)
|
||||
return G
|
||||
|
||||
|
||||
def _graph_to_json(G, path):
|
||||
from networkx.readwrite import json_graph as jg
|
||||
try:
|
||||
data = jg.node_link_data(G, edges="links")
|
||||
except TypeError:
|
||||
data = jg.node_link_data(G)
|
||||
path.write_text(json.dumps(data), encoding="utf-8")
|
||||
|
||||
|
||||
# ── build.py helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
def test_prefix_graph_preserves_label():
|
||||
from graphify.build import prefix_graph_for_global
|
||||
G = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
|
||||
H = prefix_graph_for_global(G, "repoA")
|
||||
assert "repoA::userservice" in H.nodes
|
||||
assert "userservice" not in H.nodes
|
||||
assert H.nodes["repoA::userservice"]["label"] == "UserService"
|
||||
|
||||
|
||||
def test_prefix_graph_sets_repo_and_local_id():
|
||||
from graphify.build import prefix_graph_for_global
|
||||
G = _make_graph([{"id": "userservice", "label": "UserService"}])
|
||||
H = prefix_graph_for_global(G, "repoA")
|
||||
data = H.nodes["repoA::userservice"]
|
||||
assert data["repo"] == "repoA"
|
||||
assert data["local_id"] == "userservice"
|
||||
|
||||
|
||||
def test_prefix_graph_rewrites_edges():
|
||||
from graphify.build import prefix_graph_for_global
|
||||
G = _make_graph(
|
||||
[{"id": "a", "label": "A"}, {"id": "b", "label": "B"}],
|
||||
[{"source": "a", "target": "b"}],
|
||||
)
|
||||
H = prefix_graph_for_global(G, "repo1")
|
||||
assert H.has_edge("repo1::a", "repo1::b")
|
||||
assert not H.has_edge("a", "b")
|
||||
|
||||
|
||||
def test_prune_repo_removes_correct_nodes():
|
||||
from graphify.build import prune_repo_from_graph
|
||||
G = nx.Graph()
|
||||
G.add_node("repoA::userservice", repo="repoA", label="UserService")
|
||||
G.add_node("repoB::userservice", repo="repoB", label="UserService")
|
||||
G.add_node("repoA::auth", repo="repoA", label="Auth")
|
||||
removed = prune_repo_from_graph(G, "repoA")
|
||||
assert removed == 2
|
||||
assert "repoB::userservice" in G.nodes
|
||||
assert "repoA::userservice" not in G.nodes
|
||||
assert "repoA::auth" not in G.nodes
|
||||
|
||||
|
||||
def test_prune_repo_returns_zero_if_not_present():
|
||||
from graphify.build import prune_repo_from_graph
|
||||
G = nx.Graph()
|
||||
G.add_node("repoA::x", repo="repoA")
|
||||
removed = prune_repo_from_graph(G, "repoB")
|
||||
assert removed == 0
|
||||
assert G.number_of_nodes() == 1
|
||||
|
||||
|
||||
# ── global_graph.py ───────────────────────────────────────────────────────────
|
||||
|
||||
def test_global_add_creates_global_graph(tmp_path):
|
||||
src_graph = tmp_path / "graph.json"
|
||||
G = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
|
||||
_graph_to_json(G, src_graph)
|
||||
|
||||
global_dir = tmp_path / ".graphify"
|
||||
with patch("graphify.global_graph._GLOBAL_DIR", global_dir), \
|
||||
patch("graphify.global_graph._GLOBAL_GRAPH", global_dir / "global-graph.json"), \
|
||||
patch("graphify.global_graph._GLOBAL_MANIFEST", global_dir / "global-manifest.json"):
|
||||
from graphify.global_graph import global_add
|
||||
result = global_add(src_graph, "repoA")
|
||||
|
||||
assert result["skipped"] is False
|
||||
assert result["nodes_added"] > 0
|
||||
manifest_path = global_dir / "global-manifest.json"
|
||||
assert manifest_path.exists()
|
||||
manifest = json.loads(manifest_path.read_text())
|
||||
assert "repoA" in manifest["repos"]
|
||||
|
||||
|
||||
def test_global_add_skip_on_unchanged_hash(tmp_path):
|
||||
src_graph = tmp_path / "graph.json"
|
||||
G = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
|
||||
_graph_to_json(G, src_graph)
|
||||
|
||||
global_dir = tmp_path / ".graphify"
|
||||
with patch("graphify.global_graph._GLOBAL_DIR", global_dir), \
|
||||
patch("graphify.global_graph._GLOBAL_GRAPH", global_dir / "global-graph.json"), \
|
||||
patch("graphify.global_graph._GLOBAL_MANIFEST", global_dir / "global-manifest.json"):
|
||||
from graphify.global_graph import global_add
|
||||
global_add(src_graph, "repoA")
|
||||
result2 = global_add(src_graph, "repoA")
|
||||
|
||||
assert result2["skipped"] is True
|
||||
|
||||
|
||||
def test_global_add_two_repos_no_collision(tmp_path):
|
||||
g1 = tmp_path / "graph1.json"
|
||||
g2 = tmp_path / "graph2.json"
|
||||
G1 = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
|
||||
G2 = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
|
||||
_graph_to_json(G1, g1)
|
||||
_graph_to_json(G2, g2)
|
||||
|
||||
global_dir = tmp_path / ".graphify"
|
||||
global_graph_path = global_dir / "global-graph.json"
|
||||
global_manifest_path = global_dir / "global-manifest.json"
|
||||
with patch("graphify.global_graph._GLOBAL_DIR", global_dir), \
|
||||
patch("graphify.global_graph._GLOBAL_GRAPH", global_graph_path), \
|
||||
patch("graphify.global_graph._GLOBAL_MANIFEST", global_manifest_path):
|
||||
from graphify.global_graph import global_add, _load_global_graph
|
||||
global_add(g1, "repoA")
|
||||
global_add(g2, "repoB")
|
||||
G = _load_global_graph()
|
||||
|
||||
assert "repoA::userservice" in G.nodes
|
||||
assert "repoB::userservice" in G.nodes
|
||||
assert G.number_of_nodes() == 2 # no silent merge
|
||||
|
||||
|
||||
def test_global_remove(tmp_path):
|
||||
src_graph = tmp_path / "graph.json"
|
||||
G = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
|
||||
_graph_to_json(G, src_graph)
|
||||
|
||||
global_dir = tmp_path / ".graphify"
|
||||
with patch("graphify.global_graph._GLOBAL_DIR", global_dir), \
|
||||
patch("graphify.global_graph._GLOBAL_GRAPH", global_dir / "global-graph.json"), \
|
||||
patch("graphify.global_graph._GLOBAL_MANIFEST", global_dir / "global-manifest.json"):
|
||||
from graphify.global_graph import global_add, global_remove
|
||||
global_add(src_graph, "repoA")
|
||||
removed = global_remove("repoA")
|
||||
|
||||
assert removed > 0
|
||||
# manifest should no longer list repoA - need to re-patch for list call
|
||||
global_dir2 = global_dir # same dir
|
||||
with patch("graphify.global_graph._GLOBAL_DIR", global_dir2), \
|
||||
patch("graphify.global_graph._GLOBAL_GRAPH", global_dir2 / "global-graph.json"), \
|
||||
patch("graphify.global_graph._GLOBAL_MANIFEST", global_dir2 / "global-manifest.json"):
|
||||
from graphify.global_graph import global_list
|
||||
repos = global_list()
|
||||
assert "repoA" not in repos
|
||||
|
||||
|
||||
def test_global_remove_unknown_tag_raises(tmp_path):
|
||||
global_dir = tmp_path / ".graphify"
|
||||
with patch("graphify.global_graph._GLOBAL_DIR", global_dir), \
|
||||
patch("graphify.global_graph._GLOBAL_GRAPH", global_dir / "global-graph.json"), \
|
||||
patch("graphify.global_graph._GLOBAL_MANIFEST", global_dir / "global-manifest.json"):
|
||||
from graphify.global_graph import global_remove
|
||||
with pytest.raises(KeyError):
|
||||
global_remove("nonexistent")
|
||||
|
||||
|
||||
def test_global_add_collision_warning(tmp_path, capsys):
|
||||
g1 = tmp_path / "graph1.json"
|
||||
g2 = tmp_path / "graph2.json"
|
||||
G = _make_graph([{"id": "x", "label": "X", "source_file": "x.py"}])
|
||||
_graph_to_json(G, g1)
|
||||
_graph_to_json(G, g2)
|
||||
|
||||
global_dir = tmp_path / ".graphify"
|
||||
with patch("graphify.global_graph._GLOBAL_DIR", global_dir), \
|
||||
patch("graphify.global_graph._GLOBAL_GRAPH", global_dir / "global-graph.json"), \
|
||||
patch("graphify.global_graph._GLOBAL_MANIFEST", global_dir / "global-manifest.json"):
|
||||
from graphify.global_graph import global_add
|
||||
global_add(g1, "myrepo")
|
||||
global_add(g2, "myrepo") # different source path, same tag
|
||||
|
||||
captured = capsys.readouterr()
|
||||
assert "warning" in captured.err.lower() or "warning" in captured.out.lower()
|
||||
|
||||
|
||||
# ── dedup guard ───────────────────────────────────────────────────────────────
|
||||
|
||||
def test_dedup_raises_on_cross_repo_nodes():
|
||||
from graphify.dedup import deduplicate_entities
|
||||
nodes = [
|
||||
{"id": "repoA::userservice", "label": "UserService", "repo": "repoA"},
|
||||
{"id": "repoB::userservice", "label": "UserService", "repo": "repoB"},
|
||||
]
|
||||
with pytest.raises(ValueError, match="multiple repos"):
|
||||
deduplicate_entities(nodes, [], communities={})
|
||||
|
||||
|
||||
def test_dedup_ok_with_single_repo():
|
||||
from graphify.dedup import deduplicate_entities
|
||||
nodes = [
|
||||
{"id": "repoA::userservice", "label": "UserService", "repo": "repoA"},
|
||||
{"id": "repoA::auth", "label": "Auth", "repo": "repoA"},
|
||||
]
|
||||
result_nodes, result_edges = deduplicate_entities(nodes, [], communities={})
|
||||
assert len(result_nodes) == 2 # no false merge
|
||||
|
||||
|
||||
def test_dedup_ok_with_no_repo_attr():
|
||||
from graphify.dedup import deduplicate_entities
|
||||
nodes = [
|
||||
{"id": "userservice", "label": "UserService"},
|
||||
{"id": "auth", "label": "Auth"},
|
||||
]
|
||||
result_nodes, result_edges = deduplicate_entities(nodes, [], communities={})
|
||||
assert len(result_nodes) == 2
|
||||
|
||||
|
||||
# ── merge-graphs prefix ───────────────────────────────────────────────────────
|
||||
|
||||
def test_merge_graphs_prefixes_ids(tmp_path):
|
||||
"""merge-graphs should prefix node IDs with repo name to avoid silent collision."""
|
||||
from graphify.build import prefix_graph_for_global
|
||||
from networkx.readwrite import json_graph as jg
|
||||
|
||||
# Two graphs with same node ID
|
||||
G1 = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
|
||||
G2 = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
|
||||
|
||||
repo1 = tmp_path / "repo1" / "graphify-out"
|
||||
repo2 = tmp_path / "repo2" / "graphify-out"
|
||||
repo1.mkdir(parents=True)
|
||||
repo2.mkdir(parents=True)
|
||||
|
||||
g1_path = repo1 / "graph.json"
|
||||
g2_path = repo2 / "graph.json"
|
||||
_graph_to_json(G1, g1_path)
|
||||
_graph_to_json(G2, g2_path)
|
||||
|
||||
# Simulate what merge-graphs now does (prefix before compose)
|
||||
graphs = []
|
||||
graph_paths = [g1_path, g2_path]
|
||||
for gp in graph_paths:
|
||||
data = json.loads(gp.read_text())
|
||||
if "links" not in data and "edges" in data:
|
||||
data = dict(data, links=data["edges"])
|
||||
try:
|
||||
G = jg.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
G = jg.node_link_graph(data)
|
||||
repo_tag = gp.parent.parent.name
|
||||
graphs.append(prefix_graph_for_global(G, repo_tag))
|
||||
|
||||
merged = nx.Graph()
|
||||
for G in graphs:
|
||||
merged = nx.compose(merged, G)
|
||||
|
||||
assert "repo1::userservice" in merged.nodes
|
||||
assert "repo2::userservice" in merged.nodes
|
||||
assert merged.number_of_nodes() == 2 # no silent collapse
|
||||
@@ -123,3 +123,22 @@ 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 == ""
|
||||
@@ -0,0 +1,529 @@
|
||||
"""Tests for #716 — TypeScript bare-path imports, Svelte 5 rune file imports
|
||||
(`from './foo.svelte'` for a `.svelte.ts` file), and directory/index.ts
|
||||
imports must resolve to the actual file's node id, not a phantom.
|
||||
|
||||
Before #716, `_import_js` only rewrote `.js → .ts` and `.jsx → .tsx`. Every
|
||||
other shape (bare path, `.svelte → .svelte.ts`, `./foo` directory imports)
|
||||
produced an id like `..._foo` while the real file's node id was `..._foo_ts`,
|
||||
so `build_from_json` dropped the edge as external.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.extract import (
|
||||
_make_id,
|
||||
_resolve_js_module_path,
|
||||
extract_js,
|
||||
extract_svelte,
|
||||
)
|
||||
|
||||
|
||||
def _write(path: Path, body: str) -> Path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(body, encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def _import_targets(result: dict) -> set[str]:
|
||||
return {str(e.get("target") or "") for e in result["edges"]
|
||||
if e.get("relation") in ("imports", "imports_from")}
|
||||
|
||||
|
||||
# ── _resolve_js_module_path unit tests ──────────────────────────────────────
|
||||
|
||||
|
||||
def test_resolve_returns_existing_path_unchanged(tmp_path):
|
||||
p = _write(tmp_path / "foo.ts", "export const x = 1")
|
||||
assert _resolve_js_module_path(p) == p
|
||||
|
||||
|
||||
def test_resolve_bare_path_to_ts(tmp_path):
|
||||
target = _write(tmp_path / "foo.ts", "export const x = 1")
|
||||
bare = tmp_path / "foo"
|
||||
assert _resolve_js_module_path(bare) == target
|
||||
|
||||
|
||||
def test_resolve_bare_path_to_tsx(tmp_path):
|
||||
target = _write(tmp_path / "Component.tsx", "export const x = 1")
|
||||
bare = tmp_path / "Component"
|
||||
assert _resolve_js_module_path(bare) == target
|
||||
|
||||
|
||||
def test_resolve_bare_path_to_svelte(tmp_path):
|
||||
target = _write(tmp_path / "Card.svelte", "<div></div>")
|
||||
bare = tmp_path / "Card"
|
||||
assert _resolve_js_module_path(bare) == target
|
||||
|
||||
|
||||
def test_resolve_prefers_ts_over_svelte_when_both_exist(tmp_path):
|
||||
"""Vite resolver order: .ts wins over .svelte for ambiguous bare paths."""
|
||||
ts_target = _write(tmp_path / "foo.ts", "export const x = 1")
|
||||
_write(tmp_path / "foo.svelte", "<div></div>")
|
||||
bare = tmp_path / "foo"
|
||||
assert _resolve_js_module_path(bare) == ts_target
|
||||
|
||||
|
||||
def test_resolve_file_wins_over_sibling_directory(tmp_path):
|
||||
"""Real-world repro: a project has both `auth.ts` (file) and `auth/`
|
||||
(directory of sub-modules) at the same path. Both TypeScript and Vite
|
||||
prefer the file match. If the resolver checks the directory first and
|
||||
falls back on a missing index, every `from './auth'` import silently
|
||||
drops because the directory has no index.{ts,…}."""
|
||||
file_target = _write(tmp_path / "auth.ts", "export const x = 1")
|
||||
sibling_dir = tmp_path / "auth"
|
||||
sibling_dir.mkdir()
|
||||
_write(sibling_dir / "helpers.ts", "export const y = 2")
|
||||
bare = tmp_path / "auth"
|
||||
assert _resolve_js_module_path(bare) == file_target
|
||||
|
||||
|
||||
def test_resolve_directory_to_index_ts(tmp_path):
|
||||
pkg = tmp_path / "queue"
|
||||
target = _write(pkg / "index.ts", "export const x = 1")
|
||||
assert _resolve_js_module_path(pkg) == target
|
||||
|
||||
|
||||
def test_resolve_directory_prefers_index_ts_over_index_js(tmp_path):
|
||||
pkg = tmp_path / "queue"
|
||||
target = _write(pkg / "index.ts", "export const x = 1")
|
||||
_write(pkg / "index.js", "module.exports = {}")
|
||||
assert _resolve_js_module_path(pkg) == target
|
||||
|
||||
|
||||
def test_resolve_svelte_to_svelte_ts_for_rune_files(tmp_path):
|
||||
"""Svelte 5: `from './foo.svelte'` may actually point at `foo.svelte.ts`
|
||||
(a rune-only TypeScript file with no .svelte file). The resolver must
|
||||
APPEND .ts to the full filename, not swap suffixes."""
|
||||
target = _write(tmp_path / "is-mobile.svelte.ts",
|
||||
"export const isMobile = () => true")
|
||||
written_as = tmp_path / "is-mobile.svelte"
|
||||
resolved = _resolve_js_module_path(written_as)
|
||||
assert resolved == target, (
|
||||
f"Expected resolution to is-mobile.svelte.ts; got {resolved}"
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_svelte_to_svelte_js_for_javascript_rune_files(tmp_path):
|
||||
"""JS variant of the rune file pattern: a `.svelte.js` file (used in
|
||||
JavaScript-only Svelte 5 projects, no TypeScript). `from './foo.svelte'`
|
||||
must resolve to `foo.svelte.js` when no `.ts` variant exists.
|
||||
|
||||
Same code path as the .svelte.ts case — the generalized resolver tries
|
||||
every extension in priority order, so JS-only and TS-only projects
|
||||
both work without special-casing."""
|
||||
target = _write(tmp_path / "store.svelte.js",
|
||||
"export const count = $state(0)")
|
||||
written_as = tmp_path / "store.svelte"
|
||||
resolved = _resolve_js_module_path(written_as)
|
||||
assert resolved == target
|
||||
|
||||
|
||||
def test_resolve_svelte_prefers_svelte_ts_over_svelte_js(tmp_path):
|
||||
"""When both `.svelte.ts` and `.svelte.js` exist (hybrid project mid-
|
||||
migration, or a build artifact alongside the source), `.ts` wins —
|
||||
matching the resolver's stated TypeScript-first priority order.
|
||||
|
||||
Note: Vite's default `resolve.extensions` puts `.js` before `.ts`, but
|
||||
in practice TypeScript codebases that emit `.svelte.js` build artifacts
|
||||
expect tooling to read the `.svelte.ts` source. graphify is a source-
|
||||
code tool, not a runtime resolver, so source-first ordering is correct
|
||||
for our use case."""
|
||||
ts_target = _write(tmp_path / "store.svelte.ts",
|
||||
"export const count = $state(0)")
|
||||
_write(tmp_path / "store.svelte.js",
|
||||
"export const count = 0 // build artifact")
|
||||
written_as = tmp_path / "store.svelte"
|
||||
resolved = _resolve_js_module_path(written_as)
|
||||
assert resolved == ts_target
|
||||
|
||||
|
||||
def test_resolve_real_svelte_file_wins_over_svelte_ts_sibling(tmp_path):
|
||||
"""If `foo.svelte` IS a real markup file, importing `./foo.svelte`
|
||||
must resolve to that — not get hijacked to a sibling `foo.svelte.ts`
|
||||
rune file. The existence-check short-circuits before any append."""
|
||||
real = _write(tmp_path / "Card.svelte", "<div>card markup</div>")
|
||||
_write(tmp_path / "Card.svelte.ts",
|
||||
"export const helpers = {} // rune sibling, not the import target")
|
||||
resolved = _resolve_js_module_path(real)
|
||||
assert resolved == real
|
||||
|
||||
|
||||
def test_resolve_js_to_ts_when_real_file_is_ts(tmp_path):
|
||||
"""TS ESM convention: imports written as .js but the actual file is .ts."""
|
||||
target = _write(tmp_path / "foo.ts", "export const x = 1")
|
||||
written_as = tmp_path / "foo.js"
|
||||
assert _resolve_js_module_path(written_as) == target
|
||||
|
||||
|
||||
def test_resolve_jsx_to_tsx_when_real_file_is_tsx(tmp_path):
|
||||
target = _write(tmp_path / "Component.tsx", "export const x = 1")
|
||||
written_as = tmp_path / "Component.jsx"
|
||||
assert _resolve_js_module_path(written_as) == target
|
||||
|
||||
|
||||
def test_resolve_returns_unchanged_when_nothing_matches(tmp_path):
|
||||
"""External / truly missing paths fall back to the input — preserves
|
||||
pre-#716 behavior of becoming an external phantom edge."""
|
||||
nothing = tmp_path / "does_not_exist"
|
||||
assert _resolve_js_module_path(nothing) == nothing
|
||||
|
||||
|
||||
def test_resolve_real_js_stays_js_when_ts_does_not_exist(tmp_path):
|
||||
"""If `.js` exists and `.ts` does not, keep the `.js` rewrite from
|
||||
triggering — return the existing file."""
|
||||
target = _write(tmp_path / "foo.js", "module.exports = 1")
|
||||
assert _resolve_js_module_path(target) == target
|
||||
|
||||
|
||||
# ── End-to-end: bare-path imports in pure TS files ───────────────────────────
|
||||
|
||||
|
||||
def test_bare_path_import_resolves_in_ts_file(tmp_path):
|
||||
"""The #716 reproducer: TS file imports a sibling without an extension."""
|
||||
target = _write(tmp_path / "type-helpers.ts",
|
||||
"export type GetNestedType<T> = T")
|
||||
importer = _write(tmp_path / "page.ts",
|
||||
"import type { GetNestedType } from './type-helpers'\n")
|
||||
result = extract_js(importer)
|
||||
expected = _make_id(str(target))
|
||||
assert expected in _import_targets(result), (
|
||||
f"Bare-path .ts import must resolve to target node id; "
|
||||
f"expected {expected}; got {_import_targets(result)}"
|
||||
)
|
||||
|
||||
|
||||
def test_directory_import_resolves_to_index_ts(tmp_path):
|
||||
"""`from './queue'` must resolve to `./queue/index.ts`."""
|
||||
target = _write(tmp_path / "queue" / "index.ts",
|
||||
"export const enqueue = () => {}")
|
||||
importer = _write(tmp_path / "page.ts",
|
||||
"import { enqueue } from './queue'\n")
|
||||
result = extract_js(importer)
|
||||
expected = _make_id(str(target))
|
||||
assert expected in _import_targets(result), (
|
||||
f"Directory import must resolve to ./queue/index.ts; "
|
||||
f"expected {expected}; got {_import_targets(result)}"
|
||||
)
|
||||
|
||||
|
||||
# ── End-to-end: .svelte → .svelte.ts (Svelte 5 rune files) ───────────────────
|
||||
|
||||
|
||||
def test_dot_svelte_import_resolves_to_dot_svelte_ts(tmp_path):
|
||||
"""Svelte 5 rune file: import written as .svelte, real file is .svelte.ts."""
|
||||
target = _write(tmp_path / "is-mobile.svelte.ts",
|
||||
"export const isMobile = () => true")
|
||||
importer = _write(tmp_path / "page.ts",
|
||||
"import { isMobile } from './is-mobile.svelte'\n")
|
||||
result = extract_js(importer)
|
||||
expected = _make_id(str(target))
|
||||
assert expected in _import_targets(result), (
|
||||
f".svelte → .svelte.ts resolution failed; "
|
||||
f"expected {expected}; got {_import_targets(result)}"
|
||||
)
|
||||
|
||||
|
||||
# ── Regression guards: existing behavior preserved ───────────────────────────
|
||||
|
||||
|
||||
def test_explicit_ts_import_still_works(tmp_path):
|
||||
"""The most common case — import with explicit .ts extension — must
|
||||
continue to work after the resolver change."""
|
||||
target = _write(tmp_path / "foo.ts", "export const x = 1")
|
||||
importer = _write(tmp_path / "page.ts",
|
||||
"import { x } from './foo.ts'\n")
|
||||
result = extract_js(importer)
|
||||
expected = _make_id(str(target))
|
||||
assert expected in _import_targets(result), (
|
||||
f"Explicit .ts imports must still resolve; "
|
||||
f"expected {expected}; got {_import_targets(result)}"
|
||||
)
|
||||
|
||||
|
||||
def test_explicit_svelte_import_still_works(tmp_path):
|
||||
"""Real .svelte file imports must still resolve when the .svelte file
|
||||
exists (i.e. don't accidentally redirect to a non-existent .svelte.ts)."""
|
||||
target = _write(tmp_path / "Card.svelte", "<div></div>")
|
||||
importer = _write(tmp_path / "page.ts",
|
||||
"import Card from './Card.svelte'\n")
|
||||
result = extract_js(importer)
|
||||
expected = _make_id(str(target))
|
||||
assert expected in _import_targets(result), (
|
||||
f"Existing .svelte imports must resolve to the .svelte node, "
|
||||
f"not get redirected; expected {expected}; "
|
||||
f"got {_import_targets(result)}"
|
||||
)
|
||||
|
||||
|
||||
def test_external_module_unchanged(tmp_path):
|
||||
"""Bare module specifiers (no leading dot, no alias match) must still
|
||||
fall through to the external/last-segment path — don't accidentally
|
||||
treat 'lodash' as a relative path."""
|
||||
importer = _write(tmp_path / "page.ts",
|
||||
"import _ from 'lodash-es'\n")
|
||||
result = extract_js(importer)
|
||||
targets = _import_targets(result)
|
||||
# The target should be the bare module name, not a resolved file path
|
||||
assert "lodash_es" in targets or any("lodash" in t for t in targets), (
|
||||
f"External module specifier should still produce an external "
|
||||
f"reference; got {targets}"
|
||||
)
|
||||
|
||||
|
||||
# ── End-to-end: alias-resolved imports go through the same resolver ─────────
|
||||
|
||||
|
||||
def test_alias_import_with_bare_path_resolves(tmp_path):
|
||||
"""`$lib/foo` (alias + bare path) — both layers must work together."""
|
||||
src = tmp_path / "src"
|
||||
target = _write(src / "lib" / "type-helpers.ts",
|
||||
"export type X = string")
|
||||
_write(tmp_path / "tsconfig.json",
|
||||
'{"compilerOptions":{"paths":{"$lib":["./src/lib"],'
|
||||
'"$lib/*":["./src/lib/*"]}}}')
|
||||
importer_dir = src / "routes"
|
||||
importer = _write(importer_dir / "page.ts",
|
||||
"import type { X } from '$lib/type-helpers'\n")
|
||||
result = extract_js(importer)
|
||||
expected = _make_id(str(target))
|
||||
assert expected in _import_targets(result), (
|
||||
f"Alias + bare-path resolution failed; "
|
||||
f"expected {expected}; got {_import_targets(result)}"
|
||||
)
|
||||
|
||||
|
||||
# ── Edge cases — exhaustiveness ──────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_type_only_import_with_bare_path_resolves(tmp_path):
|
||||
"""`import type { X } from './foo'` — type-only imports must go through
|
||||
the same resolution path as regular imports. Common in TS codebases
|
||||
that separate types into their own module."""
|
||||
target = _write(tmp_path / "type-helpers.ts",
|
||||
"export type GetNestedType<T> = T")
|
||||
importer = _write(tmp_path / "page.ts",
|
||||
"import type { GetNestedType } from './type-helpers'\n")
|
||||
result = extract_js(importer)
|
||||
expected = _make_id(str(target))
|
||||
assert expected in _import_targets(result), (
|
||||
f"Type-only import with bare path failed to resolve; "
|
||||
f"expected {expected}; got {_import_targets(result)}"
|
||||
)
|
||||
|
||||
|
||||
def test_named_imports_emit_symbol_edges_after_resolution(tmp_path):
|
||||
"""`import { foo, bar } from './module'` should emit per-symbol `imports`
|
||||
edges to `module.foo` and `module.bar`, not just the file-level
|
||||
`imports_from`. The symbol-edge target_stem comes from _file_stem(resolved),
|
||||
which depends on resolution succeeding first."""
|
||||
_write(tmp_path / "utils.ts", "export const foo = 1\nexport const bar = 2")
|
||||
importer = _write(tmp_path / "page.ts",
|
||||
"import { foo, bar } from './utils'\n")
|
||||
result = extract_js(importer)
|
||||
sym_edges = [e for e in result["edges"] if e.get("relation") == "imports"]
|
||||
targets = {str(e.get("target") or "") for e in sym_edges}
|
||||
# Target ids look like "<dir>_utils_foo" — substring-match the symbol names
|
||||
assert any("_foo" in t for t in targets), (
|
||||
f"Per-symbol `imports` edge for `foo` missing; got {targets}"
|
||||
)
|
||||
assert any("_bar" in t for t in targets), (
|
||||
f"Per-symbol `imports` edge for `bar` missing; got {targets}"
|
||||
)
|
||||
|
||||
|
||||
def test_alias_directory_import_resolves_to_index_ts(tmp_path):
|
||||
"""`from '$lib/queue'` where queue/ is a directory under src/lib/."""
|
||||
src = tmp_path / "src"
|
||||
target = _write(src / "lib" / "queue" / "index.ts",
|
||||
"export const enqueue = () => {}")
|
||||
_write(tmp_path / "tsconfig.json",
|
||||
'{"compilerOptions":{"paths":{"$lib":["./src/lib"],'
|
||||
'"$lib/*":["./src/lib/*"]}}}')
|
||||
importer = _write(src / "routes" / "page.ts",
|
||||
"import { enqueue } from '$lib/queue'\n")
|
||||
result = extract_js(importer)
|
||||
expected = _make_id(str(target))
|
||||
assert expected in _import_targets(result), (
|
||||
f"Alias + directory resolution failed; "
|
||||
f"expected {expected}; got {_import_targets(result)}"
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_does_not_match_partial_directory_name(tmp_path):
|
||||
"""Regression guard: `from './foo'` where './foo' doesn't exist but
|
||||
'./foo-extra.ts' does must NOT accidentally resolve to the latter.
|
||||
`.with_suffix(".ts")` on 'foo' produces 'foo.ts' — not 'foo-extra.ts',
|
||||
but worth pinning down."""
|
||||
_write(tmp_path / "foo-extra.ts", "export const x = 1")
|
||||
bare = tmp_path / "foo"
|
||||
resolved = _resolve_js_module_path(bare)
|
||||
# Not a real file → nothing matches → returns input unchanged
|
||||
assert resolved == bare, (
|
||||
f"Partial-name match must not happen; got {resolved}"
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_directory_without_index_returns_unchanged(tmp_path):
|
||||
"""A directory with no index file should fall through to the
|
||||
\"return as-is\" path, not pick a non-index file from inside."""
|
||||
pkg = tmp_path / "pkg"
|
||||
_write(pkg / "not-index.ts", "export const x = 1")
|
||||
resolved = _resolve_js_module_path(pkg)
|
||||
assert resolved == pkg, (
|
||||
f"Directory without index.* must return unchanged; got {resolved}"
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_handles_subpath_into_directory_with_index(tmp_path):
|
||||
"""`./foo/sub` where ./foo/sub/index.ts exists — nested subpath.
|
||||
Common pattern for sub-modules inside a package."""
|
||||
target = _write(tmp_path / "foo" / "sub" / "index.ts",
|
||||
"export const x = 1")
|
||||
sub = tmp_path / "foo" / "sub"
|
||||
assert _resolve_js_module_path(sub) == target
|
||||
|
||||
|
||||
def test_resolve_does_not_treat_dotfile_as_extension(tmp_path):
|
||||
"""Edge case: `.eslintrc` and similar dotfiles. Path('.eslintrc').suffix
|
||||
returns '' on Python 3.x for files starting with `.`. Make sure we
|
||||
don't accidentally treat a real file as bare and try to append .ts."""
|
||||
target = _write(tmp_path / ".env-types.ts",
|
||||
"export const x = 1")
|
||||
# Path('.env-types.ts').suffix is '.ts' — not a problem
|
||||
assert _resolve_js_module_path(target) == target
|
||||
|
||||
|
||||
def test_resolve_multi_dot_helper_file(tmp_path):
|
||||
"""Common patterns: foo.shared.ts, foo.config.ts, foo.compile.ts,
|
||||
foo.integration.ts, foo.triggers.ts. Imports written as
|
||||
`from './foo.shared'` (preserving the meaningful suffix) must resolve
|
||||
to foo.shared.ts.
|
||||
|
||||
Before this rule, .suffix was '.shared' so neither the bare-path branch
|
||||
nor the .js/.jsx branches matched, and the import dropped to a phantom."""
|
||||
target = _write(tmp_path / "tag-action.shared.ts",
|
||||
"export const apply = () => {}")
|
||||
written_as = tmp_path / "tag-action.shared"
|
||||
assert _resolve_js_module_path(written_as) == target
|
||||
|
||||
|
||||
def test_resolve_multi_dot_with_explicit_extension_still_works(tmp_path):
|
||||
"""Sanity: `from './foo.shared.ts'` (explicit) still wins over implicit."""
|
||||
target = _write(tmp_path / "foo.shared.ts", "export const x = 1")
|
||||
assert _resolve_js_module_path(target) == target
|
||||
|
||||
|
||||
def test_resolve_ambient_d_ts_via_bare_path(tmp_path):
|
||||
"""Ambient TS declaration files (foo.d.ts) — bare import `./foo.d`
|
||||
should resolve to `./foo.d.ts` because `name + '.ts'` gives `foo.d.ts`."""
|
||||
target = _write(tmp_path / "ambient.d.ts", "declare const X: string")
|
||||
written_as = tmp_path / "ambient.d"
|
||||
assert _resolve_js_module_path(written_as) == target
|
||||
|
||||
|
||||
def test_end_to_end_multi_dot_import_resolves(tmp_path):
|
||||
"""End-to-end sanity for the multi-dot pattern via the import handler."""
|
||||
target = _write(tmp_path / "tag-action.shared.ts",
|
||||
"export const apply = () => {}")
|
||||
importer = _write(tmp_path / "page.ts",
|
||||
"import { apply } from './tag-action.shared'\n")
|
||||
result = extract_js(importer)
|
||||
expected = _make_id(str(target))
|
||||
assert expected in _import_targets(result), (
|
||||
f"Multi-dot import failed end-to-end; "
|
||||
f"expected {expected}; got {_import_targets(result)}"
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_chain_alias_and_extension_compose(tmp_path):
|
||||
"""Alias → bare path → .svelte.ts. Two layers of resolution must
|
||||
compose correctly: tsconfig alias maps `$lib/...` to a real dir,
|
||||
then extension resolution finds the actual file."""
|
||||
src = tmp_path / "src"
|
||||
target = _write(src / "lib" / "hooks" / "is-mobile.svelte.ts",
|
||||
"export const isMobile = () => true")
|
||||
_write(tmp_path / "tsconfig.json",
|
||||
'{"compilerOptions":{"paths":{"$lib":["./src/lib"],'
|
||||
'"$lib/*":["./src/lib/*"]}}}')
|
||||
importer = _write(src / "routes" / "page.ts",
|
||||
"import { isMobile } from '$lib/hooks/is-mobile.svelte'\n")
|
||||
result = extract_js(importer)
|
||||
expected = _make_id(str(target))
|
||||
assert expected in _import_targets(result), (
|
||||
f"Alias + .svelte→.svelte.ts chain failed to compose; "
|
||||
f"expected {expected}; got {_import_targets(result)}"
|
||||
)
|
||||
|
||||
|
||||
# ── End-to-end: dynamic_import in .svelte regex pass uses resolver ──────────
|
||||
|
||||
|
||||
def test_ts_dynamic_import_bare_path_resolves(tmp_path):
|
||||
"""Real-world repro: a TS file uses `await import('./foo')` (no extension)
|
||||
to lazy-load a sibling module. The dynamic-import handler in JS/TS files
|
||||
has its own copy of the resolution logic — distinct from the static-import
|
||||
handler and from the Svelte regex pass — and was missing the bare-path
|
||||
extension append, silently dropping every such edge."""
|
||||
target = _write(tmp_path / "profanity.ts",
|
||||
"export const hasProfanity = (s: string) => false")
|
||||
importer = _write(tmp_path / "auth-validators.ts", """\
|
||||
export async function validate(name: string) {
|
||||
const { hasProfanity } = await import('./profanity')
|
||||
return hasProfanity(name)
|
||||
}
|
||||
""")
|
||||
result = extract_js(importer)
|
||||
expected = _make_id(str(target))
|
||||
targets = {str(e.get("target") or "") for e in result["edges"]
|
||||
if e.get("relation") in ("imports", "imports_from")}
|
||||
assert expected in targets, (
|
||||
f"Bare-path TS dynamic import failed to resolve; "
|
||||
f"expected {expected}; got {targets}"
|
||||
)
|
||||
|
||||
|
||||
def test_ts_dynamic_import_alias_with_bare_path_resolves(tmp_path):
|
||||
"""The other branch of the dynamic-import handler — alias resolution —
|
||||
also needs the same fixups. `import('$lib/foo')` should resolve to
|
||||
`$lib/foo.ts` after both alias substitution and extension append."""
|
||||
src = tmp_path / "src"
|
||||
target = _write(src / "lib" / "lazy-module.ts", "export const x = 1")
|
||||
_write(tmp_path / "tsconfig.json",
|
||||
'{"compilerOptions":{"paths":{"$lib":["./src/lib"],'
|
||||
'"$lib/*":["./src/lib/*"]}}}')
|
||||
importer = _write(src / "routes" / "page.ts", """\
|
||||
export async function load() {
|
||||
const m = await import('$lib/lazy-module')
|
||||
return m.x
|
||||
}
|
||||
""")
|
||||
result = extract_js(importer)
|
||||
expected = _make_id(str(target))
|
||||
targets = {str(e.get("target") or "") for e in result["edges"]
|
||||
if e.get("relation") in ("imports", "imports_from")}
|
||||
assert expected in targets, (
|
||||
f"Alias + bare-path dynamic import failed to resolve; "
|
||||
f"expected {expected}; got {targets}"
|
||||
)
|
||||
|
||||
|
||||
def test_dynamic_import_bare_path_resolves(tmp_path):
|
||||
"""The regex pass for `import('...')` in .svelte files must also use
|
||||
the new resolver — otherwise dynamic imports of bare paths still
|
||||
produce phantom edges."""
|
||||
target = _write(tmp_path / "Heavy.svelte.ts",
|
||||
"export const heavy = () => 1")
|
||||
importer = _write(tmp_path / "page.svelte", """\
|
||||
<script>
|
||||
const lazy = () => import('./Heavy.svelte')
|
||||
</script>
|
||||
""")
|
||||
result = extract_svelte(importer)
|
||||
dyn_targets = {str(e.get("target") or "") for e in result["edges"]
|
||||
if e.get("relation") == "dynamic_import"}
|
||||
expected = _make_id(str(target))
|
||||
assert expected in dyn_targets, (
|
||||
f"dynamic_import of .svelte that's actually .svelte.ts must "
|
||||
f"resolve through the new resolver; "
|
||||
f"expected {expected}; got {dyn_targets}"
|
||||
)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Integration tests for incremental graphify extract behavior."""
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
PYTHON = sys.executable
|
||||
|
||||
|
||||
def _run(args: list[str], cwd: Path) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
[PYTHON, "-m", "graphify"] + args,
|
||||
cwd=cwd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def _make_docs_corpus(tmp_path: Path) -> Path:
|
||||
docs = tmp_path / "docs"
|
||||
docs.mkdir()
|
||||
(docs / "intro.md").write_text("# Introduction\nThis doc introduces the system.")
|
||||
(docs / "api.md").write_text("# API Reference\nThe API has endpoints.")
|
||||
return docs
|
||||
|
||||
|
||||
def test_manifest_written_after_extract(tmp_path):
|
||||
"""After a full extract run, manifest.json must exist (or run fails before writing it)."""
|
||||
docs = _make_docs_corpus(tmp_path)
|
||||
r = _run(["extract", str(docs)], tmp_path)
|
||||
# Should fail with no API key — but NOT with a path error
|
||||
assert "no LLM API key" in r.stderr or r.returncode != 0
|
||||
# manifest should NOT exist (run failed before writing)
|
||||
manifest = docs / "graphify-out" / "manifest.json"
|
||||
assert not manifest.exists()
|
||||
|
||||
|
||||
def test_incremental_mode_detected_via_manifest(tmp_path):
|
||||
"""If manifest.json + graph.json exist, incremental mode message is shown."""
|
||||
docs = _make_docs_corpus(tmp_path)
|
||||
out = docs / "graphify-out"
|
||||
out.mkdir()
|
||||
(out / "graph.json").write_text(json.dumps({"nodes": [], "links": []}))
|
||||
(out / "manifest.json").write_text(json.dumps({"document": [str(docs / "intro.md")]}))
|
||||
r = _run(["extract", str(docs)], tmp_path)
|
||||
combined = r.stdout + r.stderr
|
||||
assert "incremental" in combined.lower() or r.returncode != 0
|
||||
|
||||
|
||||
def test_no_incremental_without_manifest(tmp_path):
|
||||
"""Without manifest.json, full scan message is shown (not incremental)."""
|
||||
docs = _make_docs_corpus(tmp_path)
|
||||
r = _run(["extract", str(docs)], tmp_path)
|
||||
assert "incremental" not in r.stdout
|
||||
+406
-2
@@ -1,11 +1,12 @@
|
||||
"""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, Fortran, 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, extract_fortran,
|
||||
extract_groovy,
|
||||
)
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
@@ -25,6 +26,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 +66,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 +107,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 +142,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 +209,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 +260,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 +294,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():
|
||||
@@ -234,6 +332,20 @@ def test_php_finds_imports():
|
||||
r = extract_php(FIXTURES / "sample.php")
|
||||
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)
|
||||
@@ -319,6 +431,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"]}
|
||||
@@ -405,6 +524,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 ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -428,12 +553,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"]
|
||||
@@ -468,6 +607,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"]
|
||||
@@ -543,6 +689,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"]
|
||||
@@ -555,8 +708,259 @@ 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}"
|
||||
|
||||
|
||||
# ── Fortran extractor ────────────────────────────────────────────────────────
|
||||
|
||||
def test_fortran_finds_module():
|
||||
r = extract_fortran(FIXTURES / "sample.f90")
|
||||
assert "error" not in r
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert "geometry" in labels
|
||||
|
||||
|
||||
def test_fortran_finds_subroutines():
|
||||
r = extract_fortran(FIXTURES / "sample.f90")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert any("circle_area" in l for l in labels)
|
||||
assert any("print_area" in l for l in labels)
|
||||
|
||||
|
||||
def test_fortran_finds_function():
|
||||
r = extract_fortran(FIXTURES / "sample.f90")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert any("distance" in l for l in labels)
|
||||
|
||||
|
||||
def test_fortran_finds_program():
|
||||
r = extract_fortran(FIXTURES / "sample.f90")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert "main" in labels
|
||||
|
||||
|
||||
def test_fortran_finds_use_imports():
|
||||
r = extract_fortran(FIXTURES / "sample.f90")
|
||||
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
|
||||
assert len(import_edges) >= 2
|
||||
|
||||
|
||||
def test_fortran_use_edges_have_use_context():
|
||||
r = extract_fortran(FIXTURES / "sample.f90")
|
||||
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
|
||||
assert all(e.get("context") == "use" for e in import_edges)
|
||||
|
||||
|
||||
def test_fortran_finds_calls():
|
||||
r = extract_fortran(FIXTURES / "sample.f90")
|
||||
call_edges = [e for e in r["edges"] if e["relation"] == "calls"]
|
||||
assert len(call_edges) >= 1
|
||||
|
||||
|
||||
def test_fortran_case_insensitive_names():
|
||||
r = extract_fortran(FIXTURES / "sample.f90")
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert all(l == l.lower() or "(" in l for l in labels if l.endswith(("()", "")) and not "." in l)
|
||||
assert "geometry" in labels
|
||||
assert "main" in labels
|
||||
|
||||
|
||||
def test_fortran_no_dangling_edges():
|
||||
r = extract_fortran(FIXTURES / "sample.f90")
|
||||
node_ids = {n["id"] for n in r["nodes"]}
|
||||
for e in r["edges"]:
|
||||
assert e["source"] in node_ids, f"Dangling source: {e}"
|
||||
|
||||
|
||||
def test_fortran_capital_F_parses_preprocessed():
|
||||
r = extract_fortran(FIXTURES / "sample.F90")
|
||||
assert "error" not in r
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert "shapes" in labels
|
||||
assert any("compute_volume" in l for l in labels)
|
||||
|
||||
|
||||
# ── 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}"
|
||||
|
||||
|
||||
# ── Markdown ─────────────────────────────────────────────────────────────────
|
||||
|
||||
from graphify.extract import extract_markdown
|
||||
|
||||
def test_markdown_no_error():
|
||||
r = extract_markdown(FIXTURES / "deploy_guide.md")
|
||||
assert "error" not in r
|
||||
|
||||
def test_markdown_finds_headings():
|
||||
r = extract_markdown(FIXTURES / "deploy_guide.md")
|
||||
labels = _labels(r)
|
||||
assert any("Deploy Guide" in l for l in labels)
|
||||
assert any("Prerequisites" in l for l in labels)
|
||||
assert any("Full Deploy" in l for l in labels)
|
||||
assert any("Rollback" in l for l in labels)
|
||||
|
||||
def test_markdown_finds_nested_heading():
|
||||
"""### Database Migration is nested under ## Full Deploy."""
|
||||
r = extract_markdown(FIXTURES / "deploy_guide.md")
|
||||
labels = _labels(r)
|
||||
assert any("Database Migration" in l for l in labels)
|
||||
|
||||
def test_markdown_finds_code_blocks():
|
||||
r = extract_markdown(FIXTURES / "deploy_guide.md")
|
||||
labels = _labels(r)
|
||||
assert any("code:bash" in l for l in labels)
|
||||
assert any("code:sql" in l for l in labels)
|
||||
assert any("code:python" in l for l in labels)
|
||||
|
||||
def test_markdown_contains_edges():
|
||||
"""Headings and code blocks should be connected via 'contains' edges."""
|
||||
r = extract_markdown(FIXTURES / "deploy_guide.md")
|
||||
assert "contains" in _relations(r)
|
||||
contains_edges = [e for e in r["edges"] if e["relation"] == "contains"]
|
||||
assert len(contains_edges) >= 5 # file->h1, h1->h2s, h2->h3, h2->codeblocks
|
||||
|
||||
def test_markdown_no_dangling_edges():
|
||||
r = extract_markdown(FIXTURES / "deploy_guide.md")
|
||||
node_ids = {n["id"] for n in r["nodes"]}
|
||||
for e in r["edges"]:
|
||||
assert e["source"] in node_ids, f"Dangling source: {e}"
|
||||
|
||||
|
||||
# ── Groovy ───────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_groovy_no_error():
|
||||
r = extract_groovy(FIXTURES / "sample.groovy")
|
||||
assert "error" not in r
|
||||
|
||||
|
||||
def test_groovy_finds_class():
|
||||
r = extract_groovy(FIXTURES / "sample.groovy")
|
||||
assert any("SampleService" in l for l in _labels(r))
|
||||
|
||||
|
||||
def test_groovy_finds_methods():
|
||||
r = extract_groovy(FIXTURES / "sample.groovy")
|
||||
labels = _labels(r)
|
||||
assert any("process" in l for l in labels)
|
||||
assert any("reset" in l for l in labels)
|
||||
|
||||
|
||||
def test_groovy_finds_imports():
|
||||
r = extract_groovy(FIXTURES / "sample.groovy")
|
||||
assert "imports" in _relations(r)
|
||||
|
||||
|
||||
def test_groovy_import_edges_have_import_context():
|
||||
r = extract_groovy(FIXTURES / "sample.groovy")
|
||||
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_groovy_no_dangling_edges():
|
||||
r = extract_groovy(FIXTURES / "sample.groovy")
|
||||
node_ids = {n["id"] for n in r["nodes"]}
|
||||
for e in r["edges"]:
|
||||
assert e["source"] in node_ids
|
||||
|
||||
|
||||
def test_groovy_spock_finds_class():
|
||||
r = extract_groovy(FIXTURES / "sample_spock.groovy")
|
||||
assert any("SampleSpec" in l for l in _labels(r))
|
||||
|
||||
|
||||
def test_groovy_spock_finds_feature_methods():
|
||||
r = extract_groovy(FIXTURES / "sample_spock.groovy")
|
||||
feature_labels = [l for l in _labels(r) if l.startswith('"')]
|
||||
assert len(feature_labels) >= 2
|
||||
|
||||
|
||||
def test_groovy_spock_finds_method_with_apostrophe():
|
||||
r = extract_groovy(FIXTURES / "sample_spock.groovy")
|
||||
assert any("it's" in l for l in _labels(r))
|
||||
|
||||
|
||||
def test_groovy_spock_preserves_import_edges():
|
||||
r = extract_groovy(FIXTURES / "sample_spock.groovy")
|
||||
assert "imports" in _relations(r)
|
||||
|
||||
|
||||
def test_groovy_spock_no_dangling_edges():
|
||||
r = extract_groovy(FIXTURES / "sample_spock.groovy")
|
||||
node_ids = {n["id"] for n in r["nodes"]}
|
||||
for e in r["edges"]:
|
||||
assert e["source"] in node_ids
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Tests for direct semantic-extraction backend selection."""
|
||||
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify import llm
|
||||
|
||||
|
||||
def _clear_backend_env(monkeypatch):
|
||||
for env_key in (
|
||||
"GEMINI_API_KEY",
|
||||
"GOOGLE_API_KEY",
|
||||
"MOONSHOT_API_KEY",
|
||||
"ANTHROPIC_API_KEY",
|
||||
"OPENAI_API_KEY",
|
||||
):
|
||||
monkeypatch.delenv(env_key, raising=False)
|
||||
|
||||
|
||||
def test_gemini_accepts_gemini_api_key(monkeypatch):
|
||||
_clear_backend_env(monkeypatch)
|
||||
monkeypatch.setenv("GEMINI_API_KEY", "gemini-key")
|
||||
|
||||
assert llm.detect_backend() == "gemini"
|
||||
assert llm._get_backend_api_key("gemini") == "gemini-key"
|
||||
|
||||
|
||||
def test_gemini_accepts_google_api_key(monkeypatch):
|
||||
_clear_backend_env(monkeypatch)
|
||||
monkeypatch.setenv("GOOGLE_API_KEY", "google-key")
|
||||
|
||||
assert llm.detect_backend() == "gemini"
|
||||
assert llm._get_backend_api_key("gemini") == "google-key"
|
||||
|
||||
|
||||
def test_backend_detection_prefers_gemini(monkeypatch):
|
||||
_clear_backend_env(monkeypatch)
|
||||
monkeypatch.setenv("OPENAI_API_KEY", "openai-key")
|
||||
monkeypatch.setenv("ANTHROPIC_API_KEY", "anthropic-key")
|
||||
monkeypatch.setenv("MOONSHOT_API_KEY", "moonshot-key")
|
||||
monkeypatch.setenv("GEMINI_API_KEY", "gemini-key")
|
||||
|
||||
assert llm.detect_backend() == "gemini"
|
||||
|
||||
|
||||
def test_openai_backend_detected(monkeypatch):
|
||||
_clear_backend_env(monkeypatch)
|
||||
monkeypatch.setenv("OPENAI_API_KEY", "openai-key")
|
||||
|
||||
assert llm.detect_backend() == "openai"
|
||||
assert llm._get_backend_api_key("openai") == "openai-key"
|
||||
|
||||
|
||||
def test_extract_files_direct_routes_gemini_through_openai_compat(tmp_path, monkeypatch):
|
||||
_clear_backend_env(monkeypatch)
|
||||
monkeypatch.setenv("GOOGLE_API_KEY", "google-key")
|
||||
source = tmp_path / "note.md"
|
||||
source.write_text("# Architecture\n\nThe runner emits a snapshot.\n")
|
||||
result = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 1, "output_tokens": 1}
|
||||
|
||||
with patch("graphify.llm._call_openai_compat", return_value=result) as call:
|
||||
assert llm.extract_files_direct([source], backend="gemini", root=tmp_path) is result
|
||||
|
||||
assert call.call_args.args[:4] == (
|
||||
"https://generativelanguage.googleapis.com/v1beta/openai/",
|
||||
"google-key",
|
||||
"gemini-3-flash-preview",
|
||||
"=== note.md ===\n# Architecture\n\nThe runner emits a snapshot.\n",
|
||||
)
|
||||
assert call.call_args.kwargs["temperature"] == 0
|
||||
assert call.call_args.kwargs["reasoning_effort"] == "low"
|
||||
assert call.call_args.kwargs["max_completion_tokens"] == 16384
|
||||
|
||||
|
||||
def test_gemini_model_can_be_overridden_by_env(tmp_path, monkeypatch):
|
||||
_clear_backend_env(monkeypatch)
|
||||
monkeypatch.setenv("GOOGLE_API_KEY", "google-key")
|
||||
monkeypatch.setenv("GRAPHIFY_GEMINI_MODEL", "gemini-3.1-pro-preview")
|
||||
source = tmp_path / "note.md"
|
||||
source.write_text("# Architecture\n")
|
||||
result = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 1, "output_tokens": 1}
|
||||
|
||||
with patch("graphify.llm._call_openai_compat", return_value=result) as call:
|
||||
llm.extract_files_direct([source], backend="gemini", root=tmp_path)
|
||||
|
||||
assert call.call_args.args[2] == "gemini-3.1-pro-preview"
|
||||
|
||||
|
||||
def test_missing_gemini_key_names_both_supported_env_vars(monkeypatch):
|
||||
_clear_backend_env(monkeypatch)
|
||||
|
||||
with pytest.raises(ValueError) as exc:
|
||||
llm.extract_files_direct([Path("missing.md")], backend="gemini")
|
||||
|
||||
assert "GEMINI_API_KEY or GOOGLE_API_KEY" in str(exc.value)
|
||||
+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']}"
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Tests for the Ollama backend additions in graphify/llm.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
from graphify.llm import detect_backend, BACKENDS
|
||||
|
||||
|
||||
def test_ollama_in_backends():
|
||||
assert "ollama" in BACKENDS
|
||||
assert BACKENDS["ollama"]["pricing"]["input"] == 0.0
|
||||
assert BACKENDS["ollama"]["pricing"]["output"] == 0.0
|
||||
assert "max_tokens" in BACKENDS["ollama"]
|
||||
|
||||
|
||||
def test_detect_backend_ollama(monkeypatch):
|
||||
monkeypatch.delenv("MOONSHOT_API_KEY", raising=False)
|
||||
monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
|
||||
monkeypatch.setenv("OLLAMA_BASE_URL", "http://localhost:11434/v1")
|
||||
assert detect_backend() == "ollama"
|
||||
|
||||
|
||||
def test_detect_backend_kimi_beats_ollama(monkeypatch):
|
||||
monkeypatch.setenv("MOONSHOT_API_KEY", "test-key")
|
||||
monkeypatch.setenv("OLLAMA_BASE_URL", "http://localhost:11434/v1")
|
||||
monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
|
||||
assert detect_backend() == "kimi"
|
||||
|
||||
|
||||
def test_detect_backend_ollama_beats_claude(monkeypatch):
|
||||
monkeypatch.delenv("MOONSHOT_API_KEY", raising=False)
|
||||
monkeypatch.setenv("OLLAMA_BASE_URL", "http://localhost:11434/v1")
|
||||
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-test")
|
||||
assert detect_backend() == "ollama"
|
||||
|
||||
|
||||
def test_detect_backend_none_without_envvars(monkeypatch):
|
||||
monkeypatch.delenv("MOONSHOT_API_KEY", raising=False)
|
||||
monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)
|
||||
monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
|
||||
assert detect_backend() is None
|
||||
|
||||
|
||||
def test_ollama_api_key_sentinel(monkeypatch):
|
||||
"""extract_files_direct with backend=ollama and no OLLAMA_API_KEY should use sentinel 'ollama' not raise."""
|
||||
monkeypatch.delenv("OLLAMA_API_KEY", raising=False)
|
||||
from unittest.mock import patch
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
|
||||
fake_result = {
|
||||
"nodes": [],
|
||||
"edges": [],
|
||||
"hyperedges": [],
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 10,
|
||||
"finish_reason": "stop",
|
||||
}
|
||||
with patch("graphify.llm._call_openai_compat", return_value=fake_result) as mock_call:
|
||||
from graphify.llm import extract_files_direct
|
||||
with tempfile.NamedTemporaryFile(suffix=".py", mode="w", delete=False) as f:
|
||||
f.write("x = 1\n")
|
||||
tmp = Path(f.name)
|
||||
try:
|
||||
extract_files_direct([tmp], backend="ollama", root=tmp.parent)
|
||||
# Should have called _call_openai_compat with api_key="ollama"
|
||||
assert mock_call.called
|
||||
call_kwargs = mock_call.call_args
|
||||
api_key_used = call_kwargs.args[1] if call_kwargs.args else call_kwargs.kwargs.get("api_key", "")
|
||||
assert api_key_used == "ollama"
|
||||
finally:
|
||||
tmp.unlink(missing_ok=True)
|
||||
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user